blob: acd49d5b455dc1710d392ee51d78b9935ffb9afa [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"
David Srbeckyb73323c2018-07-15 23:58:44 +010029#include "base/indenter.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080030#include "base/logging.h" // For VLOG
David Sehrc431b9d2018-03-02 12:01:51 -080031#include "base/os.h"
David Sehr67bf42e2018-02-26 16:43:04 -080032#include "base/safe_map.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080033#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080034#include "base/unix_file/fd_file.h"
David Sehr79e26072018-04-06 17:58:50 -070035#include "base/zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070036#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010037#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010038#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000039#include "debug/method_debug_info.h"
David Sehr013fd802018-01-11 22:55:24 -080040#include "dex/art_dex_file_loader.h"
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -070041#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080042#include "dex/dex_file-inl.h"
43#include "dex/dex_file_loader.h"
44#include "dex/dex_file_types.h"
45#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070046#include "dex/type_lookup_table.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000047#include "dex/verification_results.h"
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080048#include "dex_container.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070049#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070050#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000051#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010052#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070053#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030054#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010055#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010056#include "linker/buffered_output_stream.h"
57#include "linker/file_output_stream.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000058#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010059#include "linker/linker_patch.h"
Vladimir Marko944da602016-02-19 12:27:55 +000060#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000061#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/array.h"
63#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010064#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070065#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010066#include "oat_quick_method_header.h"
David Sehr82d046e2018-04-23 08:14:19 -070067#include "profile/profile_compilation_info.h"
Mathieu Chartier210531f2018-01-12 10:15:51 -080068#include "quicken_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070069#include "scoped_thread_state_change-inl.h"
David Srbeckyb73323c2018-07-15 23:58:44 +010070#include "stack_map.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010071#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010072#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010073#include "verifier/verifier_deps.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070074
75namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000076namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070077
Vladimir Marko9bdf1082016-01-21 12:15:52 +000078namespace { // anonymous namespace
79
Mathieu Chartier120aa282017-08-05 16:03:03 -070080// If we write dex layout info in the oat file.
81static constexpr bool kWriteDexLayoutInfo = true;
82
Igor Murashkin545412b2017-08-17 15:26:54 -070083// Force the OAT method layout to be sorted-by-name instead of
84// the default (class_def_idx, method_idx).
85//
86// Otherwise if profiles are used, that will act as
87// the primary sort order.
88//
89// A bit easier to use for development since oatdump can easily
90// show that things are being re-ordered when two methods aren't adjacent.
91static constexpr bool kOatWriterForceOatCodeLayout = false;
92
93static constexpr bool kOatWriterDebugOatCodeLayout = false;
94
Andreas Gampec55bb392018-09-21 00:02:02 +000095using UnalignedDexFileHeader __attribute__((__aligned__(1))) = DexFile::Header;
Vladimir Marko9bdf1082016-01-21 12:15:52 +000096
97const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
Andreas Gampec55bb392018-09-21 00:02:02 +000098 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
Vladimir Marko9bdf1082016-01-21 12:15:52 +000099}
100
Vladimir Markoe079e212016-05-25 12:49:49 +0100101class ChecksumUpdatingOutputStream : public OutputStream {
102 public:
103 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
104 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
105
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100106 bool WriteFully(const void* buffer, size_t byte_count) override {
Vladimir Markoe079e212016-05-25 12:49:49 +0100107 oat_header_->UpdateChecksum(buffer, byte_count);
108 return out_->WriteFully(buffer, byte_count);
109 }
110
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100111 off_t Seek(off_t offset, Whence whence) override {
Vladimir Markoe079e212016-05-25 12:49:49 +0100112 return out_->Seek(offset, whence);
113 }
114
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100115 bool Flush() override {
Vladimir Markoe079e212016-05-25 12:49:49 +0100116 return out_->Flush();
117 }
118
119 private:
120 OutputStream* const out_;
121 OatHeader* const oat_header_;
122};
123
Vladimir Marko0c737df2016-08-01 16:33:16 +0100124inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
125 // We want to align the code rather than the preheader.
126 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
127 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
128 return aligned_code_offset - unaligned_code_offset;
129}
130
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000131} // anonymous namespace
132
133// Defines the location of the raw dex file to write.
134class OatWriter::DexFileSource {
135 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800136 enum Type {
137 kNone,
138 kZipEntry,
139 kRawFile,
140 kRawData,
141 };
142
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000143 explicit DexFileSource(ZipEntry* zip_entry)
144 : type_(kZipEntry), source_(zip_entry) {
145 DCHECK(source_ != nullptr);
146 }
147
148 explicit DexFileSource(File* raw_file)
149 : type_(kRawFile), source_(raw_file) {
150 DCHECK(source_ != nullptr);
151 }
152
153 explicit DexFileSource(const uint8_t* dex_file)
154 : type_(kRawData), source_(dex_file) {
155 DCHECK(source_ != nullptr);
156 }
157
Mathieu Chartier497d5262017-02-28 20:17:30 -0800158 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000159 bool IsZipEntry() const { return type_ == kZipEntry; }
160 bool IsRawFile() const { return type_ == kRawFile; }
161 bool IsRawData() const { return type_ == kRawData; }
162
163 ZipEntry* GetZipEntry() const {
164 DCHECK(IsZipEntry());
165 DCHECK(source_ != nullptr);
166 return static_cast<ZipEntry*>(const_cast<void*>(source_));
167 }
168
169 File* GetRawFile() const {
170 DCHECK(IsRawFile());
171 DCHECK(source_ != nullptr);
172 return static_cast<File*>(const_cast<void*>(source_));
173 }
174
175 const uint8_t* GetRawData() const {
176 DCHECK(IsRawData());
177 DCHECK(source_ != nullptr);
178 return static_cast<const uint8_t*>(source_);
179 }
180
181 void Clear() {
182 type_ = kNone;
183 source_ = nullptr;
184 }
185
186 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000187 Type type_;
188 const void* source_;
189};
190
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700191// OatClassHeader is the header only part of the oat class that is required even when compilation
192// is not enabled.
193class OatWriter::OatClassHeader {
194 public:
195 OatClassHeader(uint32_t offset,
196 uint32_t num_non_null_compiled_methods,
197 uint32_t num_methods,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000198 ClassStatus status)
199 : status_(enum_cast<uint16_t>(status)),
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700200 offset_(offset) {
201 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
202 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
203 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
204 if (num_non_null_compiled_methods == 0) {
205 type_ = kOatClassNoneCompiled;
206 } else if (num_non_null_compiled_methods == num_methods) {
207 type_ = kOatClassAllCompiled;
208 } else {
209 type_ = kOatClassSomeCompiled;
210 }
211 }
212
213 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
214
215 static size_t SizeOf() {
216 return sizeof(status_) + sizeof(type_);
217 }
218
219 // Data to write.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000220 static_assert(enum_cast<>(ClassStatus::kLast) < (1 << 16), "class status won't fit in 16bits");
221 uint16_t status_;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700222
223 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
224 uint16_t type_;
225
226 // Offset of start of OatClass from beginning of OatHeader. It is
227 // used to validate file position when writing.
228 uint32_t offset_;
229};
230
231// The actual oat class body contains the information about compiled methods. It is only required
232// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000233class OatWriter::OatClass {
234 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700235 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100236 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700237 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000238 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000239 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700240 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000241
242 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
243 return compiled_methods_[class_def_method_index];
244 }
245
Vladimir Marko49b0f452015-12-10 13:49:19 +0000246 // CompiledMethods for each class_def_method_index, or null if no method is available.
247 dchecked_vector<CompiledMethod*> compiled_methods_;
248
249 // Offset from OatClass::offset_ to the OatMethodOffsets for the
250 // class_def_method_index. If 0, it means the corresponding
251 // CompiledMethod entry in OatClass::compiled_methods_ should be
252 // null and that the OatClass::type_ should be kOatClassBitmap.
253 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
254
255 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000256 uint32_t method_bitmap_size_;
257
258 // bit vector indexed by ClassDef method index. When
259 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
260 // method has an OatMethodOffsets in methods_offsets_, otherwise
261 // the entry was ommited to save space. If OatClassType::type_ is
262 // not is kOatClassBitmap, the bitmap will be null.
263 std::unique_ptr<BitVector> method_bitmap_;
264
265 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
266 // present in the OatClass. Note that some may be missing if
267 // OatClass::compiled_methods_ contains null values (and
268 // oat_method_offsets_offsets_from_oat_class_ should contain 0
269 // values in this case).
270 dchecked_vector<OatMethodOffsets> method_offsets_;
271 dchecked_vector<OatQuickMethodHeader> method_headers_;
272
273 private:
274 size_t GetMethodOffsetsRawSize() const {
275 return method_offsets_.size() * sizeof(method_offsets_[0]);
276 }
277
278 DISALLOW_COPY_AND_ASSIGN(OatClass);
279};
280
281class OatWriter::OatDexFile {
282 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000283 OatDexFile(const char* dex_file_location,
284 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000285 CreateTypeLookupTable create_type_lookup_table,
286 uint32_t dex_file_location_checksun,
287 size_t dex_file_size);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000288 OatDexFile(OatDexFile&& src) = default;
289
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000290 const char* GetLocation() const {
291 return dex_file_location_data_;
292 }
293
Vladimir Marko49b0f452015-12-10 13:49:19 +0000294 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000295 bool Write(OatWriter* oat_writer, OutputStream* out) const;
296 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
297
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100298 size_t GetClassOffsetsRawSize() const {
299 return class_offsets_.size() * sizeof(class_offsets_[0]);
300 }
301
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000302 // The source of the dex file.
303 DexFileSource source_;
304
305 // Whether to create the type lookup table.
306 CreateTypeLookupTable create_type_lookup_table_;
307
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000308 // Dex file size. Passed in the constructor, but could be
309 // overwritten by LayoutAndWriteDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000310 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000311
312 // Offset of start of OatDexFile from beginning of OatHeader. It is
313 // used to validate file position when writing.
314 size_t offset_;
315
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000316 ///// Start of data to write to vdex/oat file.
317
318 const uint32_t dex_file_location_size_;
319 const char* const dex_file_location_data_;
320
321 // The checksum of the dex file.
322 const uint32_t dex_file_location_checksum_;
323
324 // Offset of the dex file in the vdex file. Set when writing dex files in
325 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000326 uint32_t dex_file_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000327
328 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000329 uint32_t lookup_table_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000330
331 // Class and BSS offsets set in PrepareLayout.
332 uint32_t class_offsets_offset_;
Nicolas Geoffray715d6722017-11-20 22:28:46 +0000333 uint32_t method_bss_mapping_offset_;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000334 uint32_t type_bss_mapping_offset_;
335 uint32_t string_bss_mapping_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000336
337 // Offset of dex sections that will have different runtime madvise states.
338 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700339 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000340
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000341 // Data to write to a separate section. We set the length
342 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000343 dchecked_vector<uint32_t> class_offsets_;
344
Mathieu Chartier120aa282017-08-05 16:03:03 -0700345 // Dex section layout info to serialize.
346 DexLayoutSections dex_sections_layout_;
347
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000348 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000349 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000350 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
351};
352
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100353#define DCHECK_OFFSET() \
354 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
355 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
356
357#define DCHECK_OFFSET_() \
358 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
359 << "file_offset=" << file_offset << " offset_=" << offset_
360
Vladimir Markoa0431112018-06-25 09:32:54 +0100361OatWriter::OatWriter(const CompilerOptions& compiler_options,
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700362 TimingLogger* timings,
363 ProfileCompilationInfo* info,
364 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000365 : write_state_(WriteState::kAddingDexFileSources),
366 timings_(timings),
367 raw_dex_files_(),
368 zip_archives_(),
369 zipped_dex_files_(),
370 zipped_dex_file_locations_(),
371 compiler_driver_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100372 compiler_options_(compiler_options),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000373 image_writer_(nullptr),
Mathieu Chartier792111c2018-02-15 13:02:15 -0800374 extract_dex_files_into_vdex_(true),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000375 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100376 vdex_size_(0u),
377 vdex_dex_files_offset_(0u),
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800378 vdex_dex_shared_data_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100379 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100380 vdex_quickening_info_offset_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000381 code_size_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100382 oat_size_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000383 data_bimg_rel_ro_start_(0u),
384 data_bimg_rel_ro_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000385 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000386 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100387 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000388 bss_roots_offset_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000389 data_bimg_rel_ro_entries_(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100390 bss_method_entry_references_(),
391 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000392 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000393 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100394 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700395 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100396 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000397 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700398 size_dex_file_alignment_(0),
399 size_executable_offset_alignment_(0),
400 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700401 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700402 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100403 size_verifier_deps_(0),
404 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100405 size_quickening_info_(0),
406 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700407 size_interpreter_to_interpreter_bridge_(0),
408 size_interpreter_to_compiled_code_bridge_(0),
409 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800410 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700411 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700412 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700413 size_quick_to_interpreter_bridge_(0),
414 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100415 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700416 size_code_(0),
417 size_code_alignment_(0),
Vladimir Markob066d432018-01-03 13:14:37 +0000418 size_data_bimg_rel_ro_(0),
419 size_data_bimg_rel_ro_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100420 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100421 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700422 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700423 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700424 size_oat_dex_file_location_size_(0),
425 size_oat_dex_file_location_data_(0),
426 size_oat_dex_file_location_checksum_(0),
427 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000428 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000429 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700430 size_oat_dex_file_dex_layout_sections_offset_(0),
431 size_oat_dex_file_dex_layout_sections_(0),
432 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100433 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000434 size_oat_dex_file_type_bss_mapping_offset_(0),
435 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000436 size_oat_lookup_table_alignment_(0),
437 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000438 size_oat_class_offsets_alignment_(0),
439 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700440 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700441 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700442 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100443 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100444 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000445 size_type_bss_mappings_(0u),
446 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000447 relative_patcher_(nullptr),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700448 profile_compilation_info_(info),
449 compact_dex_level_(compact_dex_level) {
Mathieu Chartierddf39552018-04-03 10:22:27 -0700450 // If we have a profile, always use at least the default compact dex level. The reason behind
451 // this is that CompactDex conversion is not more expensive than normal dexlayout.
452 if (info != nullptr && compact_dex_level_ == CompactDexLevel::kCompactDexLevelNone) {
453 compact_dex_level_ = kDefaultCompactDexLevel;
454 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000455}
456
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000457static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
458 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
459 if (!valid_standard_dex_magic) {
460 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
461 return false;
462 }
463 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
464 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
465 return false;
466 }
467 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
468 if (header->file_size_ < sizeof(DexFile::Header)) {
469 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
470 << " File: " << location;
471 return false;
472 }
473 return true;
474}
475
476static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
477 uint8_t* raw_header,
478 const char* location) {
479 // Read the dex file header and perform minimal verification.
480 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
481 PLOG(ERROR) << "Failed to read dex file header. Actual: "
482 << " File: " << location << " Output: " << file->GetPath();
483 return nullptr;
484 }
485 if (!ValidateDexFileHeader(raw_header, location)) {
486 return nullptr;
487 }
488
489 return AsUnalignedDexFileHeader(raw_header);
490}
491
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492bool OatWriter::AddDexFileSource(const char* filename,
493 const char* location,
494 CreateTypeLookupTable create_type_lookup_table) {
495 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
496 uint32_t magic;
497 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700498 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
499 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000500 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
501 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700502 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000503 uint8_t raw_header[sizeof(DexFile::Header)];
504 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
505 if (header == nullptr) {
506 return false;
507 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000508 // The file is open for reading, not writing, so it's OK to let the File destructor
509 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700510 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000511 oat_dex_files_.emplace_back(/* OatDexFile */
512 location,
513 DexFileSource(raw_dex_files_.back().get()),
514 create_type_lookup_table,
515 header->checksum_,
516 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000517 } else if (IsZipMagic(magic)) {
518 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
519 return false;
520 }
521 } else {
522 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
523 return false;
524 }
525 return true;
526}
527
528// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700529bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530 const char* location,
531 CreateTypeLookupTable create_type_lookup_table) {
532 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
533 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700534 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000535 ZipArchive* zip_archive = zip_archives_.back().get();
536 if (zip_archive == nullptr) {
537 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
538 << error_msg;
539 return false;
540 }
541 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700542 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
544 if (entry == nullptr) {
545 break;
546 }
547 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700548 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000549 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000550 // We override the checksum from header with the CRC from ZIP entry.
551 oat_dex_files_.emplace_back(/* OatDexFile */
552 full_location,
553 DexFileSource(zipped_dex_files_.back().get()),
554 create_type_lookup_table,
555 zipped_dex_files_.back()->GetCrc32(),
556 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 }
558 if (zipped_dex_file_locations_.empty()) {
559 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
560 return false;
561 }
562 return true;
563}
564
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000565// Add dex file source(s) from a vdex file specified by a file handle.
566bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
567 const char* location,
568 CreateTypeLookupTable create_type_lookup_table) {
569 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000570 DCHECK(vdex_file.HasDexSection());
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000571 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000572 for (size_t i = 0; i < vdex_file.GetVerifierDepsHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000573 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
574 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000575 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
576 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000577 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700578
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700579 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000580 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
581 return false;
582 }
583 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700584 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000585 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000586 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
587 oat_dex_files_.emplace_back(/* OatDexFile */
588 full_location,
589 DexFileSource(current_dex_data),
590 create_type_lookup_table,
591 vdex_file.GetLocationChecksum(i),
592 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000593 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000594
595 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
596 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
597 return false;
598 }
599
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000600 if (oat_dex_files_.empty()) {
601 LOG(ERROR) << "No dex files in vdex file created from " << location;
602 return false;
603 }
604 return true;
605}
606
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000607// Add dex file source from raw memory.
608bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
609 const char* location,
610 uint32_t location_checksum,
611 CreateTypeLookupTable create_type_lookup_table) {
612 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
613 if (data.size() < sizeof(DexFile::Header)) {
614 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
615 << data.size() << " File: " << location;
616 return false;
617 }
618 if (!ValidateDexFileHeader(data.data(), location)) {
619 return false;
620 }
621 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
622 if (data.size() < header->file_size_) {
623 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
624 << " file size from header: " << header->file_size_ << " File: " << location;
625 return false;
626 }
627
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000628 oat_dex_files_.emplace_back(/* OatDexFile */
629 location,
630 DexFileSource(data.data()),
631 create_type_lookup_table,
632 location_checksum,
633 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000634 return true;
635}
636
Calin Juravle1ce70852017-06-28 10:59:03 -0700637dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
638 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000639 locations.reserve(oat_dex_files_.size());
640 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
641 locations.push_back(oat_dex_file.GetLocation());
642 }
643 return locations;
644}
645
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700646bool OatWriter::MayHaveCompiledMethods() const {
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100647 return GetCompilerOptions().IsAnyCompilationEnabled();
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700648}
649
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000650bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100651 File* vdex_file,
652 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000653 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800654 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000655 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +0000656 CopyOption copy_dex_files,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100657 /*out*/ std::vector<MemMap>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000658 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
659 CHECK(write_state_ == WriteState::kAddingDexFileSources);
660
David Brazdil7b49e6c2016-09-01 11:06:18 +0100661 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
662 if (!RecordOatDataOffset(oat_rodata)) {
663 return false;
664 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000665
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100666 std::vector<MemMap> dex_files_map;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000667 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100668
669 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000670
671 // Reserve space for Vdex header and checksums.
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000672 vdex_size_ = sizeof(VdexFile::VerifierDepsHeader) +
673 oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Markoa0431112018-06-25 09:32:54 +0100674 oat_size_ = InitOatHeader(dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100675 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100676
677 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
678
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000679 std::unique_ptr<BufferedOutputStream> vdex_out =
680 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
681 // Write DEX files into VDEX, mmap and open them.
Mathieu Chartier792111c2018-02-15 13:02:15 -0800682 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex, copy_dex_files) ||
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000683 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
684 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000685 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000686
Mathieu Chartier120aa282017-08-05 16:03:03 -0700687 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000688 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
689 return false;
690 }
691
Mathieu Chartier120aa282017-08-05 16:03:03 -0700692 // Write dex layout sections into the oat file.
693 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
694 return false;
695 }
696
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000697 *opened_dex_files_map = std::move(dex_files_map);
698 *opened_dex_files = std::move(dex_files);
699 write_state_ = WriteState::kPrepareLayout;
700 return true;
701}
702
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100703// Initialize the writer with the given parameters.
704void OatWriter::Initialize(const CompilerDriver* compiler_driver,
705 ImageWriter* image_writer,
706 const std::vector<const DexFile*>& dex_files) {
707 compiler_driver_ = compiler_driver;
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100708 image_writer_ = image_writer;
709 dex_files_ = &dex_files;
710}
711
Vladimir Marko74527972016-11-29 15:57:32 +0000712void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000713 CHECK(write_state_ == WriteState::kPrepareLayout);
714
Vladimir Marko944da602016-02-19 12:27:55 +0000715 relative_patcher_ = relative_patcher;
716 SetMultiOatRelativePatcherAdjustment();
717
Vladimir Markoa0431112018-06-25 09:32:54 +0100718 if (GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000719 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800720 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100721 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000722 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100723
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100724 {
725 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
726 InitBssLayout(instruction_set);
727 }
728
David Brazdil7b49e6c2016-09-01 11:06:18 +0100729 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800730 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100731 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
732 offset = InitClassOffsets(offset);
733 }
734 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000735 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800736 offset = InitOatClasses(offset);
737 }
738 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000739 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
740 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100741 }
742 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000743 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100744 offset = InitOatMaps(offset);
745 }
746 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100747 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
748 oat_header_->SetOatDexFilesOffset(offset);
749 offset = InitOatDexFiles(offset);
750 }
751 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000752 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800753 offset = InitOatCode(offset);
754 }
755 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000756 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800757 offset = InitOatCodeDexFiles(offset);
Vladimir Markob066d432018-01-03 13:14:37 +0000758 code_size_ = offset - GetOatHeader().GetExecutableOffset();
Ian Rogersca368cb2013-11-15 15:52:08 -0800759 }
Vladimir Markob066d432018-01-03 13:14:37 +0000760 {
761 TimingLogger::ScopedTiming split("InitDataBimgRelRoLayout", timings_);
762 offset = InitDataBimgRelRoLayout(offset);
763 }
764 oat_size_ = offset; // .bss does not count towards oat_size_.
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100765 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100766
Brian Carlstrome24fa612011-09-29 00:53:55 -0700767 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Markoa0431112018-06-25 09:32:54 +0100768 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800769 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000770 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800771 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000772
773 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700774}
775
Ian Rogers0571d352011-11-03 19:51:38 -0700776OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700777}
778
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100779class OatWriter::DexMethodVisitor {
780 public:
781 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100782 : writer_(writer),
783 offset_(offset),
784 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700785 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100786
787 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
788 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700789 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100790 dex_file_ = dex_file;
791 class_def_index_ = class_def_index;
792 return true;
793 }
794
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -0700795 virtual bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100796
797 virtual bool EndClass() {
798 if (kIsDebugBuild) {
799 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700800 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100801 }
802 return true;
803 }
804
805 size_t GetOffset() const {
806 return offset_;
807 }
808
809 protected:
810 virtual ~DexMethodVisitor() { }
811
812 OatWriter* const writer_;
813
814 // The offset is usually advanced for each visited method by the derived class.
815 size_t offset_;
816
817 // The dex file and class def index are set in StartClass().
818 const DexFile* dex_file_;
819 size_t class_def_index_;
820};
821
822class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
823 public:
824 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100825 : DexMethodVisitor(writer, offset),
826 oat_class_index_(0u),
827 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100828
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100829 bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100830 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700831 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
832 // There are no oat classes if there aren't any compiled methods.
833 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
834 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100835 method_offsets_index_ = 0u;
836 return true;
837 }
838
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100839 bool EndClass() override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100840 ++oat_class_index_;
841 return DexMethodVisitor::EndClass();
842 }
843
844 protected:
845 size_t oat_class_index_;
846 size_t method_offsets_index_;
847};
848
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100849static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000850 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100851}
852
853static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000854 // The dextodexcompiler puts the quickening info table into the CompiledMethod
855 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100856 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
857}
858
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100859class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
860 public:
861 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
862 : DexMethodVisitor(writer, /* offset */ 0u) {}
863
864 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100865 const ClassAccessor::Method& method) override {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100866 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
867 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -0700868 MethodReference(dex_file_, method.GetIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100869 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100870 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Markob066d432018-01-03 13:14:37 +0000871 if (patch.GetType() == LinkerPatch::Type::kDataBimgRelRo) {
872 writer_->data_bimg_rel_ro_entries_.Overwrite(patch.BootImageOffset(),
873 /* placeholder */ 0u);
874 } else if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100875 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000876 AddBssReference(target_method,
877 target_method.dex_file->NumMethodIds(),
878 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100879 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
880 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000881 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
882 AddBssReference(target_type,
883 target_type.dex_file->NumTypeIds(),
884 &writer_->bss_type_entry_references_);
885 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100886 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000887 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
888 AddBssReference(target_string,
889 target_string.dex_file->NumStringIds(),
890 &writer_->bss_string_entry_references_);
891 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100892 }
893 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100894 } else {
895 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100896 }
897 return true;
898 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000899
900 private:
901 void AddBssReference(const DexFileReference& ref,
902 size_t number_of_indexes,
903 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
904 // We currently support inlining of throwing instructions only when they originate in the
905 // same dex file as the outer method. All .bss references are used by throwing instructions.
906 DCHECK_EQ(dex_file_, ref.dex_file);
907
908 auto refs_it = references->find(ref.dex_file);
909 if (refs_it == references->end()) {
910 refs_it = references->Put(
911 ref.dex_file,
912 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
913 refs_it->second.ClearAllBits();
914 }
915 refs_it->second.SetBit(ref.index);
916 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100917};
918
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100919class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
920 public:
921 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100922 : DexMethodVisitor(writer, offset),
923 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100924 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000925 size_t num_classes = 0u;
926 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
927 num_classes += oat_dex_file.class_offsets_.size();
928 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700929 // If we aren't compiling only reserve headers.
930 writer_->oat_class_headers_.reserve(num_classes);
931 if (writer->MayHaveCompiledMethods()) {
932 writer->oat_classes_.reserve(num_classes);
933 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100934 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100935 // If there are any classes, the class offsets allocation aligns the offset.
936 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100937 }
938
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100939 bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100940 DexMethodVisitor::StartClass(dex_file, class_def_index);
941 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100942 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100943 return true;
944 }
945
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300946 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100947 const ClassAccessor::Method& method) override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100948 // Fill in the compiled_methods_ array for methods that have a
949 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100950 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100951 // OatMethodOffsets for the compiled methods.
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -0700952 uint32_t method_idx = method.GetIndex();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100953 CompiledMethod* compiled_method =
954 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
955 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100956 if (HasCompiledCode(compiled_method)) {
957 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100958 }
959 return true;
960 }
961
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100962 bool EndClass() override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko2c64a832018-01-04 11:31:56 +0000964 ClassStatus status;
Andreas Gampebb846102017-05-11 21:03:35 -0700965 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
966 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700967 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
968 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700969 // The oat class status is used only for verification of resolved classes,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000970 // so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
Andreas Gampebb846102017-05-11 21:03:35 -0700971 // during compile-time verification.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000972 status = ClassStatus::kErrorResolved;
Andreas Gampebb846102017-05-11 21:03:35 -0700973 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +0000974 status = ClassStatus::kNotReady;
Andreas Gampebb846102017-05-11 21:03:35 -0700975 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100976 }
977
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700978 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100979 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700980 compiled_methods_.size(),
981 status);
982 OatClassHeader& header = writer_->oat_class_headers_.back();
983 offset_ += header.SizeOf();
984 if (writer_->MayHaveCompiledMethods()) {
985 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100986 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700987 header.type_);
988 offset_ += writer_->oat_classes_.back().SizeOf();
989 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100990 return DexMethodVisitor::EndClass();
991 }
992
993 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000994 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100995 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100996};
997
Igor Murashkin545412b2017-08-17 15:26:54 -0700998// CompiledMethod + metadata required to do ordered method layout.
999//
1000// See also OrderedMethodVisitor.
1001struct OatWriter::OrderedMethodData {
1002 ProfileCompilationInfo::MethodHotness method_hotness;
1003 OatClass* oat_class;
1004 CompiledMethod* compiled_method;
1005 MethodReference method_reference;
1006 size_t method_offsets_index;
1007
1008 size_t class_def_index;
1009 uint32_t access_flags;
1010 const DexFile::CodeItem* code_item;
1011
1012 // A value of -1 denotes missing debug info
1013 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
1014 // Index into writer_->method_info_
1015 size_t debug_info_idx;
1016
1017 bool HasDebugInfo() const {
1018 return debug_info_idx != kDebugInfoIdxInvalid;
1019 }
1020
1021 // Bin each method according to the profile flags.
1022 //
1023 // Groups by e.g.
1024 // -- not hot at all
1025 // -- hot
1026 // -- hot and startup
1027 // -- hot and post-startup
1028 // -- hot and startup and poststartup
1029 // -- startup
1030 // -- startup and post-startup
1031 // -- post-startup
1032 //
1033 // (See MethodHotness enum definition for up-to-date binning order.)
1034 bool operator<(const OrderedMethodData& other) const {
1035 if (kOatWriterForceOatCodeLayout) {
1036 // Development flag: Override default behavior by sorting by name.
1037
1038 std::string name = method_reference.PrettyMethod();
1039 std::string other_name = other.method_reference.PrettyMethod();
1040 return name < other_name;
1041 }
1042
1043 // Use the profile's method hotness to determine sort order.
1044 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1045 return true;
1046 }
1047
1048 // Default: retain the original order.
1049 return false;
1050 }
1051
1052 private:
1053 // Used to determine relative order for OAT code layout when determining
1054 // binning.
1055 size_t GetMethodHotnessOrder() const {
1056 bool hotness[] = {
1057 method_hotness.IsHot(),
1058 method_hotness.IsStartup(),
1059 method_hotness.IsPostStartup()
1060 };
1061
1062
1063 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1064 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1065 // time that memory is referenced in the process.
1066
1067 size_t hotness_bits = 0;
1068 for (size_t i = 0; i < arraysize(hotness); ++i) {
1069 if (hotness[i]) {
1070 hotness_bits |= (1 << i);
1071 }
1072 }
1073
1074 if (kIsDebugBuild) {
1075 // Check for bins that are always-empty given a real profile.
1076 if (method_hotness.IsHot() &&
1077 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1078 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001079 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1080 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001081 // This is not fatal, so only warn.
1082 }
1083 }
1084
1085 return hotness_bits;
1086 }
1087};
1088
1089// Given a queue of CompiledMethod in some total order,
1090// visit each one in that order.
1091class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001092 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001093 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1094 : ordered_methods_(std::move(ordered_methods)) {
1095 }
1096
1097 virtual ~OrderedMethodVisitor() {}
1098
1099 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1100 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1101 if (!VisitStart()) {
1102 return false;
1103 }
1104
1105 for (const OrderedMethodData& method_data : ordered_methods_) {
1106 if (!VisitMethod(method_data)) {
1107 return false;
1108 }
1109 }
1110
1111 return VisitComplete();
1112 }
1113
1114 // Invoked once at the beginning, prior to visiting anything else.
1115 //
1116 // Return false to abort further visiting.
1117 virtual bool VisitStart() { return true; }
1118
1119 // Invoked repeatedly in the order specified by `ordered_methods`.
1120 //
1121 // Return false to short-circuit and to stop visiting further methods.
1122 virtual bool VisitMethod(const OrderedMethodData& method_data)
1123 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1124
1125 // Invoked once at the end, after every other method has been successfully visited.
1126 //
1127 // Return false to indicate the overall `Visit` has failed.
1128 virtual bool VisitComplete() = 0;
1129
1130 OrderedMethodList ReleaseOrderedMethods() {
1131 return std::move(ordered_methods_);
1132 }
1133
1134 private:
1135 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1136 // Methods can be inserted more than once in case of duplicated methods.
1137 OrderedMethodList ordered_methods_;
1138};
1139
1140// Visit every compiled method in order to determine its order within the OAT file.
1141// Methods from the same class do not need to be adjacent in the OAT code.
1142class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1143 public:
1144 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1145 : OatDexMethodVisitor(writer, offset) {
1146 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001147
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001148 bool EndClass() override {
Vladimir Markof4da6752014-08-01 19:04:18 +01001149 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001150 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001151 }
1152
Igor Murashkin545412b2017-08-17 15:26:54 -07001153 bool VisitMethod(size_t class_def_method_index,
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001154 const ClassAccessor::Method& method)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001155 override
Igor Murashkin545412b2017-08-17 15:26:54 -07001156 REQUIRES_SHARED(Locks::mutator_lock_) {
1157 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1158
Vladimir Marko49b0f452015-12-10 13:49:19 +00001159 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001160 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1161
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001162 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001163 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001164
Igor Murashkin545412b2017-08-17 15:26:54 -07001165 {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001166 const CompilerOptions& compiler_options = writer_->GetCompilerOptions();
Igor Murashkin545412b2017-08-17 15:26:54 -07001167 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1168 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001169
Igor Murashkin545412b2017-08-17 15:26:54 -07001170 // Debug method info must be pushed in the original order
1171 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1172 // ElfCompilationUnitWriter::Write requires this.
1173 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1174 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1175 writer_->method_info_.push_back(info);
1176
1177 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1178 // once we know the offsets.
1179 //
1180 // Store the index into writer_->method_info_ since future push-backs
1181 // could reallocate and change the underlying data address.
1182 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001183 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001184 }
1185
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001186 MethodReference method_ref(dex_file_, method.GetIndex());
Igor Murashkin545412b2017-08-17 15:26:54 -07001187
1188 // Lookup method hotness from profile, if available.
1189 // Otherwise assume a default of none-hotness.
1190 ProfileCompilationInfo::MethodHotness method_hotness =
1191 writer_->profile_compilation_info_ != nullptr
1192 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1193 : ProfileCompilationInfo::MethodHotness();
1194
1195 // Handle duplicate methods by pushing them repeatedly.
1196 OrderedMethodData method_data = {
1197 method_hotness,
1198 oat_class,
1199 compiled_method,
1200 method_ref,
1201 method_offsets_index_,
1202 class_def_index_,
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001203 method.GetAccessFlags(),
1204 method.GetCodeItem(),
Igor Murashkin545412b2017-08-17 15:26:54 -07001205 debug_info_idx
1206 };
1207 ordered_methods_.push_back(method_data);
1208
1209 method_offsets_index_++;
1210 }
1211
1212 return true;
1213 }
1214
1215 OrderedMethodList ReleaseOrderedMethods() {
1216 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1217 // Sort by the method ordering criteria (in OrderedMethodData).
1218 // Since most methods will have the same ordering criteria,
1219 // we preserve the original insertion order within the same sort order.
1220 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1221 } else {
1222 // The profile-less behavior is as if every method had 0 hotness
1223 // associated with it.
1224 //
1225 // Since sorting all methods with hotness=0 should give back the same
1226 // order as before, don't do anything.
1227 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1228 }
1229
1230 return std::move(ordered_methods_);
1231 }
1232
1233 private:
1234 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1235 // Methods can be inserted more than once in case of duplicated methods.
1236 OrderedMethodList ordered_methods_;
1237};
1238
1239// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1240class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1241 public:
1242 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1243 size_t offset,
1244 OrderedMethodList ordered_methods)
1245 : LayoutReserveOffsetCodeMethodVisitor(writer,
1246 offset,
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001247 writer->GetCompilerOptions(),
Igor Murashkin545412b2017-08-17 15:26:54 -07001248 std::move(ordered_methods)) {
1249 }
1250
Roland Levillainf73caca2018-08-24 17:19:07 +01001251 bool VisitComplete() override {
Igor Murashkin545412b2017-08-17 15:26:54 -07001252 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1253 if (generate_debug_info_) {
1254 std::vector<debug::MethodDebugInfo> thunk_infos =
1255 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1256 writer_->method_info_.insert(writer_->method_info_.end(),
1257 std::make_move_iterator(thunk_infos.begin()),
1258 std::make_move_iterator(thunk_infos.end()));
1259 }
1260 return true;
1261 }
1262
Roland Levillainf73caca2018-08-24 17:19:07 +01001263 bool VisitMethod(const OrderedMethodData& method_data) override
Igor Murashkin545412b2017-08-17 15:26:54 -07001264 REQUIRES_SHARED(Locks::mutator_lock_) {
1265 OatClass* oat_class = method_data.oat_class;
1266 CompiledMethod* compiled_method = method_data.compiled_method;
1267 const MethodReference& method_ref = method_data.method_reference;
1268 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1269 size_t class_def_index = method_data.class_def_index;
1270 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001271 bool has_debug_info = method_data.HasDebugInfo();
1272 size_t debug_info_idx = method_data.debug_info_idx;
1273
1274 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1275
1276 // Derived from CompiledMethod.
1277 uint32_t quick_code_offset = 0;
1278
1279 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1280 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1281 uint32_t thumb_offset = compiled_method->CodeDelta();
1282
1283 // Deduplicate code arrays if we are not producing debuggable code.
1284 bool deduped = true;
1285 if (debuggable_) {
1286 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1287 if (quick_code_offset != 0u) {
1288 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1289 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001290 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001291 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1292 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001293 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001294 } else {
1295 quick_code_offset = dedupe_map_.GetOrCreate(
1296 compiled_method,
1297 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1298 deduped = false;
1299 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1300 });
1301 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001302
Igor Murashkin545412b2017-08-17 15:26:54 -07001303 if (code_size != 0) {
1304 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1305 // TODO: Should this be a hard failure?
1306 LOG(WARNING) << "Multiple definitions of "
1307 << method_ref.dex_file->PrettyMethod(method_ref.index)
1308 << " offsets " << relative_patcher_->GetOffset(method_ref)
1309 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001310 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001311 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1312 }
1313 }
1314
1315 // Update quick method header.
1316 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1317 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1318 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
Igor Murashkin545412b2017-08-17 15:26:54 -07001319 // 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 }
David Srbecky8cd54542018-07-15 23:58:44 +01001329 *method_header = OatQuickMethodHeader(vmap_table_offset, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001330
Igor Murashkin545412b2017-08-17 15:26:54 -07001331 if (!deduped) {
1332 // Update offsets. (Checksum is updated when writing.)
1333 offset_ += sizeof(*method_header); // Method header is prepended before code.
1334 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001335 }
1336
Igor Murashkin545412b2017-08-17 15:26:54 -07001337 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1338 if (generate_debug_info_ && code_size != 0) {
1339 DCHECK(has_debug_info);
David Srbecky88087562018-06-23 22:05:56 +01001340 const uint8_t* code_info = compiled_method->GetVmapTable().data();
1341 DCHECK(code_info != nullptr);
Igor Murashkin545412b2017-08-17 15:26:54 -07001342
Igor Murashkin545412b2017-08-17 15:26:54 -07001343 // Record debug information for this function if we are doing that.
1344 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
David Srbeckyc684f332018-01-19 17:38:06 +00001345 DCHECK(info.custom_name.empty());
Igor Murashkin545412b2017-08-17 15:26:54 -07001346 info.dex_file = method_ref.dex_file;
1347 info.class_def_index = class_def_index;
1348 info.dex_method_index = method_ref.index;
1349 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001350 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1351 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001352 info.isa = compiled_method->GetInstructionSet();
1353 info.deduped = deduped;
1354 info.is_native_debuggable = native_debuggable_;
1355 info.is_optimized = method_header->IsOptimized();
1356 info.is_code_address_text_relative = true;
1357 info.code_address = code_offset - executable_offset_;
1358 info.code_size = code_size;
David Srbecky88087562018-06-23 22:05:56 +01001359 info.frame_size_in_bytes = CodeInfo::DecodeFrameInfo(code_info).FrameSizeInBytes();
1360 info.code_info = code_info;
Igor Murashkin545412b2017-08-17 15:26:54 -07001361 info.cfi = compiled_method->GetCFIInfo();
1362 } else {
1363 DCHECK(!has_debug_info);
1364 }
1365
1366 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1367 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1368 offsets->code_offset_ = quick_code_offset;
1369
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001370 return true;
1371 }
1372
Igor Murashkin545412b2017-08-17 15:26:54 -07001373 size_t GetOffset() const {
1374 return offset_;
1375 }
1376
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001377 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001378 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1379 size_t offset,
1380 const CompilerOptions& compiler_options,
1381 OrderedMethodList ordered_methods)
1382 : OrderedMethodVisitor(std::move(ordered_methods)),
1383 writer_(writer),
1384 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001385 relative_patcher_(writer->relative_patcher_),
1386 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1387 debuggable_(compiler_options.GetDebuggable()),
1388 native_debuggable_(compiler_options.GetNativeDebuggable()),
Vladimir Marko8e524ad2018-07-13 10:27:43 +01001389 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {}
Vladimir Marko1b404a82017-09-01 13:35:26 +01001390
Vladimir Marko20f85592015-03-19 10:07:02 +00001391 struct CodeOffsetsKeyComparator {
1392 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001393 // Code is deduplicated by CompilerDriver, compare only data pointers.
1394 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1395 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001396 }
1397 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001398 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1399 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001400 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001401 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1402 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001403 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001404 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1405 return rhs->IsIntrinsic();
1406 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001407 return false;
1408 }
1409 };
1410
David Srbecky009e2a62015-04-15 02:46:30 +01001411 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001412 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001413 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001414 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001415 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1416 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001417 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1418 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1419 }
1420
Igor Murashkin545412b2017-08-17 15:26:54 -07001421 OatWriter* writer_;
1422
1423 // Offset of the code of the compiled methods.
1424 size_t offset_;
1425
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001426 // Deduplication is already done on a pointer basis by the compiler driver,
1427 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001428 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001429
Vladimir Marko1b404a82017-09-01 13:35:26 +01001430 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001431 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001432 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001433 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001434 const bool native_debuggable_;
1435 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001436};
1437
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001438class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1439 public:
1440 InitMapMethodVisitor(OatWriter* writer, size_t offset)
David Srbeckyd1606412018-07-31 15:05:14 +01001441 : OatDexMethodVisitor(writer, offset),
1442 dedupe_bit_table_(&writer_->code_info_data_) {
1443 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001444
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001445 bool VisitMethod(size_t class_def_method_index,
1446 const ClassAccessor::Method& method ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001447 override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001448 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001449 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1450
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001451 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001452 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001453 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001454
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001455 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
David Srbeckyb73323c2018-07-15 23:58:44 +01001456 if (map.size() != 0u) {
David Srbeckyb73323c2018-07-15 23:58:44 +01001457 size_t offset = dedupe_code_info_.GetOrCreate(map.data(), [=]() {
David Srbeckyd1606412018-07-31 15:05:14 +01001458 // Deduplicate the inner BitTable<>s within the CodeInfo.
1459 return offset_ + dedupe_bit_table_.Dedupe(map.data());
David Srbeckyb73323c2018-07-15 23:58:44 +01001460 });
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001461 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1462 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1463 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001464 }
1465 ++method_offsets_index_;
1466 }
1467
1468 return true;
1469 }
1470
1471 private:
David Srbeckyb73323c2018-07-15 23:58:44 +01001472 // Deduplicate at CodeInfo level. The value is byte offset within code_info_data_.
1473 // This deduplicates the whole CodeInfo object without going into the inner tables.
1474 // The compiler already deduplicated the pointers but it did not dedupe the tables.
1475 SafeMap<const uint8_t*, size_t> dedupe_code_info_;
1476
David Srbeckyd1606412018-07-31 15:05:14 +01001477 // Deduplicate at BitTable level.
1478 CodeInfo::Deduper dedupe_bit_table_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001479};
1480
1481class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1482 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001483 InitImageMethodVisitor(OatWriter* writer,
1484 size_t offset,
1485 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001486 : OatDexMethodVisitor(writer, offset),
Vladimir Markoa0431112018-06-25 09:32:54 +01001487 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001488 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001489 dex_files_(dex_files),
1490 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001491
1492 // Handle copied methods here. Copy pointer to quick code from
1493 // an origin method to a copied method only if they are
1494 // in the same oat file. If the origin and the copied methods are
1495 // in different oat files don't touch the copied method.
1496 // References to other oat files are not supported yet.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001497 bool StartClass(const DexFile* dex_file, size_t class_def_index) override
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001498 REQUIRES_SHARED(Locks::mutator_lock_) {
1499 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1500 // Skip classes that are not in the image.
1501 if (!IsImageClass()) {
1502 return true;
1503 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001504 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001505 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1506 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1507 if (klass != nullptr) {
1508 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1509 // Find origin method. Declaring class and dex_method_idx
1510 // in the copied method should be the same as in the origin
1511 // method.
Vladimir Markoc945e0d2018-07-18 17:26:45 +01001512 ObjPtr<mirror::Class> declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001513 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001514 declaring_class->GetDexCache(),
1515 method.GetDexMethodIndex(),
1516 pointer_size_);
1517 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001518 CHECK(!origin->IsDirect());
1519 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001520 if (IsInOatFile(&declaring_class->GetDexFile())) {
1521 const void* code_ptr =
1522 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1523 if (code_ptr == nullptr) {
1524 methods_to_process_.push_back(std::make_pair(&method, origin));
1525 } else {
1526 method.SetEntryPointFromQuickCompiledCodePtrSize(
1527 code_ptr, pointer_size_);
1528 }
1529 }
1530 }
1531 }
1532 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001533 }
1534
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001535 bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001536 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001538 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001539 return true;
1540 }
1541
Vladimir Marko49b0f452015-12-10 13:49:19 +00001542 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001543 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1544
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001545 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001546 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001547 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1548 offsets = oat_class->method_offsets_[method_offsets_index_];
1549 ++method_offsets_index_;
1550 }
1551
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001552 Thread* self = Thread::Current();
1553 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001554 ArtMethod* resolved_method;
Vladimir Markoa0431112018-06-25 09:32:54 +01001555 if (writer_->GetCompilerOptions().IsBootImage()) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001556 const InvokeType invoke_type = method.GetInvokeType(
1557 dex_file_->GetClassDef(class_def_index_).access_flags_);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001558 // Unchecked as we hold mutator_lock_ on entry.
1559 ScopedObjectAccessUnchecked soa(self);
1560 StackHandleScope<1> hs(self);
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001561 resolved_method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
1562 method.GetIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001563 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001564 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Marko89011192017-12-11 13:45:05 +00001565 /* referrer */ nullptr,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001566 invoke_type);
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001567 if (resolved_method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001568 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001569 << dex_file_->PrettyMethod(method.GetIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001570 self->AssertPendingException();
1571 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001572 std::string dump = exc->Dump();
1573 LOG(FATAL) << dump;
1574 UNREACHABLE();
1575 }
1576 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001577 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001578 // 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 +01001579 // entrypoint. This is not fatal since we shall use a resolution method.
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001580 resolved_method = class_linker_->LookupResolvedMethod(method.GetIndex(),
1581 dex_cache,
1582 class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001583 }
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001584 if (resolved_method != nullptr &&
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001585 compiled_method != nullptr &&
1586 compiled_method->GetQuickCode().size() != 0) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001587 resolved_method->SetEntryPointFromQuickCompiledCodePtrSize(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001588 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1589 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001590
1591 return true;
1592 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001593
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001594 // Check whether current class is image class
1595 bool IsImageClass() {
1596 const DexFile::TypeId& type_id =
1597 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1598 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001599 return writer_->GetCompilerOptions().IsImageClass(class_descriptor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001600 }
1601
1602 // Check whether specified dex file is in the compiled oat file.
1603 bool IsInOatFile(const DexFile* dex_file) {
1604 return ContainsElement(*dex_files_, dex_file);
1605 }
1606
1607 // Assign a pointer to quick code for copied methods
1608 // not handled in the method StartClass
1609 void Postprocess() {
1610 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1611 ArtMethod* method = p.first;
1612 ArtMethod* origin = p.second;
1613 const void* code_ptr =
1614 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1615 if (code_ptr != nullptr) {
1616 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1617 }
1618 }
1619 }
1620
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001621 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001622 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001623 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001624 const std::vector<const DexFile*>* dex_files_;
1625 ClassLinker* const class_linker_;
1626 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001627};
1628
Igor Murashkin545412b2017-08-17 15:26:54 -07001629class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001630 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001631 WriteCodeMethodVisitor(OatWriter* writer,
1632 OutputStream* out,
1633 const size_t file_offset,
1634 size_t relative_offset,
1635 OrderedMethodList ordered_methods)
1636 : OrderedMethodVisitor(std::move(ordered_methods)),
1637 writer_(writer),
1638 offset_(relative_offset),
1639 dex_file_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +01001640 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001641 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1642 out_(out),
1643 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001644 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001645 dex_cache_(nullptr),
1646 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001647 patched_code_.reserve(16 * KB);
Vladimir Markoa0431112018-06-25 09:32:54 +01001648 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001649 // If we're creating the image, the address space must be ready so that we can apply patches.
1650 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001651 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001652 }
1653
Roland Levillainf73caca2018-08-24 17:19:07 +01001654 bool VisitStart() override {
Igor Murashkin545412b2017-08-17 15:26:54 -07001655 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001656 }
1657
Igor Murashkin545412b2017-08-17 15:26:54 -07001658 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001659 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001660 dex_file_ = dex_file;
1661
1662 // Ordered method visiting is only for compiled methods.
1663 DCHECK(writer_->MayHaveCompiledMethods());
1664
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001665 if (writer_->GetCompilerOptions().IsAotCompilationEnabled()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001666 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1667 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1668 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1669 DCHECK(dex_cache_ != nullptr);
1670 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001671 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001672 }
1673
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001674 bool VisitComplete() override {
Igor Murashkin545412b2017-08-17 15:26:54 -07001675 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1676 if (UNLIKELY(offset_ == 0u)) {
1677 PLOG(ERROR) << "Failed to write final relative call thunks";
1678 return false;
1679 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001680 return true;
1681 }
1682
Roland Levillainf73caca2018-08-24 17:19:07 +01001683 bool VisitMethod(const OrderedMethodData& method_data) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001684 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001685 const MethodReference& method_ref = method_data.method_reference;
1686 UpdateDexFileAndDexCache(method_ref.dex_file);
1687
1688 OatClass* oat_class = method_data.oat_class;
1689 CompiledMethod* compiled_method = method_data.compiled_method;
1690 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001691
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001692 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001693 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001694 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001695
Igor Murashkin545412b2017-08-17 15:26:54 -07001696 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1697 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1698 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001699
Igor Murashkin545412b2017-08-17 15:26:54 -07001700 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1701 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1702
1703 // Deduplicate code arrays.
1704 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1705 if (method_offsets.code_offset_ > offset_) {
1706 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1707 if (offset_ == 0u) {
1708 ReportWriteFailure("relative call thunk", method_ref);
1709 return false;
1710 }
1711 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1712 if (alignment_size != 0) {
1713 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1714 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001715 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001716 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001717 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001718 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001719 }
1720 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1721 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1722 DCHECK_EQ(method_offsets.code_offset_,
1723 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1724 << dex_file_->PrettyMethod(method_ref.index);
1725 const OatQuickMethodHeader& method_header =
1726 oat_class->method_headers_[method_offsets_index];
1727 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1728 ReportWriteFailure("method header", method_ref);
1729 return false;
1730 }
1731 writer_->size_method_header_ += sizeof(method_header);
1732 offset_ += sizeof(method_header);
1733 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001734
Igor Murashkin545412b2017-08-17 15:26:54 -07001735 if (!compiled_method->GetPatches().empty()) {
1736 patched_code_.assign(quick_code.begin(), quick_code.end());
1737 quick_code = ArrayRef<const uint8_t>(patched_code_);
1738 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1739 uint32_t literal_offset = patch.LiteralOffset();
1740 switch (patch.GetType()) {
Vladimir Marko6fd16062018-06-26 11:02:04 +01001741 case LinkerPatch::Type::kIntrinsicReference: {
1742 uint32_t target_offset = GetTargetIntrinsicReferenceOffset(patch);
1743 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1744 patch,
1745 offset_ + literal_offset,
1746 target_offset);
1747 break;
1748 }
Vladimir Markob066d432018-01-03 13:14:37 +00001749 case LinkerPatch::Type::kDataBimgRelRo: {
1750 uint32_t target_offset =
1751 writer_->data_bimg_rel_ro_start_ +
1752 writer_->data_bimg_rel_ro_entries_.Get(patch.BootImageOffset());
1753 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1754 patch,
1755 offset_ + literal_offset,
1756 target_offset);
1757 break;
1758 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001759 case LinkerPatch::Type::kMethodBssEntry: {
1760 uint32_t target_offset =
1761 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1762 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1763 patch,
1764 offset_ + literal_offset,
1765 target_offset);
1766 break;
1767 }
1768 case LinkerPatch::Type::kCallRelative: {
1769 // NOTE: Relative calls across oat files are not supported.
1770 uint32_t target_offset = GetTargetOffset(patch);
1771 writer_->relative_patcher_->PatchCall(&patched_code_,
1772 literal_offset,
1773 offset_ + literal_offset,
1774 target_offset);
1775 break;
1776 }
1777 case LinkerPatch::Type::kStringRelative: {
1778 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1779 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1780 patch,
1781 offset_ + literal_offset,
1782 target_offset);
1783 break;
1784 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001785 case LinkerPatch::Type::kStringBssEntry: {
1786 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1787 uint32_t target_offset =
1788 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1789 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1790 patch,
1791 offset_ + literal_offset,
1792 target_offset);
1793 break;
1794 }
1795 case LinkerPatch::Type::kTypeRelative: {
1796 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1797 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1798 patch,
1799 offset_ + literal_offset,
1800 target_offset);
1801 break;
1802 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001803 case LinkerPatch::Type::kTypeBssEntry: {
1804 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1805 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1806 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1807 patch,
1808 offset_ + literal_offset,
1809 target_offset);
1810 break;
1811 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001812 case LinkerPatch::Type::kMethodRelative: {
1813 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1814 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1815 patch,
1816 offset_ + literal_offset,
1817 target_offset);
1818 break;
1819 }
1820 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1821 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1822 patch,
1823 offset_ + literal_offset);
1824 break;
1825 }
1826 default: {
1827 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1828 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001829 }
1830 }
1831 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001832 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001833
1834 if (!out->WriteFully(quick_code.data(), code_size)) {
1835 ReportWriteFailure("method code", method_ref);
1836 return false;
1837 }
1838 writer_->size_code_ += code_size;
1839 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001840 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001841 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001842
1843 return true;
1844 }
1845
Igor Murashkin545412b2017-08-17 15:26:54 -07001846 size_t GetOffset() const {
1847 return offset_;
1848 }
1849
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001850 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001851 OatWriter* const writer_;
1852
1853 // Updated in VisitMethod as methods are written out.
1854 size_t offset_;
1855
1856 // Potentially varies with every different VisitMethod.
1857 // Used to determine which DexCache to use when finding ArtMethods.
1858 const DexFile* dex_file_;
1859
1860 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001861 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001862 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001863 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001864 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001865 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001866 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001867 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001868 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001869 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001870 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001871
Igor Murashkin545412b2017-08-17 15:26:54 -07001872 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001873 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001874 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001875 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001876
Mathieu Chartiere401d142015-04-22 13:56:20 -07001877 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001878 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001879 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001880 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001881 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1882 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001883 ArtMethod* method =
1884 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001885 CHECK(method != nullptr);
1886 return method;
1887 }
1888
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001889 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001890 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1891 // If there's no new compiled code, either we're compiling an app and the target method
1892 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001893 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001894 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001895 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001896 const void* oat_code_offset =
1897 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Yi Kong4b22b342018-08-02 14:43:21 -07001898 if (oat_code_offset != nullptr) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001899 DCHECK(!writer_->GetCompilerOptions().IsBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001900 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1901 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1902 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1903 target_offset = PointerToLowMemUInt32(oat_code_offset);
1904 } else {
1905 target_offset = target->IsNative()
1906 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1907 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1908 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001909 }
1910 return target_offset;
1911 }
1912
Vladimir Markocd556b02017-02-03 11:47:34 +00001913 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001914 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001915 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001916 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001917 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1918 }
1919
Vladimir Marko28e012a2017-12-07 11:22:59 +00001920 ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1921 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001922 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001923 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001924 ObjPtr<mirror::Class> type =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001925 class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001926 CHECK(type != nullptr);
Vladimir Marko28e012a2017-12-07 11:22:59 +00001927 return type;
Vladimir Markof4da6752014-08-01 19:04:18 +01001928 }
1929
Vladimir Marko28e012a2017-12-07 11:22:59 +00001930 ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1931 REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001932 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Markoa64b52d2017-12-08 16:27:49 +00001933 ObjPtr<mirror::String> string =
1934 linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001935 DCHECK(string != nullptr);
Vladimir Markoa0431112018-06-25 09:32:54 +01001936 DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001937 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1938 return string;
1939 }
1940
Vladimir Marko6fd16062018-06-26 11:02:04 +01001941 uint32_t GetTargetIntrinsicReferenceOffset(const LinkerPatch& patch)
1942 REQUIRES_SHARED(Locks::mutator_lock_) {
1943 DCHECK(writer_->GetCompilerOptions().IsBootImage());
1944 const void* address =
1945 writer_->image_writer_->GetIntrinsicReferenceAddress(patch.IntrinsicData());
1946 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1947 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1948 // TODO: Clean up offset types. The target offset must be treated as signed.
1949 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(address) - oat_data_begin);
1950 }
1951
Vladimir Marko65979462017-05-19 17:25:12 +01001952 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001953 DCHECK(writer_->GetCompilerOptions().IsBootImage());
Vladimir Marko65979462017-05-19 17:25:12 +01001954 method = writer_->image_writer_->GetImageMethodAddress(method);
1955 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1956 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1957 // TODO: Clean up offset types. The target offset must be treated as signed.
1958 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1959 }
1960
Vladimir Marko28e012a2017-12-07 11:22:59 +00001961 uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
1962 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001963 DCHECK(writer_->GetCompilerOptions().IsBootImage());
Vladimir Marko28e012a2017-12-07 11:22:59 +00001964 object = writer_->image_writer_->GetImageAddress(object.Ptr());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001965 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1966 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1967 // TODO: Clean up offset types. The target offset must be treated as signed.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001968 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001969 }
1970
Vladimir Markof4da6752014-08-01 19:04:18 +01001971 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001972 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001973 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001974 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001975 } else {
1976 // NOTE: We're using linker patches for app->boot references when the image can
1977 // be relocated and therefore we need to emit .oat_patches. We're not using this
1978 // for app->app references, so check that the object is in the image space.
1979 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001980 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001981 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001982 uint32_t address = PointerToLowMemUInt32(object);
1983 DCHECK_LE(offset + 4, code->size());
1984 uint8_t* data = &(*code)[offset];
1985 data[0] = address & 0xffu;
1986 data[1] = (address >> 8) & 0xffu;
1987 data[2] = (address >> 16) & 0xffu;
1988 data[3] = (address >> 24) & 0xffu;
1989 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001990};
1991
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001992// Visit all methods from all classes in all dex files with the specified visitor.
1993bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1994 for (const DexFile* dex_file : *dex_files_) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001995 for (ClassAccessor accessor : dex_file->GetClasses()) {
1996 if (UNLIKELY(!visitor->StartClass(dex_file, accessor.GetClassDefIndex()))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001997 return false;
1998 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07001999 if (MayHaveCompiledMethods()) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07002000 size_t class_def_method_index = 0u;
2001 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2002 if (!visitor->VisitMethod(class_def_method_index, method)) {
2003 return false;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002004 }
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07002005 ++class_def_method_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002006 }
2007 }
2008 if (UNLIKELY(!visitor->EndClass())) {
2009 return false;
2010 }
2011 }
2012 }
2013 return true;
2014}
2015
Vladimir Markoa0431112018-06-25 09:32:54 +01002016size_t OatWriter::InitOatHeader(uint32_t num_dex_files,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002017 SafeMap<std::string, std::string>* key_value_store) {
2018 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
Vladimir Markoa0431112018-06-25 09:32:54 +01002019 oat_header_.reset(OatHeader::Create(GetCompilerOptions().GetInstructionSet(),
2020 GetCompilerOptions().GetInstructionSetFeatures(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002021 num_dex_files,
2022 key_value_store));
2023 size_oat_header_ += sizeof(OatHeader);
2024 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002025 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002026}
2027
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002028size_t OatWriter::InitClassOffsets(size_t offset) {
2029 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002030 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002031 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2032 if (!oat_dex_file.class_offsets_.empty()) {
2033 // Class offsets are required to be 4 byte aligned.
2034 offset = RoundUp(offset, 4u);
2035 oat_dex_file.class_offsets_offset_ = offset;
2036 offset += oat_dex_file.GetClassOffsetsRawSize();
2037 DCHECK_ALIGNED(offset, 4u);
2038 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002039 }
2040 return offset;
2041}
2042
Brian Carlstrom389efb02012-01-11 12:06:26 -08002043size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002044 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002045 InitOatClassesMethodVisitor visitor(this, offset);
2046 bool success = VisitDexMethods(&visitor);
2047 CHECK(success);
2048 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002049
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002050 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002051 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002052 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2053 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002054 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002055 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002056 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002057 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002058 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002059 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002060
2061 return offset;
2062}
2063
2064size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002065 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002066 return offset;
2067 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002068 {
2069 InitMapMethodVisitor visitor(this, offset);
2070 bool success = VisitDexMethods(&visitor);
2071 DCHECK(success);
David Srbeckyd1606412018-07-31 15:05:14 +01002072 code_info_data_.shrink_to_fit();
David Srbeckyb73323c2018-07-15 23:58:44 +01002073 offset += code_info_data_.size();
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002074 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002075 return offset;
2076}
2077
Vladimir Markof3c52b42017-11-17 17:32:12 +00002078template <typename GetBssOffset>
2079static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2080 size_t slot_size,
2081 const BitVector& indexes,
2082 GetBssOffset get_bss_offset) {
2083 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2084 size_t number_of_entries = 0u;
2085 bool first_index = true;
2086 for (uint32_t index : indexes.Indexes()) {
2087 uint32_t bss_offset = get_bss_offset(index);
2088 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2089 encoder.Reset(index, bss_offset);
2090 ++number_of_entries;
2091 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002092 }
2093 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002094 DCHECK_NE(number_of_entries, 0u);
2095 return number_of_entries;
2096}
2097
2098template <typename GetBssOffset>
2099static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2100 size_t slot_size,
2101 const BitVector& indexes,
2102 GetBssOffset get_bss_offset) {
2103 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2104 slot_size,
2105 indexes,
2106 get_bss_offset);
2107 return IndexBssMapping::ComputeSize(number_of_entries);
2108}
2109
2110size_t OatWriter::InitIndexBssMappings(size_t offset) {
2111 if (bss_method_entry_references_.empty() &&
2112 bss_type_entry_references_.empty() &&
2113 bss_string_entry_references_.empty()) {
2114 return offset;
2115 }
2116 // If there are any classes, the class offsets allocation aligns the offset
2117 // and we cannot have any index bss mappings without class offsets.
2118 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2119 DCHECK_ALIGNED(offset, 4u);
2120
2121 size_t number_of_method_dex_files = 0u;
2122 size_t number_of_type_dex_files = 0u;
2123 size_t number_of_string_dex_files = 0u;
2124 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2125 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2126 const DexFile* dex_file = (*dex_files_)[i];
2127 auto method_it = bss_method_entry_references_.find(dex_file);
2128 if (method_it != bss_method_entry_references_.end()) {
2129 const BitVector& method_indexes = method_it->second;
2130 ++number_of_method_dex_files;
2131 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2132 offset += CalculateIndexBssMappingSize(
2133 dex_file->NumMethodIds(),
2134 static_cast<size_t>(pointer_size),
2135 method_indexes,
2136 [=](uint32_t index) {
2137 return bss_method_entries_.Get({dex_file, index});
2138 });
2139 }
2140
2141 auto type_it = bss_type_entry_references_.find(dex_file);
2142 if (type_it != bss_type_entry_references_.end()) {
2143 const BitVector& type_indexes = type_it->second;
2144 ++number_of_type_dex_files;
2145 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2146 offset += CalculateIndexBssMappingSize(
2147 dex_file->NumTypeIds(),
2148 sizeof(GcRoot<mirror::Class>),
2149 type_indexes,
2150 [=](uint32_t index) {
2151 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2152 });
2153 }
2154
2155 auto string_it = bss_string_entry_references_.find(dex_file);
2156 if (string_it != bss_string_entry_references_.end()) {
2157 const BitVector& string_indexes = string_it->second;
2158 ++number_of_string_dex_files;
2159 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2160 offset += CalculateIndexBssMappingSize(
2161 dex_file->NumStringIds(),
2162 sizeof(GcRoot<mirror::String>),
2163 string_indexes,
2164 [=](uint32_t index) {
2165 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2166 });
2167 }
2168 }
2169 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2170 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2171 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2172 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002173 return offset;
2174}
2175
2176size_t OatWriter::InitOatDexFiles(size_t offset) {
2177 // Initialize offsets of oat dex files.
2178 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2179 oat_dex_file.offset_ = offset;
2180 offset += oat_dex_file.SizeOf();
2181 }
2182 return offset;
2183}
2184
Brian Carlstrome24fa612011-09-29 00:53:55 -07002185size_t OatWriter::InitOatCode(size_t offset) {
2186 // calculate the offsets within OatHeader to executable code
2187 size_t old_offset = offset;
2188 // required to be on a new page boundary
2189 offset = RoundUp(offset, kPageSize);
2190 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002191 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002192 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2193 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2194 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002195 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002196 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002197 const bool generate_debug_info = GetCompilerOptions().GenerateAnyDebugInfo();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002198 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002199
Vladimir Marko1b404a82017-09-01 13:35:26 +01002200 #define DO_TRAMPOLINE(field, fn_name) \
2201 offset = CompiledCode::AlignCode(offset, instruction_set); \
2202 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2203 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2204 (field) = compiler_driver_->Create ## fn_name(); \
2205 if (generate_debug_info) { \
2206 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +00002207 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +01002208 info.isa = instruction_set; \
2209 info.is_code_address_text_relative = true; \
2210 /* Use the code offset rather than the `adjusted_offset`. */ \
2211 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2212 info.code_size = (field)->size(); \
2213 method_info_.push_back(std::move(info)); \
2214 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002215 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002216
Ian Rogers848871b2013-08-05 10:56:33 -07002217 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002218 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002219 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002220 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2221 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002222
Ian Rogers848871b2013-08-05 10:56:33 -07002223 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002224 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002225 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002226 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002227 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002228 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002229 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002230 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002231 return offset;
2232}
2233
2234size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002235 if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002236 if (kOatWriterDebugOatCodeLayout) {
2237 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2238 << this << "), "
2239 << "compilation is disabled";
2240 }
2241
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002242 return offset;
2243 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002244 bool success = false;
2245
2246 {
2247 ScopedObjectAccess soa(Thread::Current());
2248
2249 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2250 success = VisitDexMethods(&layout_code_visitor);
2251 DCHECK(success);
2252
2253 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2254 this,
2255 offset,
2256 layout_code_visitor.ReleaseOrderedMethods());
2257 success = layout_reserve_code_visitor.Visit();
2258 DCHECK(success);
2259 offset = layout_reserve_code_visitor.GetOffset();
2260
2261 // Save the method order because the WriteCodeMethodVisitor will need this
2262 // order again.
2263 DCHECK(ordered_methods_ == nullptr);
2264 ordered_methods_.reset(
2265 new OrderedMethodList(
2266 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2267
2268 if (kOatWriterDebugOatCodeLayout) {
2269 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2270 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2271 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2272 LOG(INFO) << pretty_name
2273 << "@ offset "
2274 << relative_patcher_->GetOffset(ordered_method.method_reference)
2275 << " X hotness "
2276 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2277 }
2278 }
2279 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002280
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002281 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002282 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002283 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002284 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002285 DCHECK(success);
2286 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002287 }
Logan Chien8b977d32012-02-21 19:14:55 +08002288
Brian Carlstrome24fa612011-09-29 00:53:55 -07002289 return offset;
2290}
2291
Vladimir Markob066d432018-01-03 13:14:37 +00002292size_t OatWriter::InitDataBimgRelRoLayout(size_t offset) {
2293 DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
2294 if (data_bimg_rel_ro_entries_.empty()) {
2295 // Nothing to put to the .data.bimg.rel.ro section.
2296 return offset;
2297 }
2298
2299 data_bimg_rel_ro_start_ = RoundUp(offset, kPageSize);
2300
2301 for (auto& entry : data_bimg_rel_ro_entries_) {
2302 size_t& entry_offset = entry.second;
2303 entry_offset = data_bimg_rel_ro_size_;
2304 data_bimg_rel_ro_size_ += sizeof(uint32_t);
2305 }
2306
2307 offset = data_bimg_rel_ro_start_ + data_bimg_rel_ro_size_;
2308 return offset;
2309}
2310
Vladimir Markoaad75c62016-10-03 08:46:48 +00002311void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002312 {
2313 InitBssLayoutMethodVisitor visitor(this);
2314 bool success = VisitDexMethods(&visitor);
2315 DCHECK(success);
2316 }
2317
2318 DCHECK_EQ(bss_size_, 0u);
Vladimir Markoa0431112018-06-25 09:32:54 +01002319 if (GetCompilerOptions().IsBootImage()) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002320 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002321 }
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002322 if (bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002323 bss_type_entries_.empty() &&
2324 bss_string_entries_.empty()) {
2325 // Nothing to put to the .bss section.
2326 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002327 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002328
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002329 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002330 bss_methods_offset_ = bss_size_;
2331
2332 // Prepare offsets for .bss ArtMethod entries.
2333 for (auto& entry : bss_method_entries_) {
2334 DCHECK_EQ(entry.second, 0u);
2335 entry.second = bss_size_;
2336 bss_size_ += static_cast<size_t>(pointer_size);
2337 }
2338
Vladimir Markoaad75c62016-10-03 08:46:48 +00002339 bss_roots_offset_ = bss_size_;
2340
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002341 // Prepare offsets for .bss Class entries.
2342 for (auto& entry : bss_type_entries_) {
2343 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002344 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002345 bss_size_ += sizeof(GcRoot<mirror::Class>);
2346 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002347 // Prepare offsets for .bss String entries.
2348 for (auto& entry : bss_string_entries_) {
2349 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002350 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002351 bss_size_ += sizeof(GcRoot<mirror::String>);
2352 }
2353}
2354
David Srbeckybc90fd02015-04-22 19:40:27 +01002355bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002356 CHECK(write_state_ == WriteState::kWriteRoData);
2357
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002358 size_t file_offset = oat_data_offset_;
2359 off_t current_offset = out->Seek(0, kSeekCurrent);
2360 if (current_offset == static_cast<off_t>(-1)) {
2361 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2362 }
2363 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2364 size_t relative_offset = current_offset - file_offset;
2365
Vladimir Markoe079e212016-05-25 12:49:49 +01002366 // Wrap out to update checksum with each write.
2367 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2368 out = &checksum_updating_out;
2369
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002370 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2371 if (relative_offset == 0) {
2372 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002373 return false;
2374 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002375
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002376 relative_offset = WriteClasses(out, file_offset, relative_offset);
2377 if (relative_offset == 0) {
2378 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002379 return false;
2380 }
2381
Vladimir Markof3c52b42017-11-17 17:32:12 +00002382 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002383 if (relative_offset == 0) {
2384 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002385 return false;
2386 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002387
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002388 relative_offset = WriteMaps(out, file_offset, relative_offset);
2389 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002390 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2391 return false;
2392 }
2393
2394 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2395 if (relative_offset == 0) {
2396 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002397 return false;
2398 }
2399
David Srbeckybc90fd02015-04-22 19:40:27 +01002400 // Write padding.
2401 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2402 relative_offset += size_executable_offset_alignment_;
2403 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2404 size_t expected_file_offset = file_offset + relative_offset;
2405 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2406 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2407 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
Andreas Gampe8351aac2018-09-10 12:37:49 -07002408 return false;
David Srbeckybc90fd02015-04-22 19:40:27 +01002409 }
2410 DCHECK_OFFSET();
2411
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002412 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002413 return true;
2414}
2415
Mathieu Chartier210531f2018-01-12 10:15:51 -08002416class OatWriter::WriteQuickeningInfoMethodVisitor {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002417 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002418 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out)
2419 : writer_(writer),
2420 out_(out) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002421
Mathieu Chartier210531f2018-01-12 10:15:51 -08002422 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002423 // Map of offsets for quicken info related to method indices.
2424 SafeMap<const uint8_t*, uint32_t> offset_map;
2425 // Use method index order to minimize the encoded size of the offset table.
Mathieu Chartier210531f2018-01-12 10:15:51 -08002426 for (const DexFile* dex_file : dex_files) {
2427 std::vector<uint32_t>* const offsets =
2428 &quicken_info_offset_indices_.Put(dex_file, std::vector<uint32_t>())->second;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002429 for (uint32_t method_idx = 0; method_idx < dex_file->NumMethodIds(); ++method_idx) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002430 uint32_t offset = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002431 MethodReference method_ref(dex_file, method_idx);
2432 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(method_ref);
2433 if (compiled_method != nullptr && HasQuickeningInfo(compiled_method)) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002434 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Mathieu Chartier210531f2018-01-12 10:15:51 -08002435
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002436 // Record each index if required. written_bytes_ is the offset from the start of the
2437 // quicken info data.
2438 // May be already inserted for deduplicate items.
2439 // Add offset of one to make sure 0 represents unused.
2440 auto pair = offset_map.emplace(map.data(), written_bytes_ + 1);
2441 offset = pair.first->second;
2442 // Write out the map if it's not already written.
2443 if (pair.second) {
2444 const uint32_t length = map.size() * sizeof(map.front());
2445 if (!out_->WriteFully(map.data(), length)) {
2446 PLOG(ERROR) << "Failed to write quickening info for " << method_ref.PrettyMethod()
2447 << " to " << out_->GetLocation();
2448 return false;
2449 }
2450 written_bytes_ += length;
2451 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002452 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002453 offsets->push_back(offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002454 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002455 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002456 return true;
2457 }
2458
2459 size_t GetNumberOfWrittenBytes() const {
2460 return written_bytes_;
2461 }
2462
Mathieu Chartier210531f2018-01-12 10:15:51 -08002463 SafeMap<const DexFile*, std::vector<uint32_t>>& GetQuickenInfoOffsetIndicies() {
2464 return quicken_info_offset_indices_;
2465 }
2466
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002467 private:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002468 OatWriter* const writer_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002469 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002470 size_t written_bytes_ = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002471 SafeMap<const DexFile*, std::vector<uint32_t>> quicken_info_offset_indices_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002472};
2473
Mathieu Chartier210531f2018-01-12 10:15:51 -08002474class OatWriter::WriteQuickeningInfoOffsetsMethodVisitor {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002475 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002476 WriteQuickeningInfoOffsetsMethodVisitor(
2477 OutputStream* out,
2478 uint32_t start_offset,
2479 SafeMap<const DexFile*, std::vector<uint32_t>>* quicken_info_offset_indices,
2480 std::vector<uint32_t>* out_table_offsets)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002481 : out_(out),
Mathieu Chartier210531f2018-01-12 10:15:51 -08002482 start_offset_(start_offset),
2483 quicken_info_offset_indices_(quicken_info_offset_indices),
2484 out_table_offsets_(out_table_offsets) {}
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002485
Mathieu Chartier210531f2018-01-12 10:15:51 -08002486 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002487 for (const DexFile* dex_file : dex_files) {
Mathieu Chartier210531f2018-01-12 10:15:51 -08002488 auto it = quicken_info_offset_indices_->find(dex_file);
2489 DCHECK(it != quicken_info_offset_indices_->end()) << "Failed to find dex file "
2490 << dex_file->GetLocation();
2491 const std::vector<uint32_t>* const offsets = &it->second;
2492
2493 const uint32_t current_offset = start_offset_ + written_bytes_;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002494 CHECK_ALIGNED_PARAM(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002495
2496 // Generate and write the data.
2497 std::vector<uint8_t> table_data;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002498 CompactOffsetTable::Build(*offsets, &table_data);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002499
2500 // Store the offset since we need to put those after the dex file. Table offsets are relative
2501 // to the start of the quicken info section.
2502 out_table_offsets_->push_back(current_offset);
2503
2504 const uint32_t length = table_data.size() * sizeof(table_data.front());
2505 if (!out_->WriteFully(table_data.data(), length)) {
2506 PLOG(ERROR) << "Failed to write quickening offset table for " << dex_file->GetLocation()
2507 << " to " << out_->GetLocation();
2508 return false;
2509 }
2510 written_bytes_ += length;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002511 }
2512 return true;
2513 }
2514
2515 size_t GetNumberOfWrittenBytes() const {
2516 return written_bytes_;
2517 }
2518
2519 private:
2520 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002521 const uint32_t start_offset_;
2522 size_t written_bytes_ = 0u;
2523 // Maps containing the offsets for the tables.
2524 SafeMap<const DexFile*, std::vector<uint32_t>>* const quicken_info_offset_indices_;
2525 std::vector<uint32_t>* const out_table_offsets_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002526};
2527
2528bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08002529 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002530 // Nothing to write. Leave `vdex_size_` untouched and unaligned.
2531 vdex_quickening_info_offset_ = vdex_size_;
2532 size_quickening_info_alignment_ = 0;
2533 return true;
2534 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002535 size_t initial_offset = vdex_size_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002536 // Make sure the table is properly aligned.
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002537 size_t start_offset = RoundUp(initial_offset, 4u);
2538
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002539 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2540 if (actual_offset != static_cast<off_t>(start_offset)) {
2541 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2542 << " Expected: " << start_offset
2543 << " Output: " << vdex_out->GetLocation();
2544 return false;
2545 }
2546
Mathieu Chartier210531f2018-01-12 10:15:51 -08002547 size_t current_offset = start_offset;
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002548 if (GetCompilerOptions().IsQuickeningCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002549 std::vector<uint32_t> dex_files_indices;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002550 WriteQuickeningInfoMethodVisitor write_quicken_info_visitor(this, vdex_out);
2551 if (!write_quicken_info_visitor.VisitDexMethods(*dex_files_)) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002552 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2553 return false;
2554 }
2555
Mathieu Chartier210531f2018-01-12 10:15:51 -08002556 uint32_t quicken_info_offset = write_quicken_info_visitor.GetNumberOfWrittenBytes();
2557 current_offset = current_offset + quicken_info_offset;
2558 uint32_t before_offset = current_offset;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002559 current_offset = RoundUp(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002560 const size_t extra_bytes = current_offset - before_offset;
2561 quicken_info_offset += extra_bytes;
2562 actual_offset = vdex_out->Seek(current_offset, kSeekSet);
2563 if (actual_offset != static_cast<off_t>(current_offset)) {
2564 PLOG(ERROR) << "Failed to seek to quickening offset table section. Actual: " << actual_offset
2565 << " Expected: " << current_offset
2566 << " Output: " << vdex_out->GetLocation();
2567 return false;
2568 }
2569
2570 std::vector<uint32_t> table_offsets;
2571 WriteQuickeningInfoOffsetsMethodVisitor table_visitor(
2572 vdex_out,
2573 quicken_info_offset,
2574 &write_quicken_info_visitor.GetQuickenInfoOffsetIndicies(),
2575 /*out*/ &table_offsets);
2576 if (!table_visitor.VisitDexMethods(*dex_files_)) {
2577 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2578 << vdex_out->GetLocation();
2579 return false;
2580 }
2581
2582 CHECK_EQ(table_offsets.size(), dex_files_->size());
2583
2584 current_offset += table_visitor.GetNumberOfWrittenBytes();
2585
2586 // Store the offset table offset as a preheader for each dex.
2587 size_t index = 0;
2588 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
2589 const off_t desired_offset = oat_dex_file.dex_file_offset_ -
2590 sizeof(VdexFile::QuickeningTableOffsetType);
2591 actual_offset = vdex_out->Seek(desired_offset, kSeekSet);
2592 if (actual_offset != desired_offset) {
2593 PLOG(ERROR) << "Failed to seek to before dex file for writing offset table offset: "
2594 << actual_offset << " Expected: " << desired_offset
2595 << " Output: " << vdex_out->GetLocation();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002596 return false;
2597 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002598 uint32_t offset = table_offsets[index];
2599 if (!vdex_out->WriteFully(reinterpret_cast<const uint8_t*>(&offset), sizeof(offset))) {
2600 PLOG(ERROR) << "Failed to write verifier deps."
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002601 << " File: " << vdex_out->GetLocation();
2602 return false;
2603 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002604 ++index;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002605 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002606 if (!vdex_out->Flush()) {
2607 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2608 << " File: " << vdex_out->GetLocation();
2609 return false;
2610 }
2611 size_quickening_info_ = current_offset - start_offset;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002612 } else {
2613 // We know we did not quicken.
2614 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002615 }
2616
David Brazdil93592f52017-12-08 10:53:27 +00002617 if (size_quickening_info_ == 0) {
2618 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2619 vdex_quickening_info_offset_ = initial_offset;
2620 size_quickening_info_alignment_ = 0;
2621 } else {
2622 vdex_size_ = start_offset + size_quickening_info_;
2623 vdex_quickening_info_offset_ = start_offset;
2624 size_quickening_info_alignment_ = start_offset - initial_offset;
2625 }
2626
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002627 return true;
2628}
2629
David Brazdil5d5a36b2016-09-14 15:34:10 +01002630bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002631 if (verifier_deps == nullptr) {
2632 // Nothing to write. Record the offset, but no need
2633 // for alignment.
2634 vdex_verifier_deps_offset_ = vdex_size_;
2635 return true;
2636 }
2637
2638 size_t initial_offset = vdex_size_;
2639 size_t start_offset = RoundUp(initial_offset, 4u);
2640
2641 vdex_size_ = start_offset;
2642 vdex_verifier_deps_offset_ = vdex_size_;
2643 size_verifier_deps_alignment_ = start_offset - initial_offset;
2644
2645 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2646 if (actual_offset != static_cast<off_t>(start_offset)) {
2647 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2648 << " Expected: " << start_offset
2649 << " Output: " << vdex_out->GetLocation();
2650 return false;
2651 }
2652
2653 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002654 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002655
2656 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2657 PLOG(ERROR) << "Failed to write verifier deps."
2658 << " File: " << vdex_out->GetLocation();
2659 return false;
2660 }
2661 if (!vdex_out->Flush()) {
2662 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2663 << " File: " << vdex_out->GetLocation();
2664 return false;
2665 }
2666
2667 size_verifier_deps_ = buffer.size();
2668 vdex_size_ += size_verifier_deps_;
2669 return true;
2670}
2671
David Srbeckybc90fd02015-04-22 19:40:27 +01002672bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002673 CHECK(write_state_ == WriteState::kWriteText);
2674
Vladimir Markoe079e212016-05-25 12:49:49 +01002675 // Wrap out to update checksum with each write.
2676 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2677 out = &checksum_updating_out;
2678
Vladimir Marko944da602016-02-19 12:27:55 +00002679 SetMultiOatRelativePatcherAdjustment();
2680
David Srbeckybc90fd02015-04-22 19:40:27 +01002681 const size_t file_offset = oat_data_offset_;
2682 size_t relative_offset = oat_header_->GetExecutableOffset();
2683 DCHECK_OFFSET();
2684
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002685 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002686 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002687 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002688 return false;
2689 }
2690
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002691 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2692 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002693 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002694 return false;
2695 }
2696
Vladimir Markob066d432018-01-03 13:14:37 +00002697 if (data_bimg_rel_ro_size_ != 0u) {
2698 write_state_ = WriteState::kWriteDataBimgRelRo;
2699 } else {
2700 if (!CheckOatSize(out, file_offset, relative_offset)) {
2701 return false;
2702 }
2703 write_state_ = WriteState::kWriteHeader;
2704 }
2705 return true;
2706}
2707
2708bool OatWriter::WriteDataBimgRelRo(OutputStream* out) {
2709 CHECK(write_state_ == WriteState::kWriteDataBimgRelRo);
2710
2711 // Wrap out to update checksum with each write.
2712 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2713 out = &checksum_updating_out;
2714
2715 const size_t file_offset = oat_data_offset_;
2716 size_t relative_offset = data_bimg_rel_ro_start_;
2717
2718 // Record the padding before the .data.bimg.rel.ro section.
2719 // Do not write anything, this zero-filled part was skipped (Seek()) when starting the section.
2720 size_t code_end = GetOatHeader().GetExecutableOffset() + code_size_;
2721 DCHECK_EQ(RoundUp(code_end, kPageSize), relative_offset);
2722 size_t padding_size = relative_offset - code_end;
2723 DCHECK_EQ(size_data_bimg_rel_ro_alignment_, 0u);
2724 size_data_bimg_rel_ro_alignment_ = padding_size;
2725
2726 relative_offset = WriteDataBimgRelRo(out, file_offset, relative_offset);
2727 if (relative_offset == 0) {
2728 LOG(ERROR) << "Failed to write boot image relocations to " << out->GetLocation();
2729 return false;
2730 }
2731
2732 if (!CheckOatSize(out, file_offset, relative_offset)) {
2733 return false;
2734 }
2735 write_state_ = WriteState::kWriteHeader;
2736 return true;
2737}
2738
2739bool OatWriter::CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002740 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002741 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002742 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2743 return false;
2744 }
2745
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002746 if (kIsDebugBuild) {
2747 uint32_t size_total = 0;
2748 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002749 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2750 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002751
David Brazdil7b49e6c2016-09-01 11:06:18 +01002752 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002753 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002754 DO_STAT(size_dex_file_alignment_);
2755 DO_STAT(size_executable_offset_alignment_);
2756 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002757 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002758 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002759 DO_STAT(size_verifier_deps_);
2760 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002761 DO_STAT(size_quickening_info_);
2762 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002763 DO_STAT(size_interpreter_to_interpreter_bridge_);
2764 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2765 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002766 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002767 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002768 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002769 DO_STAT(size_quick_to_interpreter_bridge_);
2770 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002771 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002772 DO_STAT(size_code_);
2773 DO_STAT(size_code_alignment_);
Vladimir Markob066d432018-01-03 13:14:37 +00002774 DO_STAT(size_data_bimg_rel_ro_);
2775 DO_STAT(size_data_bimg_rel_ro_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002776 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002777 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002778 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002779 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002780 DO_STAT(size_oat_dex_file_location_size_);
2781 DO_STAT(size_oat_dex_file_location_data_);
2782 DO_STAT(size_oat_dex_file_location_checksum_);
2783 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002784 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002785 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002786 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2787 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2788 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002789 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002790 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2791 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002792 DO_STAT(size_oat_lookup_table_alignment_);
2793 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002794 DO_STAT(size_oat_class_offsets_alignment_);
2795 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002796 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002797 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002798 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002799 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002800 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002801 DO_STAT(size_type_bss_mappings_);
2802 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002803 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002804
David Brazdil7b49e6c2016-09-01 11:06:18 +01002805 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2806
2807 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2808 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002809 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002810
David Brazdil7b49e6c2016-09-01 11:06:18 +01002811 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2812 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002813
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002814 write_state_ = WriteState::kWriteHeader;
2815 return true;
2816}
2817
Vladimir Markoe0669322018-09-03 15:44:54 +01002818bool OatWriter::WriteHeader(OutputStream* out, uint32_t image_file_location_oat_checksum) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002819 CHECK(write_state_ == WriteState::kWriteHeader);
2820
2821 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002822 oat_header_->UpdateChecksumWithHeaderData();
2823
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002824 const size_t file_offset = oat_data_offset_;
2825
2826 off_t current_offset = out->Seek(0, kSeekCurrent);
2827 if (current_offset == static_cast<off_t>(-1)) {
2828 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2829 return false;
2830 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002831 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002832 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2833 return false;
2834 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002835 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002836
2837 // Flush all other data before writing the header.
2838 if (!out->Flush()) {
2839 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2840 return false;
2841 }
2842 // Write the header.
2843 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002844 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002845 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2846 return false;
2847 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002848 // Flush the header data.
2849 if (!out->Flush()) {
2850 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002851 return false;
2852 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002853
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002854 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2855 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2856 return false;
2857 }
2858 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2859
2860 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002861 return true;
2862}
2863
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002864size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002865 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2866 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002867 // Class offsets are required to be 4 byte aligned.
2868 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
2869 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
2870 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
2871 return 0u;
2872 }
2873 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00002874 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002875 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002876 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002877 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002878 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002879 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002880 }
2881 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002882 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002883}
2884
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002885size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002886 const bool may_have_compiled = MayHaveCompiledMethods();
2887 if (may_have_compiled) {
2888 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
2889 }
2890 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002891 // If there are any classes, the class offsets allocation aligns the offset.
2892 DCHECK_ALIGNED(relative_offset, 4u);
2893 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002894 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002895 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00002896 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002897 relative_offset += oat_class_headers_[i].SizeOf();
2898 if (may_have_compiled) {
2899 if (!oat_classes_[i].Write(this, out)) {
2900 return 0u;
2901 }
2902 relative_offset += oat_classes_[i].SizeOf();
2903 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002904 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002905 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002906}
2907
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002908size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002909 {
David Srbeckyb73323c2018-07-15 23:58:44 +01002910 if (UNLIKELY(!out->WriteFully(code_info_data_.data(), code_info_data_.size()))) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002911 return 0;
2912 }
David Srbeckyb73323c2018-07-15 23:58:44 +01002913 relative_offset += code_info_data_.size();
2914 size_vmap_table_ = code_info_data_.size();
David Srbecky8cd54542018-07-15 23:58:44 +01002915 DCHECK_OFFSET();
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002916 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002917
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002918 return relative_offset;
2919}
2920
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002921
Vladimir Markof3c52b42017-11-17 17:32:12 +00002922template <typename GetBssOffset>
2923size_t WriteIndexBssMapping(OutputStream* out,
2924 size_t number_of_indexes,
2925 size_t slot_size,
2926 const BitVector& indexes,
2927 GetBssOffset get_bss_offset) {
2928 // Allocate the IndexBssMapping.
2929 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
2930 number_of_indexes, slot_size, indexes, get_bss_offset);
2931 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
2932 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
2933 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
2934 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
2935 mappings->ClearPadding();
2936 // Encode the IndexBssMapping.
2937 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2938 auto init_it = mappings->begin();
2939 bool first_index = true;
2940 for (uint32_t index : indexes.Indexes()) {
2941 size_t bss_offset = get_bss_offset(index);
2942 if (first_index) {
2943 first_index = false;
2944 encoder.Reset(index, bss_offset);
2945 } else if (!encoder.TryMerge(index, bss_offset)) {
2946 *init_it = encoder.GetEntry();
2947 ++init_it;
2948 encoder.Reset(index, bss_offset);
2949 }
2950 }
2951 // Store the last entry.
2952 *init_it = encoder.GetEntry();
2953 ++init_it;
2954 DCHECK(init_it == mappings->end());
2955
2956 if (!out->WriteFully(storage.get(), mappings_size)) {
2957 return 0u;
2958 }
2959 return mappings_size;
2960}
2961
2962size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
2963 size_t file_offset,
2964 size_t relative_offset) {
2965 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
2966 if (bss_method_entry_references_.empty() &&
2967 bss_type_entry_references_.empty() &&
2968 bss_string_entry_references_.empty()) {
2969 return relative_offset;
2970 }
2971 // If there are any classes, the class offsets allocation aligns the offset
2972 // and we cannot have method bss mappings without class offsets.
2973 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
2974 "IndexBssMapping alignment check.");
2975 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
2976
2977 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002978 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2979 const DexFile* dex_file = (*dex_files_)[i];
2980 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00002981 auto method_it = bss_method_entry_references_.find(dex_file);
2982 if (method_it != bss_method_entry_references_.end()) {
2983 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002984 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
2985 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00002986 size_t method_mappings_size = WriteIndexBssMapping(
2987 out,
2988 dex_file->NumMethodIds(),
2989 static_cast<size_t>(pointer_size),
2990 method_indexes,
2991 [=](uint32_t index) {
2992 return bss_method_entries_.Get({dex_file, index});
2993 });
2994 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002995 return 0u;
2996 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002997 size_method_bss_mappings_ += method_mappings_size;
2998 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002999 } else {
3000 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3001 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003002
3003 auto type_it = bss_type_entry_references_.find(dex_file);
3004 if (type_it != bss_type_entry_references_.end()) {
3005 const BitVector& type_indexes = type_it->second;
3006 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3007 DCHECK_OFFSET();
3008 size_t type_mappings_size = WriteIndexBssMapping(
3009 out,
3010 dex_file->NumTypeIds(),
3011 sizeof(GcRoot<mirror::Class>),
3012 type_indexes,
3013 [=](uint32_t index) {
3014 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3015 });
3016 if (type_mappings_size == 0u) {
3017 return 0u;
3018 }
3019 size_type_bss_mappings_ += type_mappings_size;
3020 relative_offset += type_mappings_size;
3021 } else {
3022 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3023 }
3024
3025 auto string_it = bss_string_entry_references_.find(dex_file);
3026 if (string_it != bss_string_entry_references_.end()) {
3027 const BitVector& string_indexes = string_it->second;
3028 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3029 DCHECK_OFFSET();
3030 size_t string_mappings_size = WriteIndexBssMapping(
3031 out,
3032 dex_file->NumStringIds(),
3033 sizeof(GcRoot<mirror::String>),
3034 string_indexes,
3035 [=](uint32_t index) {
3036 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3037 });
3038 if (string_mappings_size == 0u) {
3039 return 0u;
3040 }
3041 size_string_bss_mappings_ += string_mappings_size;
3042 relative_offset += string_mappings_size;
3043 } else {
3044 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3045 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003046 }
3047 return relative_offset;
3048}
3049
3050size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3051 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3052
3053 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3054 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3055 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3056 DCHECK_OFFSET();
3057
3058 // Write OatDexFile.
3059 if (!oat_dex_file->Write(this, out)) {
3060 return 0u;
3061 }
3062 relative_offset += oat_dex_file->SizeOf();
3063 }
3064
3065 return relative_offset;
3066}
3067
3068size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003069 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markoa0431112018-06-25 09:32:54 +01003070 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003071
Ian Rogers848871b2013-08-05 10:56:33 -07003072 #define DO_TRAMPOLINE(field) \
3073 do { \
3074 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3075 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003076 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003077 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003078 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003079 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003080 return false; \
3081 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003082 size_ ## field += (field)->size(); \
3083 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003084 DCHECK_OFFSET(); \
3085 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003086
Ian Rogers848871b2013-08-05 10:56:33 -07003087 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003088 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003089 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003090 DO_TRAMPOLINE(quick_resolution_trampoline_);
3091 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3092 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003093 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003094 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003095}
3096
Ian Rogers3d504072014-03-01 09:16:49 -08003097size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003098 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003099 size_t relative_offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003100 if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003101 // As with InitOatCodeDexFiles, also skip the writer if
3102 // compilation was disabled.
3103 if (kOatWriterDebugOatCodeLayout) {
3104 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3105 << this << "), "
3106 << "compilation is disabled";
3107 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003108
Igor Murashkin545412b2017-08-17 15:26:54 -07003109 return relative_offset;
3110 }
3111 ScopedObjectAccess soa(Thread::Current());
3112 DCHECK(ordered_methods_ != nullptr);
3113 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3114 std::move(ordered_methods_);
3115 WriteCodeMethodVisitor visitor(this,
3116 out,
3117 file_offset,
3118 relative_offset,
3119 std::move(*ordered_methods_ptr));
3120 if (UNLIKELY(!visitor.Visit())) {
3121 return 0;
3122 }
3123 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003124
Vladimir Markob163bb72015-03-31 21:49:49 +01003125 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3126 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3127 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3128
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003129 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003130}
3131
Vladimir Markob066d432018-01-03 13:14:37 +00003132size_t OatWriter::WriteDataBimgRelRo(OutputStream* out,
3133 size_t file_offset,
3134 size_t relative_offset) {
3135 if (data_bimg_rel_ro_entries_.empty()) {
3136 return relative_offset;
3137 }
3138
3139 // Write the entire .data.bimg.rel.ro with a single WriteFully().
3140 std::vector<uint32_t> data;
3141 data.reserve(data_bimg_rel_ro_entries_.size());
3142 for (const auto& entry : data_bimg_rel_ro_entries_) {
3143 uint32_t boot_image_offset = entry.first;
3144 data.push_back(boot_image_offset);
3145 }
3146 DCHECK_EQ(data.size(), data_bimg_rel_ro_entries_.size());
3147 DCHECK_OFFSET();
3148 if (!out->WriteFully(data.data(), data.size() * sizeof(data[0]))) {
3149 PLOG(ERROR) << "Failed to write .data.bimg.rel.ro in " << out->GetLocation();
3150 return 0u;
3151 }
3152 DCHECK_EQ(size_data_bimg_rel_ro_, 0u);
3153 size_data_bimg_rel_ro_ = data.size() * sizeof(data[0]);
3154 relative_offset += size_data_bimg_rel_ro_;
3155 return relative_offset;
3156}
3157
Vladimir Marko944da602016-02-19 12:27:55 +00003158bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003159 // Get the elf file offset of the oat file.
3160 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3161 if (raw_file_offset == static_cast<off_t>(-1)) {
3162 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3163 return false;
3164 }
3165 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3166 return true;
3167}
3168
Mathieu Chartier792111c2018-02-15 13:02:15 -08003169bool OatWriter::WriteDexFiles(OutputStream* out,
3170 File* file,
3171 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003172 CopyOption copy_dex_files) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003173 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003174
Mathieu Chartier792111c2018-02-15 13:02:15 -08003175 // If extraction is enabled, only do it if not all the dex files are aligned and uncompressed.
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003176 if (copy_dex_files == CopyOption::kOnlyIfCompressed) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003177 extract_dex_files_into_vdex_ = false;
3178 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3179 if (!oat_dex_file.source_.IsZipEntry()) {
3180 extract_dex_files_into_vdex_ = true;
3181 break;
3182 }
3183 ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
David Sehr79e26072018-04-06 17:58:50 -07003184 if (!entry->IsUncompressed() || !entry->IsAlignedTo(alignof(DexFile::Header))) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003185 extract_dex_files_into_vdex_ = true;
3186 break;
3187 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003188 }
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003189 } else if (copy_dex_files == CopyOption::kAlways) {
3190 extract_dex_files_into_vdex_ = true;
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003191 } else {
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003192 DCHECK(copy_dex_files == CopyOption::kNever);
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003193 extract_dex_files_into_vdex_ = false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003194 }
3195
Mathieu Chartier792111c2018-02-15 13:02:15 -08003196 if (extract_dex_files_into_vdex_) {
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003197 // Add the dex section header.
3198 vdex_size_ += sizeof(VdexFile::DexSectionHeader);
3199 vdex_dex_files_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003200 // Write dex files.
3201 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3202 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
3203 return false;
3204 }
3205 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003206
3207 // Write shared dex file data section and fix up the dex file headers.
3208 vdex_dex_shared_data_offset_ = vdex_size_;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003209 uint32_t shared_data_size = 0u;
3210
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003211 if (dex_container_ != nullptr) {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003212 CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003213 DexContainer::Section* const section = dex_container_->GetDataSection();
3214 if (section->Size() > 0) {
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003215 CHECK(compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003216 const off_t existing_offset = out->Seek(0, kSeekCurrent);
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003217 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3218 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3219 << existing_offset;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003220 return false;
3221 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003222 shared_data_size = section->Size();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003223 if (!out->WriteFully(section->Begin(), shared_data_size)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003224 PLOG(ERROR) << "Failed to write shared data!";
3225 return false;
3226 }
3227 if (!out->Flush()) {
3228 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003229 return false;
3230 }
3231 // Fix up the dex headers to have correct offsets to the data section.
3232 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3233 // Overwrite the header by reading it, updating the offset, and writing it back out.
3234 DexFile::Header header;
3235 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003236 PLOG(ERROR) << "Failed to read dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003237 return false;
3238 }
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003239 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3240 // Non-compact dex file, probably failed to convert due to duplicate methods.
3241 continue;
3242 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003243 CHECK_GT(vdex_dex_shared_data_offset_, oat_dex_file.dex_file_offset_);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003244 // Offset is from the dex file base.
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003245 header.data_off_ = vdex_dex_shared_data_offset_ - oat_dex_file.dex_file_offset_;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003246 // The size should already be what part of the data buffer may be used by the dex.
3247 CHECK_LE(header.data_size_, shared_data_size);
3248 if (!file->PwriteFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003249 PLOG(ERROR) << "Failed to write dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003250 return false;
3251 }
3252 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003253 section->Clear();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003254 }
3255 dex_container_.reset();
Mathieu Chartierf1609832018-01-31 03:09:56 -08003256 } else {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003257 const uint8_t* data_begin = nullptr;
3258 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3259 DexFile::Header header;
3260 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3261 PLOG(ERROR) << "Failed to read dex header";
3262 return false;
3263 }
3264 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3265 // Non compact dex does not have shared data section.
3266 continue;
3267 }
3268 const uint32_t expected_data_off = vdex_dex_shared_data_offset_ -
3269 oat_dex_file.dex_file_offset_;
3270 if (header.data_off_ != expected_data_off) {
3271 PLOG(ERROR) << "Shared data section offset " << header.data_off_
3272 << " does not match expected value " << expected_data_off;
3273 return false;
3274 }
3275 if (oat_dex_file.source_.IsRawData()) {
3276 // Figure out the start of the shared data section so we can copy it below.
3277 const uint8_t* cur_data_begin = oat_dex_file.source_.GetRawData() + header.data_off_;
3278 if (data_begin != nullptr) {
3279 CHECK_EQ(data_begin, cur_data_begin);
Mathieu Chartierf1609832018-01-31 03:09:56 -08003280 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003281 data_begin = cur_data_begin;
3282 }
3283 // The different dex files currently can have different data sizes since
3284 // the dex writer writes them one at a time into the shared section.:w
3285 shared_data_size = std::max(shared_data_size, header.data_size_);
3286 }
3287 // If we are not updating the input vdex, write out the shared data section.
3288 if (!update_input_vdex) {
3289 const off_t existing_offset = out->Seek(0, kSeekCurrent);
3290 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3291 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3292 << existing_offset;
3293 return false;
3294 }
3295 if (!out->WriteFully(data_begin, shared_data_size)) {
3296 PLOG(ERROR) << "Failed to write shared data!";
3297 return false;
3298 }
3299 if (!out->Flush()) {
3300 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
3301 return false;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003302 }
3303 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003304 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003305 vdex_size_ += shared_data_size;
3306 size_dex_file_ += shared_data_size;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003307 } else {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003308 vdex_dex_shared_data_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003309 }
3310
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003311 return true;
3312}
3313
3314void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003315 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3316 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3317 }
3318 zipped_dex_files_.clear();
3319 zip_archives_.clear();
3320 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003321}
3322
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003323bool OatWriter::WriteDexFile(OutputStream* out,
3324 File* file,
3325 OatDexFile* oat_dex_file,
3326 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003327 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003328 return false;
3329 }
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003330 // update_input_vdex disables compact dex and layout.
Mathieu Chartier7c6f6362018-01-14 20:24:38 -08003331 if (profile_compilation_info_ != nullptr ||
3332 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
3333 CHECK(!update_input_vdex)
3334 << "We should never update the input vdex when doing dexlayout or compact dex";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003335 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3336 return false;
3337 }
3338 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003339 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003340 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003341 return false;
3342 }
3343 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003344 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003345 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003346 return false;
3347 }
3348 } else {
3349 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003350 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003351 return false;
3352 }
3353 }
3354
3355 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003356 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3357 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003358 size_dex_file_ += oat_dex_file->dex_file_size_;
3359 return true;
3360}
3361
3362bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3363 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003364 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003365 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray67169412018-01-12 09:06:14 +00003366 size_dex_file_alignment_ += start_offset - initial_offset;
Mathieu Chartier7a26f942018-01-04 18:23:55 -08003367
Mathieu Chartier210531f2018-01-12 10:15:51 -08003368 // Leave extra room for the quicken offset table offset.
3369 start_offset += sizeof(VdexFile::QuickeningTableOffsetType);
3370 // TODO: Not count the offset as part of alignment.
3371 size_dex_file_alignment_ += sizeof(VdexFile::QuickeningTableOffsetType);
3372
3373 size_t file_offset = start_offset;
3374
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003375 // Seek to the start of the dex file and flush any pending operations in the stream.
3376 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003377 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3378 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003379 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003380 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003381 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3382 return false;
3383 }
3384 if (!out->Flush()) {
3385 PLOG(ERROR) << "Failed to flush before writing dex file."
3386 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3387 return false;
3388 }
3389 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003390 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003391 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003392 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003393 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3394 return false;
3395 }
3396
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003397 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003398 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003399 return true;
3400}
3401
Jeff Hao608f2ce2016-10-19 11:17:11 -07003402bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
David Brazdil2b9c35b2018-01-12 15:44:43 +00003403 // Open dex files and write them into `out`.
3404 // Note that we only verify dex files which do not belong to the boot class path.
3405 // This is because those have been processed by `hiddenapi` and would not pass
3406 // some of the checks. No guarantees are lost, however, as `hiddenapi` verifies
3407 // the dex files prior to processing.
Jeff Hao608f2ce2016-10-19 11:17:11 -07003408 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3409 std::string error_msg;
3410 std::string location(oat_dex_file->GetLocation());
3411 std::unique_ptr<const DexFile> dex_file;
David Sehr013fd802018-01-11 22:55:24 -08003412 const ArtDexFileLoader dex_file_loader;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003413 if (oat_dex_file->source_.IsZipEntry()) {
3414 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003415 MemMap mem_map;
Andreas Gampefb008f42018-04-23 10:01:16 -07003416 {
3417 TimingLogger::ScopedTiming extract("Unzip", timings_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003418 mem_map = zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg);
Andreas Gampefb008f42018-04-23 10:01:16 -07003419 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003420 if (!mem_map.IsValid()) {
Jeff Hao41b2f532017-03-02 16:36:31 -08003421 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3422 return false;
3423 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003424 TimingLogger::ScopedTiming extract("Open", timings_);
David Sehr013fd802018-01-11 22:55:24 -08003425 dex_file = dex_file_loader.Open(location,
Andreas Gampefb008f42018-04-23 10:01:16 -07003426 zip_entry->GetCrc32(),
3427 std::move(mem_map),
Vladimir Markoa0431112018-06-25 09:32:54 +01003428 /* verify */ !GetCompilerOptions().IsBootImage(),
Andreas Gampefb008f42018-04-23 10:01:16 -07003429 /* verify_checksum */ true,
3430 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003431 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003432 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003433 int dup_fd = dup(raw_file->Fd());
3434 if (dup_fd < 0) {
3435 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3436 return false;
3437 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003438 TimingLogger::ScopedTiming extract("Open", timings_);
David Brazdil2b9c35b2018-01-12 15:44:43 +00003439 dex_file = dex_file_loader.OpenDex(dup_fd, location,
Vladimir Markoa0431112018-06-25 09:32:54 +01003440 /* verify */ !GetCompilerOptions().IsBootImage(),
David Brazdil2b9c35b2018-01-12 15:44:43 +00003441 /* verify_checksum */ true,
3442 /* mmap_shared */ false,
3443 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003444 } else {
3445 // The source data is a vdex file.
3446 CHECK(oat_dex_file->source_.IsRawData())
3447 << static_cast<size_t>(oat_dex_file->source_.GetType());
3448 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3449 // Note: The raw data has already been checked to contain the header
3450 // and all the data that the header specifies as the file size.
3451 DCHECK(raw_dex_file != nullptr);
3452 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3453 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3454 // Since the source may have had its layout changed, or may be quickened, don't verify it.
David Sehr013fd802018-01-11 22:55:24 -08003455 dex_file = dex_file_loader.Open(raw_dex_file,
3456 header->file_size_,
3457 location,
3458 oat_dex_file->dex_file_location_checksum_,
3459 nullptr,
3460 /* verify */ false,
3461 /* verify_checksum */ false,
3462 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003463 }
Jeff Haode197542017-02-03 10:48:13 -08003464 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003465 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003466 return false;
3467 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003468 Options options;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003469 options.compact_dex_level_ = compact_dex_level_;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003470 options.update_checksum_ = true;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -08003471 DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003472 const uint8_t* dex_src = nullptr;
Andreas Gampefb008f42018-04-23 10:01:16 -07003473 {
3474 TimingLogger::ScopedTiming extract("ProcessDexFile", timings_);
3475 if (dex_layout.ProcessDexFile(location.c_str(),
3476 dex_file.get(),
3477 0,
3478 &dex_container_,
3479 &error_msg)) {
3480 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3481 // Dex layout can affect the size of the dex file, so we update here what we have set
3482 // when adding the dex file as a source.
3483 const UnalignedDexFileHeader* header =
3484 AsUnalignedDexFileHeader(dex_container_->GetMainSection()->Begin());
3485 oat_dex_file->dex_file_size_ = header->file_size_;
3486 dex_src = dex_container_->GetMainSection()->Begin();
3487 } else {
3488 LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
3489 // Since we failed to convert the dex, just copy the input dex.
3490 dex_src = dex_file->Begin();
3491 }
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003492 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003493 {
3494 TimingLogger::ScopedTiming extract("WriteDexFile", timings_);
3495 if (!WriteDexFile(out, oat_dex_file, dex_src, /* update_input_vdex */ false)) {
3496 return false;
3497 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003498 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003499 if (dex_container_ != nullptr) {
3500 // Clear the main section in case we write more data into the container.
3501 dex_container_->GetMainSection()->Clear();
3502 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003503 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003504 return true;
3505}
3506
David Brazdil7b49e6c2016-09-01 11:06:18 +01003507bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003508 File* file,
3509 OatDexFile* oat_dex_file,
3510 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003511 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003512 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003513
3514 // Extract the dex file and get the extracted size.
3515 std::string error_msg;
3516 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3517 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3518 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3519 return false;
3520 }
3521 if (file->Flush() != 0) {
3522 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3523 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3524 return false;
3525 }
3526 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3527 if (extracted_end == static_cast<off_t>(-1)) {
3528 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3529 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3530 return false;
3531 }
3532 if (extracted_end < static_cast<off_t>(start_offset)) {
3533 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3534 << " Start: " << start_offset
3535 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3536 return false;
3537 }
3538 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3539 if (extracted_size < sizeof(DexFile::Header)) {
3540 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3541 << extracted_size << " File: " << oat_dex_file->GetLocation();
3542 return false;
3543 }
3544
3545 // Read the dex file header and extract required data to OatDexFile.
3546 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3547 if (actual_offset != static_cast<off_t>(start_offset)) {
3548 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3549 << " Expected: " << start_offset
3550 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3551 return false;
3552 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003553 if (extracted_size < oat_dex_file->dex_file_size_) {
3554 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3555 << " file size from header: " << oat_dex_file->dex_file_size_
3556 << " File: " << oat_dex_file->GetLocation();
3557 return false;
3558 }
3559
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003560 // Seek both file and stream to the end offset.
3561 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3562 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3563 if (actual_offset != static_cast<off_t>(end_offset)) {
3564 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3565 << " Expected: " << end_offset
3566 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3567 return false;
3568 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003569 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003570 if (actual_offset != static_cast<off_t>(end_offset)) {
3571 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3572 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3573 return false;
3574 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003575 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003576 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3577 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3578 return false;
3579 }
3580
3581 // If we extracted more than the size specified in the header, truncate the file.
3582 if (extracted_size > oat_dex_file->dex_file_size_) {
3583 if (file->SetLength(end_offset) != 0) {
3584 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003585 << " File: " << oat_dex_file->GetLocation()
3586 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003587 return false;
3588 }
3589 }
3590
3591 return true;
3592}
3593
David Brazdil7b49e6c2016-09-01 11:06:18 +01003594bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003595 File* file,
3596 OatDexFile* oat_dex_file,
3597 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003598 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003599 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003600
3601 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3602 if (input_offset != static_cast<off_t>(0)) {
3603 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3604 << " Expected: 0"
3605 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3606 return false;
3607 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003608
3609 // Copy the input dex file using sendfile().
3610 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3611 PLOG(ERROR) << "Failed to copy dex file to oat file."
3612 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3613 return false;
3614 }
3615 if (file->Flush() != 0) {
3616 PLOG(ERROR) << "Failed to flush dex file."
3617 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3618 return false;
3619 }
3620
3621 // Check file position and seek the stream to the end offset.
3622 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3623 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3624 if (actual_offset != static_cast<off_t>(end_offset)) {
3625 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3626 << " Expected: " << end_offset
3627 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3628 return false;
3629 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003630 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003631 if (actual_offset != static_cast<off_t>(end_offset)) {
3632 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3633 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3634 return false;
3635 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003636 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003637 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3638 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3639 return false;
3640 }
3641
3642 return true;
3643}
3644
David Brazdil7b49e6c2016-09-01 11:06:18 +01003645bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003646 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003647 const uint8_t* dex_file,
3648 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003649 // Note: The raw data has already been checked to contain the header
3650 // and all the data that the header specifies as the file size.
3651 DCHECK(dex_file != nullptr);
3652 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3653 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3654
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003655 if (update_input_vdex) {
3656 // The vdex already contains the dex code, no need to write it again.
3657 } else {
3658 if (!out->WriteFully(dex_file, header->file_size_)) {
3659 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3660 << " to " << out->GetLocation();
3661 return false;
3662 }
3663 if (!out->Flush()) {
3664 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3665 << " File: " << oat_dex_file->GetLocation();
3666 return false;
3667 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003668 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003669 return true;
3670}
3671
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003672bool OatWriter::OpenDexFiles(
3673 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003674 bool verify,
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003675 /*out*/ std::vector<MemMap>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003676 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3677 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3678
3679 if (oat_dex_files_.empty()) {
3680 // Nothing to do.
3681 return true;
3682 }
3683
Mathieu Chartier792111c2018-02-15 13:02:15 -08003684 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003685 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003686 std::vector<MemMap> maps;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003687 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3688 std::string error_msg;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003689 maps.emplace_back(oat_dex_file.source_.GetZipEntry()->MapDirectlyOrExtract(
3690 oat_dex_file.dex_file_location_data_, "zipped dex", &error_msg));
3691 MemMap* map = &maps.back();
3692 if (!map->IsValid()) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003693 LOG(ERROR) << error_msg;
3694 return false;
3695 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003696 // Now, open the dex file.
3697 const ArtDexFileLoader dex_file_loader;
3698 dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
3699 map->Size(),
3700 oat_dex_file.GetLocation(),
3701 oat_dex_file.dex_file_location_checksum_,
3702 /* oat_dex_file */ nullptr,
3703 verify,
3704 verify,
3705 &error_msg));
3706 if (dex_files.back() == nullptr) {
3707 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3708 << " Error: " << error_msg;
3709 return false;
3710 }
3711 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3712 }
3713 *opened_dex_files_map = std::move(maps);
3714 *opened_dex_files = std::move(dex_files);
3715 CloseSources();
3716 return true;
3717 }
3718 // We could have closed the sources at the point of writing the dex files, but to
3719 // make it consistent with the case we're not writing the dex files, we close them now.
3720 CloseSources();
3721
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003722 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003723 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003724
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003725 std::string error_msg;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003726 MemMap dex_files_map = MemMap::MapFile(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003727 length,
3728 PROT_READ | PROT_WRITE,
3729 MAP_SHARED,
3730 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003731 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003732 /* low_4gb */ false,
3733 file->GetPath().c_str(),
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003734 &error_msg);
3735 if (!dex_files_map.IsValid()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003736 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3737 << " error: " << error_msg;
3738 return false;
3739 }
David Sehr013fd802018-01-11 22:55:24 -08003740 const ArtDexFileLoader dex_file_loader;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003741 std::vector<std::unique_ptr<const DexFile>> dex_files;
3742 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003743 const uint8_t* raw_dex_file =
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003744 dex_files_map.Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003745
3746 if (kIsDebugBuild) {
3747 // Sanity check our input files.
3748 // Note that ValidateDexFileHeader() logs error messages.
3749 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3750 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003751 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3752 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003753
3754 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3755 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3756 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003757 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3758 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003759 }
3760
3761 // Now, open the dex file.
David Sehr013fd802018-01-11 22:55:24 -08003762 dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
3763 oat_dex_file.dex_file_size_,
3764 oat_dex_file.GetLocation(),
3765 oat_dex_file.dex_file_location_checksum_,
3766 /* oat_dex_file */ nullptr,
3767 verify,
3768 verify,
3769 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003770 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003771 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3772 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003773 return false;
3774 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003775
3776 // Set the class_offsets size now that we have easy access to the DexFile and
David Sehr013fd802018-01-11 22:55:24 -08003777 // it has been verified in dex_file_loader.Open.
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003778 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003779 }
3780
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003781 opened_dex_files_map->push_back(std::move(dex_files_map));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003782 *opened_dex_files = std::move(dex_files);
3783 return true;
3784}
3785
3786bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003787 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003788 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3789 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3790
David Brazdil7b49e6c2016-09-01 11:06:18 +01003791 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3792 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3793 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3794 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3795 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3796 return false;
3797 }
3798
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003799 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3800 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3801 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003802 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3803
3804 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3805 oat_dex_file->class_offsets_.empty()) {
3806 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003807 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003808
3809 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3810 if (table_size == 0u) {
3811 continue;
3812 }
3813
3814 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003815 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003816 const DexFile& dex_file = *opened_dex_files[i];
3817 {
Vladimir Markoea341d22018-05-11 10:33:37 +01003818 TypeLookupTable type_lookup_table = TypeLookupTable::Create(dex_file);
Mathieu Chartier1b868492016-11-16 16:22:37 -08003819 type_lookup_table_oat_dex_files_.push_back(
3820 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3821 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3822 }
Vladimir Markoea341d22018-05-11 10:33:37 +01003823 const TypeLookupTable& table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
3824 DCHECK(table.Valid());
David Brazdil181e1cc2016-09-01 16:38:47 +00003825
3826 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003827 size_t initial_offset = oat_size_;
3828 size_t rodata_offset = RoundUp(initial_offset, 4);
3829 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003830
3831 if (padding_size != 0u) {
3832 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003833 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003834 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3835 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003836 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003837 return false;
3838 }
3839 }
3840
3841 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003842 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
Vladimir Markoea341d22018-05-11 10:33:37 +01003843 DCHECK_EQ(table_size, table.RawDataLength());
David Brazdil181e1cc2016-09-01 16:38:47 +00003844
Vladimir Markoea341d22018-05-11 10:33:37 +01003845 if (!oat_rodata->WriteFully(table.RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003846 PLOG(ERROR) << "Failed to write lookup table."
3847 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003848 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003849 return false;
3850 }
3851
3852 oat_dex_file->lookup_table_offset_ = rodata_offset;
3853
David Brazdil7b49e6c2016-09-01 11:06:18 +01003854 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003855 size_oat_lookup_table_ += table_size;
3856 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003857 }
3858
David Brazdil7b49e6c2016-09-01 11:06:18 +01003859 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003860 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003861 << " File: " << oat_rodata->GetLocation();
3862 return false;
3863 }
3864
3865 return true;
3866}
3867
Mathieu Chartier120aa282017-08-05 16:03:03 -07003868bool OatWriter::WriteDexLayoutSections(
3869 OutputStream* oat_rodata,
3870 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3871 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3872
3873 if (!kWriteDexLayoutInfo) {
3874 return true;;
3875 }
3876
3877 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3878 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3879 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3880 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3881 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3882 return false;
3883 }
3884
3885 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3886 size_t rodata_offset = oat_size_;
3887 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3888 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3889 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3890
3891 // Write dex layout section alignment bytes.
3892 const size_t padding_size =
3893 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3894 if (padding_size != 0u) {
3895 std::vector<uint8_t> buffer(padding_size, 0u);
3896 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3897 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3898 << " File: " << oat_dex_file->GetLocation()
3899 << " Output: " << oat_rodata->GetLocation();
3900 return false;
3901 }
3902 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3903 rodata_offset += padding_size;
3904 }
3905
3906 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3907 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3908 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3909 DCHECK(oat_dex_file != nullptr);
3910 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3911 sizeof(oat_dex_file->dex_sections_layout_))) {
3912 PLOG(ERROR) << "Failed to write dex layout sections."
3913 << " File: " << oat_dex_file->GetLocation()
3914 << " Output: " << oat_rodata->GetLocation();
3915 return false;
3916 }
3917 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3918 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3919 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3920 }
3921 oat_size_ = rodata_offset;
3922
3923 if (!oat_rodata->Flush()) {
3924 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3925 << " File: " << oat_rodata->GetLocation();
3926 return false;
3927 }
3928
3929 return true;
3930}
3931
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003932bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003933 // Write checksums
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003934 off_t checksums_offset = sizeof(VdexFile::VerifierDepsHeader);
3935 off_t actual_offset = vdex_out->Seek(checksums_offset, kSeekSet);
3936 if (actual_offset != checksums_offset) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003937 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3938 << " File: " << vdex_out->GetLocation();
3939 return false;
3940 }
3941
3942 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3943 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3944 if (!vdex_out->WriteFully(
3945 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3946 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3947 << vdex_out->GetLocation();
3948 return false;
3949 }
3950 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3951 }
3952
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003953 // Maybe write dex section header.
3954 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
3955 DCHECK_NE(vdex_quickening_info_offset_, 0u);
3956
3957 bool has_dex_section = extract_dex_files_into_vdex_;
3958 if (has_dex_section) {
3959 DCHECK_NE(vdex_dex_files_offset_, 0u);
3960 size_t dex_section_size = vdex_dex_shared_data_offset_ - vdex_dex_files_offset_;
3961 size_t dex_shared_data_size = vdex_verifier_deps_offset_ - vdex_dex_shared_data_offset_;
3962 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
3963
3964 VdexFile::DexSectionHeader dex_section_header(dex_section_size,
3965 dex_shared_data_size,
3966 quickening_info_section_size);
3967 if (!vdex_out->WriteFully(&dex_section_header, sizeof(VdexFile::DexSectionHeader))) {
3968 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
3969 return false;
3970 }
3971 size_vdex_header_ += sizeof(VdexFile::DexSectionHeader);
3972 }
3973
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003974 // Write header.
3975 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003976 if (actual_offset != 0) {
3977 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3978 << " File: " << vdex_out->GetLocation();
3979 return false;
3980 }
3981
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003982 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003983
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003984 VdexFile::VerifierDepsHeader deps_header(
3985 oat_dex_files_.size(), verifier_deps_section_size, has_dex_section);
3986 if (!vdex_out->WriteFully(&deps_header, sizeof(VdexFile::VerifierDepsHeader))) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003987 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003988 return false;
3989 }
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003990 size_vdex_header_ += sizeof(VdexFile::VerifierDepsHeader);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003991
David Brazdil5d5a36b2016-09-14 15:34:10 +01003992 if (!vdex_out->Flush()) {
3993 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3994 << " File: " << vdex_out->GetLocation();
3995 return false;
3996 }
3997
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003998 return true;
3999}
4000
Vladimir Markof4da6752014-08-01 19:04:18 +01004001bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004002 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
4003}
4004
4005bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004006 static const uint8_t kPadding[] = {
4007 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
4008 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004009 DCHECK_LE(size, sizeof(kPadding));
4010 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004011 return false;
4012 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004013 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01004014 return true;
4015}
4016
Vladimir Marko944da602016-02-19 12:27:55 +00004017void OatWriter::SetMultiOatRelativePatcherAdjustment() {
4018 DCHECK(dex_files_ != nullptr);
4019 DCHECK(relative_patcher_ != nullptr);
4020 DCHECK_NE(oat_data_offset_, 0u);
4021 if (image_writer_ != nullptr && !dex_files_->empty()) {
4022 // The oat data begin may not be initialized yet but the oat file offset is ready.
4023 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
4024 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
4025 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01004026 }
4027}
4028
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004029OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
4030 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004031 CreateTypeLookupTable create_type_lookup_table,
4032 uint32_t dex_file_location_checksum,
4033 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004034 : source_(source),
4035 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004036 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004037 offset_(0),
4038 dex_file_location_size_(strlen(dex_file_location)),
4039 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004040 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004041 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004042 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004043 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00004044 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00004045 type_bss_mapping_offset_(0u),
4046 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004047 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004048 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07004049}
4050
4051size_t OatWriter::OatDexFile::SizeOf() const {
4052 return sizeof(dex_file_location_size_)
4053 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08004054 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08004055 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004056 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004057 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004058 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00004059 + sizeof(type_bss_mapping_offset_)
4060 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004061 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004062}
4063
4064bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
4065 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08004066 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004067
Vladimir Markoe079e212016-05-25 12:49:49 +01004068 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004069 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004070 return false;
4071 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004072 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004073
Vladimir Markoe079e212016-05-25 12:49:49 +01004074 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004075 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004076 return false;
4077 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004078 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004079
Vladimir Markoe079e212016-05-25 12:49:49 +01004080 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004081 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004082 return false;
4083 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004084 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004085
Vladimir Markoe079e212016-05-25 12:49:49 +01004086 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004087 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08004088 return false;
4089 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004090 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004091
Vladimir Markoe079e212016-05-25 12:49:49 +01004092 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004093 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
4094 return false;
4095 }
4096 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
4097
Vladimir Markoe079e212016-05-25 12:49:49 +01004098 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03004099 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
4100 return false;
4101 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004102 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004103
Mathieu Chartier120aa282017-08-05 16:03:03 -07004104 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4105 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4106 return false;
4107 }
4108 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4109
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004110 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4111 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4112 return false;
4113 }
4114 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4115
Vladimir Markof3c52b42017-11-17 17:32:12 +00004116 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4117 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4118 return false;
4119 }
4120 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4121
4122 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4123 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4124 return false;
4125 }
4126 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4127
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004128 return true;
4129}
4130
4131bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004132 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004133 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4134 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004135 return false;
4136 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004137 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004138 return true;
4139}
4140
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004141OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004142 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004143 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004144 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004145 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004146 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004147
Brian Carlstromba150c32013-08-27 17:31:03 -07004148 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4149
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004150 method_offsets_.resize(compiled_methods_with_code);
4151 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004152
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004153 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4154 // We only create this instance if there are at least some compiled.
4155 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004156 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004157 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4158 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4159 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4160 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004161 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004162 method_bitmap_size_ = 0;
4163 }
4164
4165 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004166 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004167 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004168 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4169 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004170 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004171 method_bitmap_->SetBit(i);
4172 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004173 } else {
4174 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004175 }
4176 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004177}
4178
Brian Carlstrom265091e2013-01-30 14:08:26 -08004179size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004180 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004181 + method_bitmap_size_
4182 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004183}
4184
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004185bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4186 OutputStream* out,
4187 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004188 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004189 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004190 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004191 return false;
4192 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004193 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004194
Vladimir Markoe079e212016-05-25 12:49:49 +01004195 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004196 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004197 return false;
4198 }
4199 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004200 return true;
4201}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004202
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004203bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004204 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004205 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004206 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004207 return false;
4208 }
4209 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004210
Vladimir Markoe079e212016-05-25 12:49:49 +01004211 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004212 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004213 return false;
4214 }
4215 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4216 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004217
Vladimir Markoe079e212016-05-25 12:49:49 +01004218 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004219 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004220 return false;
4221 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004222 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004223 return true;
4224}
4225
David Srbecky32210b92017-12-04 14:39:21 +00004226debug::DebugInfo OatWriter::GetDebugInfo() const {
4227 debug::DebugInfo debug_info{};
4228 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
David Srbecky96c84462018-02-05 15:42:40 +00004229 if (VdexWillContainDexFiles()) {
David Srbecky25931622018-01-18 22:55:20 +00004230 DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
4231 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
4232 const DexFile* dex_file = (*dex_files_)[i];
4233 const OatDexFile& oat_dex_file = oat_dex_files_[i];
David Srbecky96c84462018-02-05 15:42:40 +00004234 uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
4235 if (dex_file_offset != 0) {
4236 debug_info.dex_files.emplace(dex_file_offset, dex_file);
4237 }
David Srbecky32210b92017-12-04 14:39:21 +00004238 }
4239 }
4240 return debug_info;
4241}
4242
Vladimir Marko74527972016-11-29 15:57:32 +00004243} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004244} // namespace art