blob: 260888e81892a0af35cf9f2ae64b2384ccee8535 [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"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070031#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010032#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010033#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000035#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000036#include "dex_file-inl.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070037#include "dex_file_loader.h"
Andreas Gampee2abbc62017-09-15 11:59:26 -070038#include "dex_file_types.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070039#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070040#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000041#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010042#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030044#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010045#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010046#include "linker/buffered_output_stream.h"
47#include "linker/file_output_stream.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000048#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010049#include "linker/linker_patch.h"
Vladimir Marko944da602016-02-19 12:27:55 +000050#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000051#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/array.h"
53#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010054#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070055#include "mirror/object-inl.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070056#include "standard_dex_file.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010057#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070058#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070059#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070060#include "scoped_thread_state_change-inl.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030061#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010062#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010063#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010064#include "verifier/verifier_deps.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000065#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070066
67namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000068namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070069
Vladimir Marko9bdf1082016-01-21 12:15:52 +000070namespace { // anonymous namespace
71
Mathieu Chartier120aa282017-08-05 16:03:03 -070072// If we write dex layout info in the oat file.
73static constexpr bool kWriteDexLayoutInfo = true;
74
Igor Murashkin545412b2017-08-17 15:26:54 -070075// Force the OAT method layout to be sorted-by-name instead of
76// the default (class_def_idx, method_idx).
77//
78// Otherwise if profiles are used, that will act as
79// the primary sort order.
80//
81// A bit easier to use for development since oatdump can easily
82// show that things are being re-ordered when two methods aren't adjacent.
83static constexpr bool kOatWriterForceOatCodeLayout = false;
84
85static constexpr bool kOatWriterDebugOatCodeLayout = false;
86
Vladimir Marko9bdf1082016-01-21 12:15:52 +000087typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
88
89const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
90 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
91}
92
Vladimir Markoe079e212016-05-25 12:49:49 +010093class ChecksumUpdatingOutputStream : public OutputStream {
94 public:
95 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
96 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
97
98 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
99 oat_header_->UpdateChecksum(buffer, byte_count);
100 return out_->WriteFully(buffer, byte_count);
101 }
102
103 off_t Seek(off_t offset, Whence whence) OVERRIDE {
104 return out_->Seek(offset, whence);
105 }
106
107 bool Flush() OVERRIDE {
108 return out_->Flush();
109 }
110
111 private:
112 OutputStream* const out_;
113 OatHeader* const oat_header_;
114};
115
Vladimir Marko0c737df2016-08-01 16:33:16 +0100116inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
117 // We want to align the code rather than the preheader.
118 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
119 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
120 return aligned_code_offset - unaligned_code_offset;
121}
122
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000123} // anonymous namespace
124
125// Defines the location of the raw dex file to write.
126class OatWriter::DexFileSource {
127 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800128 enum Type {
129 kNone,
130 kZipEntry,
131 kRawFile,
132 kRawData,
133 };
134
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000135 explicit DexFileSource(ZipEntry* zip_entry)
136 : type_(kZipEntry), source_(zip_entry) {
137 DCHECK(source_ != nullptr);
138 }
139
140 explicit DexFileSource(File* raw_file)
141 : type_(kRawFile), source_(raw_file) {
142 DCHECK(source_ != nullptr);
143 }
144
145 explicit DexFileSource(const uint8_t* dex_file)
146 : type_(kRawData), source_(dex_file) {
147 DCHECK(source_ != nullptr);
148 }
149
Mathieu Chartier497d5262017-02-28 20:17:30 -0800150 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000151 bool IsZipEntry() const { return type_ == kZipEntry; }
152 bool IsRawFile() const { return type_ == kRawFile; }
153 bool IsRawData() const { return type_ == kRawData; }
154
155 ZipEntry* GetZipEntry() const {
156 DCHECK(IsZipEntry());
157 DCHECK(source_ != nullptr);
158 return static_cast<ZipEntry*>(const_cast<void*>(source_));
159 }
160
161 File* GetRawFile() const {
162 DCHECK(IsRawFile());
163 DCHECK(source_ != nullptr);
164 return static_cast<File*>(const_cast<void*>(source_));
165 }
166
167 const uint8_t* GetRawData() const {
168 DCHECK(IsRawData());
169 DCHECK(source_ != nullptr);
170 return static_cast<const uint8_t*>(source_);
171 }
172
173 void Clear() {
174 type_ = kNone;
175 source_ = nullptr;
176 }
177
178 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000179 Type type_;
180 const void* source_;
181};
182
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700183// OatClassHeader is the header only part of the oat class that is required even when compilation
184// is not enabled.
185class OatWriter::OatClassHeader {
186 public:
187 OatClassHeader(uint32_t offset,
188 uint32_t num_non_null_compiled_methods,
189 uint32_t num_methods,
190 mirror::Class::Status status)
191 : status_(status),
192 offset_(offset) {
193 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
194 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
195 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
196 if (num_non_null_compiled_methods == 0) {
197 type_ = kOatClassNoneCompiled;
198 } else if (num_non_null_compiled_methods == num_methods) {
199 type_ = kOatClassAllCompiled;
200 } else {
201 type_ = kOatClassSomeCompiled;
202 }
203 }
204
205 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
206
207 static size_t SizeOf() {
208 return sizeof(status_) + sizeof(type_);
209 }
210
211 // Data to write.
212 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
213 int16_t status_;
214
215 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
216 uint16_t type_;
217
218 // Offset of start of OatClass from beginning of OatHeader. It is
219 // used to validate file position when writing.
220 uint32_t offset_;
221};
222
223// The actual oat class body contains the information about compiled methods. It is only required
224// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000225class OatWriter::OatClass {
226 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700227 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100228 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700229 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000230 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000231 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700232 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000233
234 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
235 return compiled_methods_[class_def_method_index];
236 }
237
Vladimir Marko49b0f452015-12-10 13:49:19 +0000238 // CompiledMethods for each class_def_method_index, or null if no method is available.
239 dchecked_vector<CompiledMethod*> compiled_methods_;
240
241 // Offset from OatClass::offset_ to the OatMethodOffsets for the
242 // class_def_method_index. If 0, it means the corresponding
243 // CompiledMethod entry in OatClass::compiled_methods_ should be
244 // null and that the OatClass::type_ should be kOatClassBitmap.
245 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
246
247 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248 uint32_t method_bitmap_size_;
249
250 // bit vector indexed by ClassDef method index. When
251 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
252 // method has an OatMethodOffsets in methods_offsets_, otherwise
253 // the entry was ommited to save space. If OatClassType::type_ is
254 // not is kOatClassBitmap, the bitmap will be null.
255 std::unique_ptr<BitVector> method_bitmap_;
256
257 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
258 // present in the OatClass. Note that some may be missing if
259 // OatClass::compiled_methods_ contains null values (and
260 // oat_method_offsets_offsets_from_oat_class_ should contain 0
261 // values in this case).
262 dchecked_vector<OatMethodOffsets> method_offsets_;
263 dchecked_vector<OatQuickMethodHeader> method_headers_;
264
265 private:
266 size_t GetMethodOffsetsRawSize() const {
267 return method_offsets_.size() * sizeof(method_offsets_[0]);
268 }
269
270 DISALLOW_COPY_AND_ASSIGN(OatClass);
271};
272
273class OatWriter::OatDexFile {
274 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000275 OatDexFile(const char* dex_file_location,
276 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000277 CreateTypeLookupTable create_type_lookup_table,
278 uint32_t dex_file_location_checksun,
279 size_t dex_file_size);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000280 OatDexFile(OatDexFile&& src) = default;
281
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000282 const char* GetLocation() const {
283 return dex_file_location_data_;
284 }
285
Vladimir Marko49b0f452015-12-10 13:49:19 +0000286 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000287 bool Write(OatWriter* oat_writer, OutputStream* out) const;
288 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
289
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100290 size_t GetClassOffsetsRawSize() const {
291 return class_offsets_.size() * sizeof(class_offsets_[0]);
292 }
293
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000294 // The source of the dex file.
295 DexFileSource source_;
296
297 // Whether to create the type lookup table.
298 CreateTypeLookupTable create_type_lookup_table_;
299
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000300 // Dex file size. Passed in the constructor, but could be
301 // overwritten by LayoutAndWriteDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000302 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000303
304 // Offset of start of OatDexFile from beginning of OatHeader. It is
305 // used to validate file position when writing.
306 size_t offset_;
307
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000308 ///// Start of data to write to vdex/oat file.
309
310 const uint32_t dex_file_location_size_;
311 const char* const dex_file_location_data_;
312
313 // The checksum of the dex file.
314 const uint32_t dex_file_location_checksum_;
315
316 // Offset of the dex file in the vdex file. Set when writing dex files in
317 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000318 uint32_t dex_file_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000319
320 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000321 uint32_t lookup_table_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000322
323 // Class and BSS offsets set in PrepareLayout.
324 uint32_t class_offsets_offset_;
Nicolas Geoffray715d6722017-11-20 22:28:46 +0000325 uint32_t method_bss_mapping_offset_;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000326 uint32_t type_bss_mapping_offset_;
327 uint32_t string_bss_mapping_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000328
329 // Offset of dex sections that will have different runtime madvise states.
330 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700331 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000332
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000333 // Data to write to a separate section. We set the length
334 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000335 dchecked_vector<uint32_t> class_offsets_;
336
Mathieu Chartier120aa282017-08-05 16:03:03 -0700337 // Dex section layout info to serialize.
338 DexLayoutSections dex_sections_layout_;
339
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000340 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000341 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000342 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
343};
344
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100345#define DCHECK_OFFSET() \
346 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
347 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
348
349#define DCHECK_OFFSET_() \
350 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
351 << "file_offset=" << file_offset << " offset_=" << offset_
352
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700353OatWriter::OatWriter(bool compiling_boot_image,
354 TimingLogger* timings,
355 ProfileCompilationInfo* info,
356 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000357 : write_state_(WriteState::kAddingDexFileSources),
358 timings_(timings),
359 raw_dex_files_(),
360 zip_archives_(),
361 zipped_dex_files_(),
362 zipped_dex_file_locations_(),
363 compiler_driver_(nullptr),
364 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800365 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000366 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100367 vdex_size_(0u),
368 vdex_dex_files_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100369 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100370 vdex_quickening_info_offset_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100371 oat_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000372 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000373 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100374 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000375 bss_roots_offset_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100376 bss_method_entry_references_(),
377 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000378 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000379 bss_string_entries_(),
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100380 map_boot_image_tables_to_bss_(false),
Vladimir Markof4da6752014-08-01 19:04:18 +0100381 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700382 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100383 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000384 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700385 size_dex_file_alignment_(0),
386 size_executable_offset_alignment_(0),
387 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700388 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700389 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100390 size_verifier_deps_(0),
391 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100392 size_quickening_info_(0),
393 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700394 size_interpreter_to_interpreter_bridge_(0),
395 size_interpreter_to_compiled_code_bridge_(0),
396 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800397 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700398 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700399 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700400 size_quick_to_interpreter_bridge_(0),
401 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100402 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700403 size_code_(0),
404 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100405 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100406 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700407 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700408 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700409 size_oat_dex_file_location_size_(0),
410 size_oat_dex_file_location_data_(0),
411 size_oat_dex_file_location_checksum_(0),
412 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000413 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000414 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700415 size_oat_dex_file_dex_layout_sections_offset_(0),
416 size_oat_dex_file_dex_layout_sections_(0),
417 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100418 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000419 size_oat_dex_file_type_bss_mapping_offset_(0),
420 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000421 size_oat_lookup_table_alignment_(0),
422 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000423 size_oat_class_offsets_alignment_(0),
424 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700425 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700426 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700427 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100428 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100429 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000430 size_type_bss_mappings_(0u),
431 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000432 relative_patcher_(nullptr),
Jeff Hao608f2ce2016-10-19 11:17:11 -0700433 absolute_patch_locations_(),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700434 profile_compilation_info_(info),
435 compact_dex_level_(compact_dex_level) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000436}
437
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000438static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
439 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
440 if (!valid_standard_dex_magic) {
441 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
442 return false;
443 }
444 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
445 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
446 return false;
447 }
448 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
449 if (header->file_size_ < sizeof(DexFile::Header)) {
450 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
451 << " File: " << location;
452 return false;
453 }
454 return true;
455}
456
457static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
458 uint8_t* raw_header,
459 const char* location) {
460 // Read the dex file header and perform minimal verification.
461 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
462 PLOG(ERROR) << "Failed to read dex file header. Actual: "
463 << " File: " << location << " Output: " << file->GetPath();
464 return nullptr;
465 }
466 if (!ValidateDexFileHeader(raw_header, location)) {
467 return nullptr;
468 }
469
470 return AsUnalignedDexFileHeader(raw_header);
471}
472
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000473bool OatWriter::AddDexFileSource(const char* filename,
474 const char* location,
475 CreateTypeLookupTable create_type_lookup_table) {
476 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
477 uint32_t magic;
478 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700479 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
480 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
482 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700483 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000484 uint8_t raw_header[sizeof(DexFile::Header)];
485 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
486 if (header == nullptr) {
487 return false;
488 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 // The file is open for reading, not writing, so it's OK to let the File destructor
490 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700491 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000492 oat_dex_files_.emplace_back(/* OatDexFile */
493 location,
494 DexFileSource(raw_dex_files_.back().get()),
495 create_type_lookup_table,
496 header->checksum_,
497 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000498 } else if (IsZipMagic(magic)) {
499 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
500 return false;
501 }
502 } else {
503 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
504 return false;
505 }
506 return true;
507}
508
509// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700510bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000511 const char* location,
512 CreateTypeLookupTable create_type_lookup_table) {
513 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
514 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700515 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000516 ZipArchive* zip_archive = zip_archives_.back().get();
517 if (zip_archive == nullptr) {
518 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
519 << error_msg;
520 return false;
521 }
522 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700523 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000524 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
525 if (entry == nullptr) {
526 break;
527 }
528 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700529 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000531 // We override the checksum from header with the CRC from ZIP entry.
532 oat_dex_files_.emplace_back(/* OatDexFile */
533 full_location,
534 DexFileSource(zipped_dex_files_.back().get()),
535 create_type_lookup_table,
536 zipped_dex_files_.back()->GetCrc32(),
537 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000538 }
539 if (zipped_dex_file_locations_.empty()) {
540 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
541 return false;
542 }
543 return true;
544}
545
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000546// Add dex file source(s) from a vdex file specified by a file handle.
547bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
548 const char* location,
549 CreateTypeLookupTable create_type_lookup_table) {
550 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
551 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000552 for (size_t i = 0; i < vdex_file.GetHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000553 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
554 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000555 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
556 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000557 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700558
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700559 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000560 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
561 return false;
562 }
563 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700564 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000565 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000566 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
567 oat_dex_files_.emplace_back(/* OatDexFile */
568 full_location,
569 DexFileSource(current_dex_data),
570 create_type_lookup_table,
571 vdex_file.GetLocationChecksum(i),
572 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000573 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000574
575 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
576 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
577 return false;
578 }
579
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000580 if (oat_dex_files_.empty()) {
581 LOG(ERROR) << "No dex files in vdex file created from " << location;
582 return false;
583 }
584 return true;
585}
586
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000587// Add dex file source from raw memory.
588bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
589 const char* location,
590 uint32_t location_checksum,
591 CreateTypeLookupTable create_type_lookup_table) {
592 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
593 if (data.size() < sizeof(DexFile::Header)) {
594 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
595 << data.size() << " File: " << location;
596 return false;
597 }
598 if (!ValidateDexFileHeader(data.data(), location)) {
599 return false;
600 }
601 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
602 if (data.size() < header->file_size_) {
603 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
604 << " file size from header: " << header->file_size_ << " File: " << location;
605 return false;
606 }
607
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000608 oat_dex_files_.emplace_back(/* OatDexFile */
609 location,
610 DexFileSource(data.data()),
611 create_type_lookup_table,
612 location_checksum,
613 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000614 return true;
615}
616
Calin Juravle1ce70852017-06-28 10:59:03 -0700617dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
618 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000619 locations.reserve(oat_dex_files_.size());
620 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
621 locations.push_back(oat_dex_file.GetLocation());
622 }
623 return locations;
624}
625
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700626bool OatWriter::MayHaveCompiledMethods() const {
627 return CompilerFilter::IsAnyCompilationEnabled(
628 GetCompilerDriver()->GetCompilerOptions().GetCompilerFilter());
629}
630
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000631bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100632 File* vdex_file,
633 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000634 InstructionSet instruction_set,
635 const InstructionSetFeatures* instruction_set_features,
636 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800637 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000638 bool update_input_vdex,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000639 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
640 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
641 CHECK(write_state_ == WriteState::kAddingDexFileSources);
642
David Brazdil7b49e6c2016-09-01 11:06:18 +0100643 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
644 if (!RecordOatDataOffset(oat_rodata)) {
645 return false;
646 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000647
648 std::unique_ptr<MemMap> dex_files_map;
649 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100650
651 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000652
653 // Reserve space for Vdex header and checksums.
654 vdex_size_ = sizeof(VdexFile::Header) + oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100655 oat_size_ = InitOatHeader(instruction_set,
656 instruction_set_features,
657 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
658 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100659
660 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, oat_header_.get());
661
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000662 std::unique_ptr<BufferedOutputStream> vdex_out =
663 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
664 // Write DEX files into VDEX, mmap and open them.
665 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex) ||
666 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
667 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000668 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000669
Mathieu Chartier120aa282017-08-05 16:03:03 -0700670 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000671 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
672 return false;
673 }
674
Mathieu Chartier120aa282017-08-05 16:03:03 -0700675 // Write dex layout sections into the oat file.
676 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
677 return false;
678 }
679
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000680 *opened_dex_files_map = std::move(dex_files_map);
681 *opened_dex_files = std::move(dex_files);
682 write_state_ = WriteState::kPrepareLayout;
683 return true;
684}
685
Vladimir Marko74527972016-11-29 15:57:32 +0000686void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000687 CHECK(write_state_ == WriteState::kPrepareLayout);
688
Vladimir Marko944da602016-02-19 12:27:55 +0000689 relative_patcher_ = relative_patcher;
690 SetMultiOatRelativePatcherAdjustment();
691
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000692 if (compiling_boot_image_) {
693 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800694 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100695 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000696 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100697
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100698 {
699 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
700 InitBssLayout(instruction_set);
701 }
702
David Brazdil7b49e6c2016-09-01 11:06:18 +0100703 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800704 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100705 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
706 offset = InitClassOffsets(offset);
707 }
708 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000709 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800710 offset = InitOatClasses(offset);
711 }
712 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000713 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
714 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100715 }
716 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000717 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100718 offset = InitOatMaps(offset);
719 }
720 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100721 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
722 oat_header_->SetOatDexFilesOffset(offset);
723 offset = InitOatDexFiles(offset);
724 }
725 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000726 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800727 offset = InitOatCode(offset);
728 }
729 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000730 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800731 offset = InitOatCodeDexFiles(offset);
732 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100733 oat_size_ = offset;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100734 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100735
Brian Carlstrome24fa612011-09-29 00:53:55 -0700736 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800737 if (compiling_boot_image_) {
738 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000739 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800740 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000741
742 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700743}
744
Ian Rogers0571d352011-11-03 19:51:38 -0700745OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700746}
747
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100748class OatWriter::DexMethodVisitor {
749 public:
750 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100751 : writer_(writer),
752 offset_(offset),
753 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700754 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755
756 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
757 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700758 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100759 dex_file_ = dex_file;
760 class_def_index_ = class_def_index;
761 return true;
762 }
763
764 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
765
766 virtual bool EndClass() {
767 if (kIsDebugBuild) {
768 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700769 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100770 }
771 return true;
772 }
773
774 size_t GetOffset() const {
775 return offset_;
776 }
777
778 protected:
779 virtual ~DexMethodVisitor() { }
780
781 OatWriter* const writer_;
782
783 // The offset is usually advanced for each visited method by the derived class.
784 size_t offset_;
785
786 // The dex file and class def index are set in StartClass().
787 const DexFile* dex_file_;
788 size_t class_def_index_;
789};
790
791class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
792 public:
793 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100794 : DexMethodVisitor(writer, offset),
795 oat_class_index_(0u),
796 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100797
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100798 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100799 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700800 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
801 // There are no oat classes if there aren't any compiled methods.
802 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
803 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100804 method_offsets_index_ = 0u;
805 return true;
806 }
807
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100808 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100809 ++oat_class_index_;
810 return DexMethodVisitor::EndClass();
811 }
812
813 protected:
814 size_t oat_class_index_;
815 size_t method_offsets_index_;
816};
817
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100818static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000819 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100820}
821
822static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000823 // The dextodexcompiler puts the quickening info table into the CompiledMethod
824 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100825 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
826}
827
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100828class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
829 public:
830 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
831 : DexMethodVisitor(writer, /* offset */ 0u) {}
832
833 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
834 const ClassDataItemIterator& it) OVERRIDE {
835 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
836 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
837 MethodReference(dex_file_, it.GetMemberIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100838 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100839 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
840 if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
841 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000842 AddBssReference(target_method,
843 target_method.dex_file->NumMethodIds(),
844 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100845 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
846 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000847 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
848 AddBssReference(target_type,
849 target_type.dex_file->NumTypeIds(),
850 &writer_->bss_type_entry_references_);
851 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100852 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000853 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
854 AddBssReference(target_string,
855 target_string.dex_file->NumStringIds(),
856 &writer_->bss_string_entry_references_);
857 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko94ec2db2017-09-06 17:21:03 +0100858 } else if (patch.GetType() == LinkerPatch::Type::kStringInternTable ||
859 patch.GetType() == LinkerPatch::Type::kTypeClassTable) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100860 writer_->map_boot_image_tables_to_bss_ = true;
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100861 }
862 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100863 } else {
864 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100865 }
866 return true;
867 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000868
869 private:
870 void AddBssReference(const DexFileReference& ref,
871 size_t number_of_indexes,
872 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
873 // We currently support inlining of throwing instructions only when they originate in the
874 // same dex file as the outer method. All .bss references are used by throwing instructions.
875 DCHECK_EQ(dex_file_, ref.dex_file);
876
877 auto refs_it = references->find(ref.dex_file);
878 if (refs_it == references->end()) {
879 refs_it = references->Put(
880 ref.dex_file,
881 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
882 refs_it->second.ClearAllBits();
883 }
884 refs_it->second.SetBit(ref.index);
885 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100886};
887
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100888class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
889 public:
890 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100891 : DexMethodVisitor(writer, offset),
892 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100893 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000894 size_t num_classes = 0u;
895 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
896 num_classes += oat_dex_file.class_offsets_.size();
897 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700898 // If we aren't compiling only reserve headers.
899 writer_->oat_class_headers_.reserve(num_classes);
900 if (writer->MayHaveCompiledMethods()) {
901 writer->oat_classes_.reserve(num_classes);
902 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100903 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100904 // If there are any classes, the class offsets allocation aligns the offset.
905 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100906 }
907
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100908 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100909 DexMethodVisitor::StartClass(dex_file, class_def_index);
910 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100911 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100912 return true;
913 }
914
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300915 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100916 const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100917 // Fill in the compiled_methods_ array for methods that have a
918 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100919 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100920 // OatMethodOffsets for the compiled methods.
921 uint32_t method_idx = it.GetMemberIndex();
922 CompiledMethod* compiled_method =
923 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
924 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100925 if (HasCompiledCode(compiled_method)) {
926 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100927 }
928 return true;
929 }
930
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100931 bool EndClass() OVERRIDE {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100932 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100933 mirror::Class::Status status;
Andreas Gampebb846102017-05-11 21:03:35 -0700934 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
935 if (!found) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700936 VerificationResults* results = writer_->compiler_driver_->GetVerificationResults();
937 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700938 // The oat class status is used only for verification of resolved classes,
939 // so use kStatusErrorResolved whether the class was resolved or unresolved
940 // during compile-time verification.
941 status = mirror::Class::kStatusErrorResolved;
942 } else {
943 status = mirror::Class::kStatusNotReady;
944 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100945 }
946
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700947 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100948 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700949 compiled_methods_.size(),
950 status);
951 OatClassHeader& header = writer_->oat_class_headers_.back();
952 offset_ += header.SizeOf();
953 if (writer_->MayHaveCompiledMethods()) {
954 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100955 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700956 header.type_);
957 offset_ += writer_->oat_classes_.back().SizeOf();
958 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100959 return DexMethodVisitor::EndClass();
960 }
961
962 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000963 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100964 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100965};
966
Igor Murashkin545412b2017-08-17 15:26:54 -0700967// CompiledMethod + metadata required to do ordered method layout.
968//
969// See also OrderedMethodVisitor.
970struct OatWriter::OrderedMethodData {
971 ProfileCompilationInfo::MethodHotness method_hotness;
972 OatClass* oat_class;
973 CompiledMethod* compiled_method;
974 MethodReference method_reference;
975 size_t method_offsets_index;
976
977 size_t class_def_index;
978 uint32_t access_flags;
979 const DexFile::CodeItem* code_item;
980
981 // A value of -1 denotes missing debug info
982 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
983 // Index into writer_->method_info_
984 size_t debug_info_idx;
985
986 bool HasDebugInfo() const {
987 return debug_info_idx != kDebugInfoIdxInvalid;
988 }
989
990 // Bin each method according to the profile flags.
991 //
992 // Groups by e.g.
993 // -- not hot at all
994 // -- hot
995 // -- hot and startup
996 // -- hot and post-startup
997 // -- hot and startup and poststartup
998 // -- startup
999 // -- startup and post-startup
1000 // -- post-startup
1001 //
1002 // (See MethodHotness enum definition for up-to-date binning order.)
1003 bool operator<(const OrderedMethodData& other) const {
1004 if (kOatWriterForceOatCodeLayout) {
1005 // Development flag: Override default behavior by sorting by name.
1006
1007 std::string name = method_reference.PrettyMethod();
1008 std::string other_name = other.method_reference.PrettyMethod();
1009 return name < other_name;
1010 }
1011
1012 // Use the profile's method hotness to determine sort order.
1013 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1014 return true;
1015 }
1016
1017 // Default: retain the original order.
1018 return false;
1019 }
1020
1021 private:
1022 // Used to determine relative order for OAT code layout when determining
1023 // binning.
1024 size_t GetMethodHotnessOrder() const {
1025 bool hotness[] = {
1026 method_hotness.IsHot(),
1027 method_hotness.IsStartup(),
1028 method_hotness.IsPostStartup()
1029 };
1030
1031
1032 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1033 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1034 // time that memory is referenced in the process.
1035
1036 size_t hotness_bits = 0;
1037 for (size_t i = 0; i < arraysize(hotness); ++i) {
1038 if (hotness[i]) {
1039 hotness_bits |= (1 << i);
1040 }
1041 }
1042
1043 if (kIsDebugBuild) {
1044 // Check for bins that are always-empty given a real profile.
1045 if (method_hotness.IsHot() &&
1046 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1047 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001048 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1049 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001050 // This is not fatal, so only warn.
1051 }
1052 }
1053
1054 return hotness_bits;
1055 }
1056};
1057
1058// Given a queue of CompiledMethod in some total order,
1059// visit each one in that order.
1060class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001061 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001062 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1063 : ordered_methods_(std::move(ordered_methods)) {
1064 }
1065
1066 virtual ~OrderedMethodVisitor() {}
1067
1068 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1069 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1070 if (!VisitStart()) {
1071 return false;
1072 }
1073
1074 for (const OrderedMethodData& method_data : ordered_methods_) {
1075 if (!VisitMethod(method_data)) {
1076 return false;
1077 }
1078 }
1079
1080 return VisitComplete();
1081 }
1082
1083 // Invoked once at the beginning, prior to visiting anything else.
1084 //
1085 // Return false to abort further visiting.
1086 virtual bool VisitStart() { return true; }
1087
1088 // Invoked repeatedly in the order specified by `ordered_methods`.
1089 //
1090 // Return false to short-circuit and to stop visiting further methods.
1091 virtual bool VisitMethod(const OrderedMethodData& method_data)
1092 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1093
1094 // Invoked once at the end, after every other method has been successfully visited.
1095 //
1096 // Return false to indicate the overall `Visit` has failed.
1097 virtual bool VisitComplete() = 0;
1098
1099 OrderedMethodList ReleaseOrderedMethods() {
1100 return std::move(ordered_methods_);
1101 }
1102
1103 private:
1104 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1105 // Methods can be inserted more than once in case of duplicated methods.
1106 OrderedMethodList ordered_methods_;
1107};
1108
1109// Visit every compiled method in order to determine its order within the OAT file.
1110// Methods from the same class do not need to be adjacent in the OAT code.
1111class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1112 public:
1113 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1114 : OatDexMethodVisitor(writer, offset) {
1115 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001116
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001117 bool EndClass() OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +01001118 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001119 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001120 }
1121
Igor Murashkin545412b2017-08-17 15:26:54 -07001122 bool VisitMethod(size_t class_def_method_index,
1123 const ClassDataItemIterator& it)
1124 OVERRIDE
1125 REQUIRES_SHARED(Locks::mutator_lock_) {
1126 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1127
Vladimir Marko49b0f452015-12-10 13:49:19 +00001128 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001129 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1130
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001131 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001132 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001133
Igor Murashkin545412b2017-08-17 15:26:54 -07001134 {
1135 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
1136 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1137 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001138
Igor Murashkin545412b2017-08-17 15:26:54 -07001139 // Debug method info must be pushed in the original order
1140 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1141 // ElfCompilationUnitWriter::Write requires this.
1142 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1143 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1144 writer_->method_info_.push_back(info);
1145
1146 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1147 // once we know the offsets.
1148 //
1149 // Store the index into writer_->method_info_ since future push-backs
1150 // could reallocate and change the underlying data address.
1151 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001152 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001153 }
1154
1155 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1156
1157 // Lookup method hotness from profile, if available.
1158 // Otherwise assume a default of none-hotness.
1159 ProfileCompilationInfo::MethodHotness method_hotness =
1160 writer_->profile_compilation_info_ != nullptr
1161 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1162 : ProfileCompilationInfo::MethodHotness();
1163
1164 // Handle duplicate methods by pushing them repeatedly.
1165 OrderedMethodData method_data = {
1166 method_hotness,
1167 oat_class,
1168 compiled_method,
1169 method_ref,
1170 method_offsets_index_,
1171 class_def_index_,
1172 it.GetMethodAccessFlags(),
1173 it.GetMethodCodeItem(),
1174 debug_info_idx
1175 };
1176 ordered_methods_.push_back(method_data);
1177
1178 method_offsets_index_++;
1179 }
1180
1181 return true;
1182 }
1183
1184 OrderedMethodList ReleaseOrderedMethods() {
1185 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1186 // Sort by the method ordering criteria (in OrderedMethodData).
1187 // Since most methods will have the same ordering criteria,
1188 // we preserve the original insertion order within the same sort order.
1189 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1190 } else {
1191 // The profile-less behavior is as if every method had 0 hotness
1192 // associated with it.
1193 //
1194 // Since sorting all methods with hotness=0 should give back the same
1195 // order as before, don't do anything.
1196 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1197 }
1198
1199 return std::move(ordered_methods_);
1200 }
1201
1202 private:
1203 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1204 // Methods can be inserted more than once in case of duplicated methods.
1205 OrderedMethodList ordered_methods_;
1206};
1207
1208// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1209class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1210 public:
1211 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1212 size_t offset,
1213 OrderedMethodList ordered_methods)
1214 : LayoutReserveOffsetCodeMethodVisitor(writer,
1215 offset,
1216 writer->GetCompilerDriver()->GetCompilerOptions(),
1217 std::move(ordered_methods)) {
1218 }
1219
1220 virtual bool VisitComplete() OVERRIDE {
1221 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1222 if (generate_debug_info_) {
1223 std::vector<debug::MethodDebugInfo> thunk_infos =
1224 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1225 writer_->method_info_.insert(writer_->method_info_.end(),
1226 std::make_move_iterator(thunk_infos.begin()),
1227 std::make_move_iterator(thunk_infos.end()));
1228 }
1229 return true;
1230 }
1231
1232 virtual bool VisitMethod(const OrderedMethodData& method_data)
1233 OVERRIDE
1234 REQUIRES_SHARED(Locks::mutator_lock_) {
1235 OatClass* oat_class = method_data.oat_class;
1236 CompiledMethod* compiled_method = method_data.compiled_method;
1237 const MethodReference& method_ref = method_data.method_reference;
1238 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1239 size_t class_def_index = method_data.class_def_index;
1240 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001241 bool has_debug_info = method_data.HasDebugInfo();
1242 size_t debug_info_idx = method_data.debug_info_idx;
1243
1244 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1245
1246 // Derived from CompiledMethod.
1247 uint32_t quick_code_offset = 0;
1248
1249 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1250 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1251 uint32_t thumb_offset = compiled_method->CodeDelta();
1252
1253 // Deduplicate code arrays if we are not producing debuggable code.
1254 bool deduped = true;
1255 if (debuggable_) {
1256 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1257 if (quick_code_offset != 0u) {
1258 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1259 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001260 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001261 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1262 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001263 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001264 } else {
1265 quick_code_offset = dedupe_map_.GetOrCreate(
1266 compiled_method,
1267 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1268 deduped = false;
1269 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1270 });
1271 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001272
Igor Murashkin545412b2017-08-17 15:26:54 -07001273 if (code_size != 0) {
1274 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1275 // TODO: Should this be a hard failure?
1276 LOG(WARNING) << "Multiple definitions of "
1277 << method_ref.dex_file->PrettyMethod(method_ref.index)
1278 << " offsets " << relative_patcher_->GetOffset(method_ref)
1279 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001280 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001281 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1282 }
1283 }
1284
1285 // Update quick method header.
1286 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1287 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1288 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1289 uint32_t method_info_offset = method_header->GetMethodInfoOffset();
1290 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1291 // to 0-offset and we need to adjust it by code_offset.
1292 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001293 CHECK(!compiled_method->GetQuickCode().empty());
1294 // If the code is compiled, we write the offset of the stack map relative
1295 // to the code.
1296 if (vmap_table_offset != 0u) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001297 vmap_table_offset += code_offset;
1298 DCHECK_LT(vmap_table_offset, code_offset);
1299 }
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001300 if (method_info_offset != 0u) {
1301 method_info_offset += code_offset;
1302 DCHECK_LT(method_info_offset, code_offset);
1303 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001304 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1305 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1306 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1307 *method_header = OatQuickMethodHeader(vmap_table_offset,
1308 method_info_offset,
1309 frame_size_in_bytes,
1310 core_spill_mask,
1311 fp_spill_mask,
1312 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001313
Igor Murashkin545412b2017-08-17 15:26:54 -07001314 if (!deduped) {
1315 // Update offsets. (Checksum is updated when writing.)
1316 offset_ += sizeof(*method_header); // Method header is prepended before code.
1317 offset_ += code_size;
1318 // Record absolute patch locations.
1319 if (!compiled_method->GetPatches().empty()) {
1320 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1321 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1322 if (!patch.IsPcRelative()) {
1323 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001324 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001325 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001326 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001327 }
1328
Igor Murashkin545412b2017-08-17 15:26:54 -07001329 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1330 if (generate_debug_info_ && code_size != 0) {
1331 DCHECK(has_debug_info);
1332
1333 bool has_code_info = method_header->IsOptimized();
1334 // Record debug information for this function if we are doing that.
1335 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1336 DCHECK(info.trampoline_name.empty());
1337 info.dex_file = method_ref.dex_file;
1338 info.class_def_index = class_def_index;
1339 info.dex_method_index = method_ref.index;
1340 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001341 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1342 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001343 info.isa = compiled_method->GetInstructionSet();
1344 info.deduped = deduped;
1345 info.is_native_debuggable = native_debuggable_;
1346 info.is_optimized = method_header->IsOptimized();
1347 info.is_code_address_text_relative = true;
1348 info.code_address = code_offset - executable_offset_;
1349 info.code_size = code_size;
1350 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1351 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
1352 info.cfi = compiled_method->GetCFIInfo();
1353 } else {
1354 DCHECK(!has_debug_info);
1355 }
1356
1357 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1358 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1359 offsets->code_offset_ = quick_code_offset;
1360
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001361 return true;
1362 }
1363
Igor Murashkin545412b2017-08-17 15:26:54 -07001364 size_t GetOffset() const {
1365 return offset_;
1366 }
1367
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001368 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001369 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1370 size_t offset,
1371 const CompilerOptions& compiler_options,
1372 OrderedMethodList ordered_methods)
1373 : OrderedMethodVisitor(std::move(ordered_methods)),
1374 writer_(writer),
1375 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001376 relative_patcher_(writer->relative_patcher_),
1377 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1378 debuggable_(compiler_options.GetDebuggable()),
1379 native_debuggable_(compiler_options.GetNativeDebuggable()),
1380 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {
1381 writer->absolute_patch_locations_.reserve(
1382 writer->GetCompilerDriver()->GetNonRelativeLinkerPatchCount());
1383 }
1384
Vladimir Marko20f85592015-03-19 10:07:02 +00001385 struct CodeOffsetsKeyComparator {
1386 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001387 // Code is deduplicated by CompilerDriver, compare only data pointers.
1388 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1389 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001390 }
1391 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001392 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1393 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001394 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001395 if (UNLIKELY(lhs->GetMethodInfo().data() != rhs->GetMethodInfo().data())) {
1396 return lhs->GetMethodInfo().data() < rhs->GetMethodInfo().data();
1397 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001398 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1399 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001400 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001401 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1402 return rhs->IsIntrinsic();
1403 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001404 return false;
1405 }
1406 };
1407
David Srbecky009e2a62015-04-15 02:46:30 +01001408 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001409 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001410 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001411 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001412 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1413 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001414 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1415 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1416 }
1417
Igor Murashkin545412b2017-08-17 15:26:54 -07001418 OatWriter* writer_;
1419
1420 // Offset of the code of the compiled methods.
1421 size_t offset_;
1422
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001423 // Deduplication is already done on a pointer basis by the compiler driver,
1424 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001425 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001426
Vladimir Marko1b404a82017-09-01 13:35:26 +01001427 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001428 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001429 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001430 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001431 const bool native_debuggable_;
1432 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001433};
1434
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001435class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1436 public:
1437 InitMapMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001438 : OatDexMethodVisitor(writer, offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001439
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001440 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001441 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001442 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001443 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1444
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001445 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001446 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001447 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001448
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001449 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1450 uint32_t map_size = map.size() * sizeof(map[0]);
1451 if (map_size != 0u) {
1452 size_t offset = dedupe_map_.GetOrCreate(
1453 map.data(),
1454 [this, map_size]() {
1455 uint32_t new_offset = offset_;
1456 offset_ += map_size;
1457 return new_offset;
1458 });
1459 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1460 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1461 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001462 }
1463 ++method_offsets_index_;
1464 }
1465
1466 return true;
1467 }
1468
1469 private:
1470 // Deduplication is already done on a pointer basis by the compiler driver,
1471 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +01001472 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001473};
1474
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001475class OatWriter::InitMethodInfoVisitor : public OatDexMethodVisitor {
1476 public:
1477 InitMethodInfoVisitor(OatWriter* writer, size_t offset) : OatDexMethodVisitor(writer, offset) {}
1478
1479 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001480 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001481 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1482 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1483
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001484 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07001485 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1486 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset(), 0u);
1487 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
1488 const uint32_t map_size = map.size() * sizeof(map[0]);
1489 if (map_size != 0u) {
1490 size_t offset = dedupe_map_.GetOrCreate(
1491 map.data(),
1492 [this, map_size]() {
1493 uint32_t new_offset = offset_;
1494 offset_ += map_size;
1495 return new_offset;
1496 });
1497 // Code offset is not initialized yet, so set the map offset to 0u-offset.
1498 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1499 oat_class->method_headers_[method_offsets_index_].SetMethodInfoOffset(0u - offset);
1500 }
1501 ++method_offsets_index_;
1502 }
1503
1504 return true;
1505 }
1506
1507 private:
1508 // Deduplication is already done on a pointer basis by the compiler driver,
1509 // so we can simply compare the pointers to find out if things are duplicated.
1510 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
1511};
1512
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001513class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1514 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001515 InitImageMethodVisitor(OatWriter* writer,
1516 size_t offset,
1517 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001518 : OatDexMethodVisitor(writer, offset),
1519 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001520 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001521 dex_files_(dex_files),
1522 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001523
1524 // Handle copied methods here. Copy pointer to quick code from
1525 // an origin method to a copied method only if they are
1526 // in the same oat file. If the origin and the copied methods are
1527 // in different oat files don't touch the copied method.
1528 // References to other oat files are not supported yet.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001529 bool StartClass(const DexFile* dex_file, size_t class_def_index) OVERRIDE
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001530 REQUIRES_SHARED(Locks::mutator_lock_) {
1531 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1532 // Skip classes that are not in the image.
1533 if (!IsImageClass()) {
1534 return true;
1535 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001536 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001537 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1538 mirror::Class* klass = dex_cache->GetResolvedType(class_def.class_idx_);
1539 if (klass != nullptr) {
1540 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1541 // Find origin method. Declaring class and dex_method_idx
1542 // in the copied method should be the same as in the origin
1543 // method.
1544 mirror::Class* declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001545 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001546 declaring_class->GetDexCache(),
1547 method.GetDexMethodIndex(),
1548 pointer_size_);
1549 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001550 CHECK(!origin->IsDirect());
1551 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001552 if (IsInOatFile(&declaring_class->GetDexFile())) {
1553 const void* code_ptr =
1554 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1555 if (code_ptr == nullptr) {
1556 methods_to_process_.push_back(std::make_pair(&method, origin));
1557 } else {
1558 method.SetEntryPointFromQuickCompiledCodePtrSize(
1559 code_ptr, pointer_size_);
1560 }
1561 }
1562 }
1563 }
1564 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001565 }
1566
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001567 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001568 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001569 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001570 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001571 return true;
1572 }
1573
Vladimir Marko49b0f452015-12-10 13:49:19 +00001574 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001575 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1576
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001577 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001578 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001579 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1580 offsets = oat_class->method_offsets_[method_offsets_index_];
1581 ++method_offsets_index_;
1582 }
1583
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001584 Thread* self = Thread::Current();
1585 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001586 ArtMethod* method;
1587 if (writer_->HasBootImage()) {
1588 const InvokeType invoke_type = it.GetMethodInvokeType(
1589 dex_file_->GetClassDef(class_def_index_));
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001590 // Unchecked as we hold mutator_lock_ on entry.
1591 ScopedObjectAccessUnchecked soa(self);
1592 StackHandleScope<1> hs(self);
Vladimir Markoba118822017-06-12 15:41:56 +01001593 method = class_linker_->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001594 *dex_file_,
1595 it.GetMemberIndex(),
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001596 hs.NewHandle(dex_cache),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001597 ScopedNullHandle<mirror::ClassLoader>(),
1598 nullptr,
1599 invoke_type);
1600 if (method == nullptr) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001601 LOG(FATAL_WITHOUT_ABORT) << "Unexpected failure to resolve a method: "
David Sehr709b0702016-10-13 09:12:37 -07001602 << dex_file_->PrettyMethod(it.GetMemberIndex(), true);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001603 self->AssertPendingException();
1604 mirror::Throwable* exc = self->GetException();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001605 std::string dump = exc->Dump();
1606 LOG(FATAL) << dump;
1607 UNREACHABLE();
1608 }
1609 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001610 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001611 // It may not be resolved if the class failed to verify, in this case, don't set the
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001612 // entrypoint. This is not fatal since we shall use a resolution method.
1613 method = class_linker_->LookupResolvedMethod(it.GetMemberIndex(), dex_cache, class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001614 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001615 if (method != nullptr &&
1616 compiled_method != nullptr &&
1617 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001618 method->SetEntryPointFromQuickCompiledCodePtrSize(
1619 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1620 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001621
1622 return true;
1623 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001624
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001625 // Check whether current class is image class
1626 bool IsImageClass() {
1627 const DexFile::TypeId& type_id =
1628 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1629 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1630 return writer_->GetCompilerDriver()->IsImageClass(class_descriptor);
1631 }
1632
1633 // Check whether specified dex file is in the compiled oat file.
1634 bool IsInOatFile(const DexFile* dex_file) {
1635 return ContainsElement(*dex_files_, dex_file);
1636 }
1637
1638 // Assign a pointer to quick code for copied methods
1639 // not handled in the method StartClass
1640 void Postprocess() {
1641 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1642 ArtMethod* method = p.first;
1643 ArtMethod* origin = p.second;
1644 const void* code_ptr =
1645 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1646 if (code_ptr != nullptr) {
1647 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1648 }
1649 }
1650 }
1651
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001652 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001653 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001654 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001655 const std::vector<const DexFile*>* dex_files_;
1656 ClassLinker* const class_linker_;
1657 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001658};
1659
Igor Murashkin545412b2017-08-17 15:26:54 -07001660class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001661 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001662 WriteCodeMethodVisitor(OatWriter* writer,
1663 OutputStream* out,
1664 const size_t file_offset,
1665 size_t relative_offset,
1666 OrderedMethodList ordered_methods)
1667 : OrderedMethodVisitor(std::move(ordered_methods)),
1668 writer_(writer),
1669 offset_(relative_offset),
1670 dex_file_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001671 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())),
1672 class_loader_(writer->HasImage() ? writer->image_writer_->GetClassLoader() : nullptr),
1673 out_(out),
1674 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001675 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001676 dex_cache_(nullptr),
1677 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001678 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001679 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001680 // If we're creating the image, the address space must be ready so that we can apply patches.
1681 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001682 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001683 }
1684
Igor Murashkin545412b2017-08-17 15:26:54 -07001685 virtual bool VisitStart() OVERRIDE {
1686 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001687 }
1688
Igor Murashkin545412b2017-08-17 15:26:54 -07001689 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001690 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001691 dex_file_ = dex_file;
1692
1693 // Ordered method visiting is only for compiled methods.
1694 DCHECK(writer_->MayHaveCompiledMethods());
1695
Mathieu Chartier72041a02017-07-14 18:23:25 -07001696 if (writer_->GetCompilerDriver()->GetCompilerOptions().IsAotCompilationEnabled()) {
1697 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1698 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1699 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1700 DCHECK(dex_cache_ != nullptr);
1701 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001702 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001703 }
1704
1705 virtual bool VisitComplete() {
1706 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1707 if (UNLIKELY(offset_ == 0u)) {
1708 PLOG(ERROR) << "Failed to write final relative call thunks";
1709 return false;
1710 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001711 return true;
1712 }
1713
Igor Murashkin545412b2017-08-17 15:26:54 -07001714 virtual bool VisitMethod(const OrderedMethodData& method_data) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001715 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001716 const MethodReference& method_ref = method_data.method_reference;
1717 UpdateDexFileAndDexCache(method_ref.dex_file);
1718
1719 OatClass* oat_class = method_data.oat_class;
1720 CompiledMethod* compiled_method = method_data.compiled_method;
1721 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001722
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001723 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001724 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001725 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001726
Igor Murashkin545412b2017-08-17 15:26:54 -07001727 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1728 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1729 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001730
Igor Murashkin545412b2017-08-17 15:26:54 -07001731 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1732 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1733
1734 // Deduplicate code arrays.
1735 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1736 if (method_offsets.code_offset_ > offset_) {
1737 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1738 if (offset_ == 0u) {
1739 ReportWriteFailure("relative call thunk", method_ref);
1740 return false;
1741 }
1742 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1743 if (alignment_size != 0) {
1744 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1745 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001746 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001747 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001748 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001749 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001750 }
1751 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1752 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1753 DCHECK_EQ(method_offsets.code_offset_,
1754 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1755 << dex_file_->PrettyMethod(method_ref.index);
1756 const OatQuickMethodHeader& method_header =
1757 oat_class->method_headers_[method_offsets_index];
1758 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1759 ReportWriteFailure("method header", method_ref);
1760 return false;
1761 }
1762 writer_->size_method_header_ += sizeof(method_header);
1763 offset_ += sizeof(method_header);
1764 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001765
Igor Murashkin545412b2017-08-17 15:26:54 -07001766 if (!compiled_method->GetPatches().empty()) {
1767 patched_code_.assign(quick_code.begin(), quick_code.end());
1768 quick_code = ArrayRef<const uint8_t>(patched_code_);
1769 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1770 uint32_t literal_offset = patch.LiteralOffset();
1771 switch (patch.GetType()) {
1772 case LinkerPatch::Type::kMethodBssEntry: {
1773 uint32_t target_offset =
1774 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1775 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1776 patch,
1777 offset_ + literal_offset,
1778 target_offset);
1779 break;
1780 }
1781 case LinkerPatch::Type::kCallRelative: {
1782 // NOTE: Relative calls across oat files are not supported.
1783 uint32_t target_offset = GetTargetOffset(patch);
1784 writer_->relative_patcher_->PatchCall(&patched_code_,
1785 literal_offset,
1786 offset_ + literal_offset,
1787 target_offset);
1788 break;
1789 }
1790 case LinkerPatch::Type::kStringRelative: {
1791 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1792 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1793 patch,
1794 offset_ + literal_offset,
1795 target_offset);
1796 break;
1797 }
1798 case LinkerPatch::Type::kStringInternTable: {
1799 uint32_t target_offset = GetInternTableEntryOffset(patch);
1800 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1801 patch,
1802 offset_ + literal_offset,
1803 target_offset);
1804 break;
1805 }
1806 case LinkerPatch::Type::kStringBssEntry: {
1807 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1808 uint32_t target_offset =
1809 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1810 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1811 patch,
1812 offset_ + literal_offset,
1813 target_offset);
1814 break;
1815 }
1816 case LinkerPatch::Type::kTypeRelative: {
1817 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1818 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1819 patch,
1820 offset_ + literal_offset,
1821 target_offset);
1822 break;
1823 }
1824 case LinkerPatch::Type::kTypeClassTable: {
1825 uint32_t target_offset = GetClassTableEntryOffset(patch);
1826 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1827 patch,
1828 offset_ + literal_offset,
1829 target_offset);
1830 break;
1831 }
1832 case LinkerPatch::Type::kTypeBssEntry: {
1833 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1834 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1835 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1836 patch,
1837 offset_ + literal_offset,
1838 target_offset);
1839 break;
1840 }
1841 case LinkerPatch::Type::kCall: {
1842 uint32_t target_offset = GetTargetOffset(patch);
1843 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1844 break;
1845 }
1846 case LinkerPatch::Type::kMethodRelative: {
1847 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1848 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1849 patch,
1850 offset_ + literal_offset,
1851 target_offset);
1852 break;
1853 }
1854 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1855 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1856 patch,
1857 offset_ + literal_offset);
1858 break;
1859 }
1860 default: {
1861 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1862 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001863 }
1864 }
1865 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001866 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001867
1868 if (!out->WriteFully(quick_code.data(), code_size)) {
1869 ReportWriteFailure("method code", method_ref);
1870 return false;
1871 }
1872 writer_->size_code_ += code_size;
1873 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001874 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001875 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001876
1877 return true;
1878 }
1879
Igor Murashkin545412b2017-08-17 15:26:54 -07001880 size_t GetOffset() const {
1881 return offset_;
1882 }
1883
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001884 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001885 OatWriter* const writer_;
1886
1887 // Updated in VisitMethod as methods are written out.
1888 size_t offset_;
1889
1890 // Potentially varies with every different VisitMethod.
1891 // Used to determine which DexCache to use when finding ArtMethods.
1892 const DexFile* dex_file_;
1893
1894 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001895 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001896 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001897 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001898 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001899 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001900 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001901 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001902 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001903 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001904 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001905
Igor Murashkin545412b2017-08-17 15:26:54 -07001906 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001907 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001908 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001909 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001910
Mathieu Chartiere401d142015-04-22 13:56:20 -07001911 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001912 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001913 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001914 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001915 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1916 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001917 ArtMethod* method =
1918 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001919 CHECK(method != nullptr);
1920 return method;
1921 }
1922
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001923 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001924 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1925 // If there's no new compiled code, either we're compiling an app and the target method
1926 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001927 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001928 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001929 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001930 const void* oat_code_offset =
1931 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001932 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001933 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001934 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1935 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1936 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1937 target_offset = PointerToLowMemUInt32(oat_code_offset);
1938 } else {
1939 target_offset = target->IsNative()
1940 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1941 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1942 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001943 }
1944 return target_offset;
1945 }
1946
Vladimir Markocd556b02017-02-03 11:47:34 +00001947 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001948 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001949 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001950 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001951 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1952 }
1953
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001954 mirror::Class* GetTargetType(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001955 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001956 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001957 ObjPtr<mirror::Class> type =
1958 ClassLinker::LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001959 CHECK(type != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001960 return type.Ptr();
Vladimir Markof4da6752014-08-01 19:04:18 +01001961 }
1962
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001963 mirror::String* GetTargetString(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001964 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001965 mirror::String* string = linker->LookupString(*patch.TargetStringDexFile(),
1966 patch.TargetStringIndex(),
Vladimir Markof25cc732017-03-16 16:18:15 +00001967 GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001968 DCHECK(string != nullptr);
1969 DCHECK(writer_->HasBootImage() ||
1970 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1971 return string;
1972 }
1973
Vladimir Marko65979462017-05-19 17:25:12 +01001974 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1975 DCHECK(writer_->HasBootImage());
1976 method = writer_->image_writer_->GetImageMethodAddress(method);
1977 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1978 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1979 // TODO: Clean up offset types. The target offset must be treated as signed.
1980 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1981 }
1982
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001983 uint32_t GetTargetObjectOffset(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001984 DCHECK(writer_->HasBootImage());
1985 object = writer_->image_writer_->GetImageAddress(object);
1986 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1987 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1988 // TODO: Clean up offset types. The target offset must be treated as signed.
1989 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1990 }
1991
Vladimir Markof4da6752014-08-01 19:04:18 +01001992 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001993 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001994 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001995 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001996 } else {
1997 // NOTE: We're using linker patches for app->boot references when the image can
1998 // be relocated and therefore we need to emit .oat_patches. We're not using this
1999 // for app->app references, so check that the object is in the image space.
2000 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01002001 }
Vladimir Marko09d09432015-09-08 13:47:48 +01002002 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01002003 uint32_t address = PointerToLowMemUInt32(object);
2004 DCHECK_LE(offset + 4, code->size());
2005 uint8_t* data = &(*code)[offset];
2006 data[0] = address & 0xffu;
2007 data[1] = (address >> 8) & 0xffu;
2008 data[2] = (address >> 16) & 0xffu;
2009 data[3] = (address >> 24) & 0xffu;
2010 }
2011
2012 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002013 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01002014 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002015 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002016 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
2017 // TODO: Clean up offset types.
2018 // The target_offset must be treated as signed for cross-oat patching.
2019 const void* target = reinterpret_cast<const void*>(
2020 writer_->image_writer_->GetOatDataBegin(oat_index) +
2021 static_cast<int32_t>(target_offset));
2022 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01002023 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002024 DCHECK_LE(offset + 4, code->size());
2025 uint8_t* data = &(*code)[offset];
2026 data[0] = address & 0xffu;
2027 data[1] = (address >> 8) & 0xffu;
2028 data[2] = (address >> 16) & 0xffu;
2029 data[3] = (address >> 24) & 0xffu;
2030 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002031
2032 // Calculate the offset of the InternTable slot (GcRoot<String>) when mmapped to the .bss.
2033 uint32_t GetInternTableEntryOffset(const LinkerPatch& patch)
2034 REQUIRES_SHARED(Locks::mutator_lock_) {
2035 DCHECK(!writer_->HasBootImage());
2036 const uint8_t* string_root = writer_->LookupBootImageInternTableSlot(
2037 *patch.TargetStringDexFile(), patch.TargetStringIndex());
2038 DCHECK(string_root != nullptr);
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002039 return GetBootImageTableEntryOffset(string_root);
2040 }
2041
2042 // Calculate the offset of the ClassTable::TableSlot when mmapped to the .bss.
2043 uint32_t GetClassTableEntryOffset(const LinkerPatch& patch)
2044 REQUIRES_SHARED(Locks::mutator_lock_) {
2045 DCHECK(!writer_->HasBootImage());
2046 const uint8_t* table_slot =
2047 writer_->LookupBootImageClassTableSlot(*patch.TargetTypeDexFile(), patch.TargetTypeIndex());
2048 DCHECK(table_slot != nullptr);
2049 return GetBootImageTableEntryOffset(table_slot);
2050 }
2051
2052 uint32_t GetBootImageTableEntryOffset(const uint8_t* raw_root) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002053 uint32_t base_offset = writer_->bss_start_;
2054 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2055 const uint8_t* const_tables_begin =
2056 space->Begin() + space->GetImageHeader().GetBootImageConstantTablesOffset();
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002057 size_t offset = static_cast<size_t>(raw_root - const_tables_begin);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002058 if (offset < space->GetImageHeader().GetBootImageConstantTablesSize()) {
2059 DCHECK_LE(base_offset + offset, writer_->bss_start_ + writer_->bss_methods_offset_);
2060 return base_offset + offset;
2061 }
2062 base_offset += space->GetImageHeader().GetBootImageConstantTablesSize();
2063 }
2064 LOG(FATAL) << "Didn't find boot image string in boot image intern tables!";
2065 UNREACHABLE();
2066 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002067};
2068
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002069class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
2070 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002071 WriteMapMethodVisitor(OatWriter* writer,
2072 OutputStream* out,
2073 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002074 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002075 : OatDexMethodVisitor(writer, relative_offset),
2076 out_(out),
2077 file_offset_(file_offset) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002078
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002079 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002080 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002081 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2082
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002083 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002084 size_t file_offset = file_offset_;
2085 OutputStream* out = out_;
2086
Mingyao Yang063fc772016-08-02 11:02:54 -07002087 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002088 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002089 ++method_offsets_index_;
2090
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002091 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
2092 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
2093 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
David Sehr709b0702016-10-13 09:12:37 -07002094 << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002095
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002096 // If vdex is enabled, only emit the map for compiled code. The quickening info
2097 // is emitted in the vdex already.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002098 if (map_offset != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002099 // Transform map_offset to actual oat data offset.
2100 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2101 DCHECK_NE(map_offset, 0u);
David Sehr709b0702016-10-13 09:12:37 -07002102 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002103
2104 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2105 size_t map_size = map.size() * sizeof(map[0]);
2106 if (map_offset == offset_) {
2107 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01002108 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002109 ReportWriteFailure(it);
2110 return false;
2111 }
2112 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002113 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002114 }
2115 DCHECK_OFFSET_();
2116 }
2117
2118 return true;
2119 }
2120
2121 private:
2122 OutputStream* const out_;
2123 size_t const file_offset_;
2124
2125 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01002126 PLOG(ERROR) << "Failed to write map for "
David Sehr709b0702016-10-13 09:12:37 -07002127 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002128 }
2129};
2130
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002131class OatWriter::WriteMethodInfoVisitor : public OatDexMethodVisitor {
2132 public:
2133 WriteMethodInfoVisitor(OatWriter* writer,
2134 OutputStream* out,
2135 const size_t file_offset,
2136 size_t relative_offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002137 : OatDexMethodVisitor(writer, relative_offset),
2138 out_(out),
2139 file_offset_(file_offset) {}
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002140
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002141 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) OVERRIDE {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002142 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
2143 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
2144
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002145 if (HasCompiledCode(compiled_method)) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002146 size_t file_offset = file_offset_;
2147 OutputStream* out = out_;
2148 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].GetMethodInfoOffset();
2149 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
2150 ++method_offsets_index_;
2151 DCHECK((compiled_method->GetMethodInfo().size() == 0u && map_offset == 0u) ||
2152 (compiled_method->GetMethodInfo().size() != 0u && map_offset != 0u))
2153 << compiled_method->GetMethodInfo().size() << " " << map_offset << " "
2154 << dex_file_->PrettyMethod(it.GetMemberIndex());
2155 if (map_offset != 0u) {
2156 // Transform map_offset to actual oat data offset.
2157 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
2158 DCHECK_NE(map_offset, 0u);
2159 DCHECK_LE(map_offset, offset_) << dex_file_->PrettyMethod(it.GetMemberIndex());
2160
2161 ArrayRef<const uint8_t> map = compiled_method->GetMethodInfo();
2162 size_t map_size = map.size() * sizeof(map[0]);
2163 if (map_offset == offset_) {
2164 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
2165 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
2166 ReportWriteFailure(it);
2167 return false;
2168 }
2169 offset_ += map_size;
2170 }
2171 }
2172 DCHECK_OFFSET_();
2173 }
2174
2175 return true;
2176 }
2177
2178 private:
2179 OutputStream* const out_;
2180 size_t const file_offset_;
2181
2182 void ReportWriteFailure(const ClassDataItemIterator& it) {
2183 PLOG(ERROR) << "Failed to write map for "
2184 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to " << out_->GetLocation();
2185 }
2186};
2187
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002188// Visit all methods from all classes in all dex files with the specified visitor.
2189bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2190 for (const DexFile* dex_file : *dex_files_) {
2191 const size_t class_def_count = dex_file->NumClassDefs();
2192 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2193 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
2194 return false;
2195 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002196 if (MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002197 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2198 const uint8_t* class_data = dex_file->GetClassData(class_def);
2199 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
2200 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002201 it.SkipAllFields();
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002202 size_t class_def_method_index = 0u;
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002203 while (it.HasNextMethod()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002204 if (!visitor->VisitMethod(class_def_method_index, it)) {
2205 return false;
2206 }
2207 ++class_def_method_index;
2208 it.Next();
2209 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002210 DCHECK(!it.HasNext());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002211 }
2212 }
2213 if (UNLIKELY(!visitor->EndClass())) {
2214 return false;
2215 }
2216 }
2217 }
2218 return true;
2219}
2220
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002221size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
2222 const InstructionSetFeatures* instruction_set_features,
2223 uint32_t num_dex_files,
2224 SafeMap<std::string, std::string>* key_value_store) {
2225 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2226 oat_header_.reset(OatHeader::Create(instruction_set,
2227 instruction_set_features,
2228 num_dex_files,
2229 key_value_store));
2230 size_oat_header_ += sizeof(OatHeader);
2231 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002232 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002233}
2234
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002235size_t OatWriter::InitClassOffsets(size_t offset) {
2236 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002237 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002238 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2239 if (!oat_dex_file.class_offsets_.empty()) {
2240 // Class offsets are required to be 4 byte aligned.
2241 offset = RoundUp(offset, 4u);
2242 oat_dex_file.class_offsets_offset_ = offset;
2243 offset += oat_dex_file.GetClassOffsetsRawSize();
2244 DCHECK_ALIGNED(offset, 4u);
2245 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002246 }
2247 return offset;
2248}
2249
Brian Carlstrom389efb02012-01-11 12:06:26 -08002250size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002251 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002252 InitOatClassesMethodVisitor visitor(this, offset);
2253 bool success = VisitDexMethods(&visitor);
2254 CHECK(success);
2255 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002256
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002257 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002258 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002259 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2260 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002261 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002262 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002263 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002264 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002265 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002266 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002267
2268 return offset;
2269}
2270
2271size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002272 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002273 return offset;
2274 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002275 {
2276 InitMapMethodVisitor visitor(this, offset);
2277 bool success = VisitDexMethods(&visitor);
2278 DCHECK(success);
2279 offset = visitor.GetOffset();
2280 }
2281 {
2282 InitMethodInfoVisitor visitor(this, offset);
2283 bool success = VisitDexMethods(&visitor);
2284 DCHECK(success);
2285 offset = visitor.GetOffset();
2286 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002287 return offset;
2288}
2289
Vladimir Markof3c52b42017-11-17 17:32:12 +00002290template <typename GetBssOffset>
2291static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2292 size_t slot_size,
2293 const BitVector& indexes,
2294 GetBssOffset get_bss_offset) {
2295 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2296 size_t number_of_entries = 0u;
2297 bool first_index = true;
2298 for (uint32_t index : indexes.Indexes()) {
2299 uint32_t bss_offset = get_bss_offset(index);
2300 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2301 encoder.Reset(index, bss_offset);
2302 ++number_of_entries;
2303 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002304 }
2305 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002306 DCHECK_NE(number_of_entries, 0u);
2307 return number_of_entries;
2308}
2309
2310template <typename GetBssOffset>
2311static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2312 size_t slot_size,
2313 const BitVector& indexes,
2314 GetBssOffset get_bss_offset) {
2315 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2316 slot_size,
2317 indexes,
2318 get_bss_offset);
2319 return IndexBssMapping::ComputeSize(number_of_entries);
2320}
2321
2322size_t OatWriter::InitIndexBssMappings(size_t offset) {
2323 if (bss_method_entry_references_.empty() &&
2324 bss_type_entry_references_.empty() &&
2325 bss_string_entry_references_.empty()) {
2326 return offset;
2327 }
2328 // If there are any classes, the class offsets allocation aligns the offset
2329 // and we cannot have any index bss mappings without class offsets.
2330 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2331 DCHECK_ALIGNED(offset, 4u);
2332
2333 size_t number_of_method_dex_files = 0u;
2334 size_t number_of_type_dex_files = 0u;
2335 size_t number_of_string_dex_files = 0u;
2336 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2337 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2338 const DexFile* dex_file = (*dex_files_)[i];
2339 auto method_it = bss_method_entry_references_.find(dex_file);
2340 if (method_it != bss_method_entry_references_.end()) {
2341 const BitVector& method_indexes = method_it->second;
2342 ++number_of_method_dex_files;
2343 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2344 offset += CalculateIndexBssMappingSize(
2345 dex_file->NumMethodIds(),
2346 static_cast<size_t>(pointer_size),
2347 method_indexes,
2348 [=](uint32_t index) {
2349 return bss_method_entries_.Get({dex_file, index});
2350 });
2351 }
2352
2353 auto type_it = bss_type_entry_references_.find(dex_file);
2354 if (type_it != bss_type_entry_references_.end()) {
2355 const BitVector& type_indexes = type_it->second;
2356 ++number_of_type_dex_files;
2357 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2358 offset += CalculateIndexBssMappingSize(
2359 dex_file->NumTypeIds(),
2360 sizeof(GcRoot<mirror::Class>),
2361 type_indexes,
2362 [=](uint32_t index) {
2363 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2364 });
2365 }
2366
2367 auto string_it = bss_string_entry_references_.find(dex_file);
2368 if (string_it != bss_string_entry_references_.end()) {
2369 const BitVector& string_indexes = string_it->second;
2370 ++number_of_string_dex_files;
2371 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2372 offset += CalculateIndexBssMappingSize(
2373 dex_file->NumStringIds(),
2374 sizeof(GcRoot<mirror::String>),
2375 string_indexes,
2376 [=](uint32_t index) {
2377 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2378 });
2379 }
2380 }
2381 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2382 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2383 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2384 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002385 return offset;
2386}
2387
2388size_t OatWriter::InitOatDexFiles(size_t offset) {
2389 // Initialize offsets of oat dex files.
2390 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2391 oat_dex_file.offset_ = offset;
2392 offset += oat_dex_file.SizeOf();
2393 }
2394 return offset;
2395}
2396
Brian Carlstrome24fa612011-09-29 00:53:55 -07002397size_t OatWriter::InitOatCode(size_t offset) {
2398 // calculate the offsets within OatHeader to executable code
2399 size_t old_offset = offset;
2400 // required to be on a new page boundary
2401 offset = RoundUp(offset, kPageSize);
2402 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002403 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002404 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2405 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2406 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002407 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002408 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002409 const bool generate_debug_info = compiler_driver_->GetCompilerOptions().GenerateAnyDebugInfo();
2410 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002411
Vladimir Marko1b404a82017-09-01 13:35:26 +01002412 #define DO_TRAMPOLINE(field, fn_name) \
2413 offset = CompiledCode::AlignCode(offset, instruction_set); \
2414 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2415 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2416 (field) = compiler_driver_->Create ## fn_name(); \
2417 if (generate_debug_info) { \
2418 debug::MethodDebugInfo info = {}; \
2419 info.trampoline_name = #fn_name; \
2420 info.isa = instruction_set; \
2421 info.is_code_address_text_relative = true; \
2422 /* Use the code offset rather than the `adjusted_offset`. */ \
2423 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2424 info.code_size = (field)->size(); \
2425 method_info_.push_back(std::move(info)); \
2426 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002427 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002428
Ian Rogers848871b2013-08-05 10:56:33 -07002429 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002430 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002431 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002432 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2433 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002434
Ian Rogers848871b2013-08-05 10:56:33 -07002435 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002436 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002437 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002438 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002439 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002440 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002441 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002442 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002443 return offset;
2444}
2445
2446size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002447 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002448 if (kOatWriterDebugOatCodeLayout) {
2449 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2450 << this << "), "
2451 << "compilation is disabled";
2452 }
2453
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002454 return offset;
2455 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002456 bool success = false;
2457
2458 {
2459 ScopedObjectAccess soa(Thread::Current());
2460
2461 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2462 success = VisitDexMethods(&layout_code_visitor);
2463 DCHECK(success);
2464
2465 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2466 this,
2467 offset,
2468 layout_code_visitor.ReleaseOrderedMethods());
2469 success = layout_reserve_code_visitor.Visit();
2470 DCHECK(success);
2471 offset = layout_reserve_code_visitor.GetOffset();
2472
2473 // Save the method order because the WriteCodeMethodVisitor will need this
2474 // order again.
2475 DCHECK(ordered_methods_ == nullptr);
2476 ordered_methods_.reset(
2477 new OrderedMethodList(
2478 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2479
2480 if (kOatWriterDebugOatCodeLayout) {
2481 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2482 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2483 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2484 LOG(INFO) << pretty_name
2485 << "@ offset "
2486 << relative_patcher_->GetOffset(ordered_method.method_reference)
2487 << " X hotness "
2488 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2489 }
2490 }
2491 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002492
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002493 if (HasImage()) {
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002494 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002495 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002496 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002497 DCHECK(success);
2498 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002499 }
Logan Chien8b977d32012-02-21 19:14:55 +08002500
Brian Carlstrome24fa612011-09-29 00:53:55 -07002501 return offset;
2502}
2503
Vladimir Markoaad75c62016-10-03 08:46:48 +00002504void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002505 {
2506 InitBssLayoutMethodVisitor visitor(this);
2507 bool success = VisitDexMethods(&visitor);
2508 DCHECK(success);
2509 }
2510
2511 DCHECK_EQ(bss_size_, 0u);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002512 if (HasBootImage()) {
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002513 DCHECK(!map_boot_image_tables_to_bss_);
Vladimir Marko1998cd02017-01-13 13:02:58 +00002514 DCHECK(bss_string_entries_.empty());
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002515 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002516 if (!map_boot_image_tables_to_bss_ &&
2517 bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002518 bss_type_entries_.empty() &&
2519 bss_string_entries_.empty()) {
2520 // Nothing to put to the .bss section.
2521 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002522 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002523
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002524 // Allocate space for boot image tables in the .bss section.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002525 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002526 if (map_boot_image_tables_to_bss_) {
2527 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
2528 bss_size_ += space->GetImageHeader().GetBootImageConstantTablesSize();
2529 }
2530 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002531
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002532 bss_methods_offset_ = bss_size_;
2533
2534 // Prepare offsets for .bss ArtMethod entries.
2535 for (auto& entry : bss_method_entries_) {
2536 DCHECK_EQ(entry.second, 0u);
2537 entry.second = bss_size_;
2538 bss_size_ += static_cast<size_t>(pointer_size);
2539 }
2540
Vladimir Markoaad75c62016-10-03 08:46:48 +00002541 bss_roots_offset_ = bss_size_;
2542
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002543 // Prepare offsets for .bss Class entries.
2544 for (auto& entry : bss_type_entries_) {
2545 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002546 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002547 bss_size_ += sizeof(GcRoot<mirror::Class>);
2548 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002549 // Prepare offsets for .bss String entries.
2550 for (auto& entry : bss_string_entries_) {
2551 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002552 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002553 bss_size_ += sizeof(GcRoot<mirror::String>);
2554 }
2555}
2556
David Srbeckybc90fd02015-04-22 19:40:27 +01002557bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002558 CHECK(write_state_ == WriteState::kWriteRoData);
2559
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002560 size_t file_offset = oat_data_offset_;
2561 off_t current_offset = out->Seek(0, kSeekCurrent);
2562 if (current_offset == static_cast<off_t>(-1)) {
2563 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2564 }
2565 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2566 size_t relative_offset = current_offset - file_offset;
2567
Vladimir Markoe079e212016-05-25 12:49:49 +01002568 // Wrap out to update checksum with each write.
2569 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2570 out = &checksum_updating_out;
2571
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002572 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2573 if (relative_offset == 0) {
2574 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002575 return false;
2576 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002577
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002578 relative_offset = WriteClasses(out, file_offset, relative_offset);
2579 if (relative_offset == 0) {
2580 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002581 return false;
2582 }
2583
Vladimir Markof3c52b42017-11-17 17:32:12 +00002584 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002585 if (relative_offset == 0) {
2586 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002587 return false;
2588 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002589
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002590 relative_offset = WriteMaps(out, file_offset, relative_offset);
2591 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002592 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2593 return false;
2594 }
2595
2596 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2597 if (relative_offset == 0) {
2598 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002599 return false;
2600 }
2601
David Srbeckybc90fd02015-04-22 19:40:27 +01002602 // Write padding.
2603 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2604 relative_offset += size_executable_offset_alignment_;
2605 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2606 size_t expected_file_offset = file_offset + relative_offset;
2607 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2608 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2609 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2610 return 0;
2611 }
2612 DCHECK_OFFSET();
2613
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002614 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002615 return true;
2616}
2617
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002618class OatWriter::WriteQuickeningInfoMethodVisitor : public DexMethodVisitor {
2619 public:
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002620 WriteQuickeningInfoMethodVisitor(OatWriter* writer,
2621 OutputStream* out,
2622 uint32_t offset,
2623 SafeMap<const uint8_t*, uint32_t>* offset_map)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002624 : DexMethodVisitor(writer, offset),
2625 out_(out),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002626 written_bytes_(0u),
2627 offset_map_(offset_map) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002628
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002629 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it)
2630 OVERRIDE {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002631 uint32_t method_idx = it.GetMemberIndex();
2632 CompiledMethod* compiled_method =
2633 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
2634
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002635 if (HasQuickeningInfo(compiled_method)) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002636 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002637 // Deduplication is already done on a pointer basis by the compiler driver,
2638 // so we can simply compare the pointers to find out if things are duplicated.
2639 if (offset_map_->find(map.data()) == offset_map_->end()) {
2640 uint32_t length = map.size() * sizeof(map.front());
2641 offset_map_->Put(map.data(), written_bytes_);
2642 if (!out_->WriteFully(&length, sizeof(length)) ||
2643 !out_->WriteFully(map.data(), length)) {
2644 PLOG(ERROR) << "Failed to write quickening info for "
2645 << dex_file_->PrettyMethod(it.GetMemberIndex()) << " to "
2646 << out_->GetLocation();
2647 return false;
2648 }
2649 written_bytes_ += sizeof(length) + length;
2650 offset_ += sizeof(length) + length;
2651 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002652 }
2653
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002654 return true;
2655 }
2656
2657 size_t GetNumberOfWrittenBytes() const {
2658 return written_bytes_;
2659 }
2660
2661 private:
2662 OutputStream* const out_;
2663 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002664 // Maps quickening map to its offset in the file.
2665 SafeMap<const uint8_t*, uint32_t>* offset_map_;
2666};
2667
2668class OatWriter::WriteQuickeningIndicesMethodVisitor {
2669 public:
2670 WriteQuickeningIndicesMethodVisitor(OutputStream* out,
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002671 uint32_t quickening_info_bytes,
2672 const SafeMap<const uint8_t*, uint32_t>& offset_map)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002673 : out_(out),
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002674 quickening_info_bytes_(quickening_info_bytes),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002675 written_bytes_(0u),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002676 offset_map_(offset_map) {}
2677
2678 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files, const CompilerDriver& driver) {
2679 for (const DexFile* dex_file : dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002680 const size_t class_def_count = dex_file->NumClassDefs();
2681 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
2682 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2683 const uint8_t* class_data = dex_file->GetClassData(class_def);
2684 if (class_data == nullptr) {
2685 continue;
2686 }
2687 for (ClassDataItemIterator class_it(*dex_file, class_data);
2688 class_it.HasNext();
2689 class_it.Next()) {
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002690 if (!class_it.IsAtMethod() || class_it.GetMethodCodeItem() == nullptr) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002691 continue;
2692 }
2693 uint32_t method_idx = class_it.GetMemberIndex();
2694 CompiledMethod* compiled_method =
2695 driver.GetCompiledMethod(MethodReference(dex_file, method_idx));
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002696 const DexFile::CodeItem* code_item = class_it.GetMethodCodeItem();
Mathieu Chartier31f4c9f2017-12-08 15:46:11 -08002697 CodeItemDebugInfoAccessor accessor(dex_file, code_item);
2698 const uint32_t existing_debug_info_offset = accessor.DebugInfoOffset();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002699 // If the existing offset is already out of bounds (and not magic marker 0xFFFFFFFF)
2700 // we will pretend the method has been quickened.
2701 bool existing_offset_out_of_bounds =
2702 (existing_debug_info_offset >= dex_file->Size() &&
2703 existing_debug_info_offset != 0xFFFFFFFF);
2704 bool has_quickening_info = HasQuickeningInfo(compiled_method);
2705 if (has_quickening_info || existing_offset_out_of_bounds) {
2706 uint32_t new_debug_info_offset =
2707 dex_file->Size() + quickening_info_bytes_ + written_bytes_;
2708 // Abort if overflow.
2709 CHECK_GE(new_debug_info_offset, dex_file->Size());
2710 const_cast<DexFile::CodeItem*>(code_item)->SetDebugInfoOffset(new_debug_info_offset);
2711 uint32_t quickening_offset = has_quickening_info
2712 ? offset_map_.Get(compiled_method->GetVmapTable().data())
2713 : VdexFile::kNoQuickeningInfoOffset;
2714 if (!out_->WriteFully(&existing_debug_info_offset,
2715 sizeof(existing_debug_info_offset)) ||
2716 !out_->WriteFully(&quickening_offset, sizeof(quickening_offset))) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002717 PLOG(ERROR) << "Failed to write quickening info for "
2718 << dex_file->PrettyMethod(method_idx) << " to "
2719 << out_->GetLocation();
2720 return false;
2721 }
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002722 written_bytes_ += sizeof(existing_debug_info_offset) + sizeof(quickening_offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002723 }
2724 }
2725 }
2726 }
2727 return true;
2728 }
2729
2730 size_t GetNumberOfWrittenBytes() const {
2731 return written_bytes_;
2732 }
2733
2734 private:
2735 OutputStream* const out_;
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002736 const uint32_t quickening_info_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002737 size_t written_bytes_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002738 // Maps quickening map to its offset in the file.
2739 const SafeMap<const uint8_t*, uint32_t>& offset_map_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002740};
2741
2742bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002743 size_t initial_offset = vdex_size_;
2744 size_t start_offset = RoundUp(initial_offset, 4u);
2745
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002746 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2747 if (actual_offset != static_cast<off_t>(start_offset)) {
2748 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2749 << " Expected: " << start_offset
2750 << " Output: " << vdex_out->GetLocation();
2751 return false;
2752 }
2753
Nicolas Geoffray49cda062017-04-21 13:08:25 +01002754 if (compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002755 std::vector<uint32_t> dex_files_indices;
2756 SafeMap<const uint8_t*, uint32_t> offset_map;
2757 WriteQuickeningInfoMethodVisitor visitor1(this, vdex_out, start_offset, &offset_map);
2758 if (!VisitDexMethods(&visitor1)) {
2759 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2760 return false;
2761 }
2762
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002763 if (visitor1.GetNumberOfWrittenBytes() > 0) {
2764 WriteQuickeningIndicesMethodVisitor visitor2(vdex_out,
2765 visitor1.GetNumberOfWrittenBytes(),
2766 offset_map);
2767 if (!visitor2.VisitDexMethods(*dex_files_, *compiler_driver_)) {
2768 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2769 << vdex_out->GetLocation();
2770 return false;
2771 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002772
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002773 if (!vdex_out->Flush()) {
2774 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2775 << " File: " << vdex_out->GetLocation();
2776 return false;
2777 }
2778 size_quickening_info_ = visitor1.GetNumberOfWrittenBytes() +
2779 visitor2.GetNumberOfWrittenBytes();
2780 } else {
2781 // We know we did not quicken.
2782 size_quickening_info_ = 0;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002783 }
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002784 } else {
2785 // We know we did not quicken.
2786 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002787 }
2788
David Brazdil93592f52017-12-08 10:53:27 +00002789 if (size_quickening_info_ == 0) {
2790 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2791 vdex_quickening_info_offset_ = initial_offset;
2792 size_quickening_info_alignment_ = 0;
2793 } else {
2794 vdex_size_ = start_offset + size_quickening_info_;
2795 vdex_quickening_info_offset_ = start_offset;
2796 size_quickening_info_alignment_ = start_offset - initial_offset;
2797 }
2798
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002799 return true;
2800}
2801
David Brazdil5d5a36b2016-09-14 15:34:10 +01002802bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002803 if (verifier_deps == nullptr) {
2804 // Nothing to write. Record the offset, but no need
2805 // for alignment.
2806 vdex_verifier_deps_offset_ = vdex_size_;
2807 return true;
2808 }
2809
2810 size_t initial_offset = vdex_size_;
2811 size_t start_offset = RoundUp(initial_offset, 4u);
2812
2813 vdex_size_ = start_offset;
2814 vdex_verifier_deps_offset_ = vdex_size_;
2815 size_verifier_deps_alignment_ = start_offset - initial_offset;
2816
2817 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2818 if (actual_offset != static_cast<off_t>(start_offset)) {
2819 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2820 << " Expected: " << start_offset
2821 << " Output: " << vdex_out->GetLocation();
2822 return false;
2823 }
2824
2825 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002826 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002827
2828 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2829 PLOG(ERROR) << "Failed to write verifier deps."
2830 << " File: " << vdex_out->GetLocation();
2831 return false;
2832 }
2833 if (!vdex_out->Flush()) {
2834 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2835 << " File: " << vdex_out->GetLocation();
2836 return false;
2837 }
2838
2839 size_verifier_deps_ = buffer.size();
2840 vdex_size_ += size_verifier_deps_;
2841 return true;
2842}
2843
David Srbeckybc90fd02015-04-22 19:40:27 +01002844bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002845 CHECK(write_state_ == WriteState::kWriteText);
2846
Vladimir Markoe079e212016-05-25 12:49:49 +01002847 // Wrap out to update checksum with each write.
2848 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
2849 out = &checksum_updating_out;
2850
Vladimir Marko944da602016-02-19 12:27:55 +00002851 SetMultiOatRelativePatcherAdjustment();
2852
David Srbeckybc90fd02015-04-22 19:40:27 +01002853 const size_t file_offset = oat_data_offset_;
2854 size_t relative_offset = oat_header_->GetExecutableOffset();
2855 DCHECK_OFFSET();
2856
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002857 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002858 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002859 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002860 return false;
2861 }
2862
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002863 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2864 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002865 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002866 return false;
2867 }
2868
Vladimir Markof4da6752014-08-01 19:04:18 +01002869 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002870 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002871 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2872 return false;
2873 }
2874
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002875 if (kIsDebugBuild) {
2876 uint32_t size_total = 0;
2877 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002878 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2879 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002880
David Brazdil7b49e6c2016-09-01 11:06:18 +01002881 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002882 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002883 DO_STAT(size_dex_file_alignment_);
2884 DO_STAT(size_executable_offset_alignment_);
2885 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002886 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002887 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002888 DO_STAT(size_verifier_deps_);
2889 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002890 DO_STAT(size_quickening_info_);
2891 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002892 DO_STAT(size_interpreter_to_interpreter_bridge_);
2893 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2894 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002895 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002896 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002897 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002898 DO_STAT(size_quick_to_interpreter_bridge_);
2899 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002900 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002901 DO_STAT(size_code_);
2902 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002903 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002904 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002905 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002906 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002907 DO_STAT(size_oat_dex_file_location_size_);
2908 DO_STAT(size_oat_dex_file_location_data_);
2909 DO_STAT(size_oat_dex_file_location_checksum_);
2910 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002911 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002912 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002913 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2914 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2915 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002916 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002917 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2918 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002919 DO_STAT(size_oat_lookup_table_alignment_);
2920 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002921 DO_STAT(size_oat_class_offsets_alignment_);
2922 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002923 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002924 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002925 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002926 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002927 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002928 DO_STAT(size_type_bss_mappings_);
2929 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002930 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002931
David Brazdil7b49e6c2016-09-01 11:06:18 +01002932 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2933
2934 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2935 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002936 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002937
David Brazdil7b49e6c2016-09-01 11:06:18 +01002938 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2939 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002940
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002941 write_state_ = WriteState::kWriteHeader;
2942 return true;
2943}
2944
2945bool OatWriter::WriteHeader(OutputStream* out,
2946 uint32_t image_file_location_oat_checksum,
2947 uintptr_t image_file_location_oat_begin,
2948 int32_t image_patch_delta) {
2949 CHECK(write_state_ == WriteState::kWriteHeader);
2950
2951 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
2952 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
Vladimir Markoaad75c62016-10-03 08:46:48 +00002953 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002954 CHECK_EQ(image_patch_delta, 0);
2955 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
2956 } else {
2957 CHECK_ALIGNED(image_patch_delta, kPageSize);
2958 oat_header_->SetImagePatchDelta(image_patch_delta);
2959 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002960 oat_header_->UpdateChecksumWithHeaderData();
2961
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002962 const size_t file_offset = oat_data_offset_;
2963
2964 off_t current_offset = out->Seek(0, kSeekCurrent);
2965 if (current_offset == static_cast<off_t>(-1)) {
2966 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2967 return false;
2968 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002969 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002970 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2971 return false;
2972 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002973 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002974
2975 // Flush all other data before writing the header.
2976 if (!out->Flush()) {
2977 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2978 return false;
2979 }
2980 // Write the header.
2981 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002982 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002983 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2984 return false;
2985 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002986 // Flush the header data.
2987 if (!out->Flush()) {
2988 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002989 return false;
2990 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002991
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002992 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2993 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2994 return false;
2995 }
2996 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2997
2998 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002999 return true;
3000}
3001
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003002size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003003 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3004 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003005 // Class offsets are required to be 4 byte aligned.
3006 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
3007 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
3008 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
3009 return 0u;
3010 }
3011 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00003012 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003013 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003014 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003015 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003016 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003017 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003018 }
3019 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003020 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003021}
3022
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003023size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003024 const bool may_have_compiled = MayHaveCompiledMethods();
3025 if (may_have_compiled) {
3026 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
3027 }
3028 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003029 // If there are any classes, the class offsets allocation aligns the offset.
3030 DCHECK_ALIGNED(relative_offset, 4u);
3031 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003032 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003033 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00003034 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07003035 relative_offset += oat_class_headers_[i].SizeOf();
3036 if (may_have_compiled) {
3037 if (!oat_classes_[i].Write(this, out)) {
3038 return 0u;
3039 }
3040 relative_offset += oat_classes_[i].SizeOf();
3041 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003042 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003043 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003044}
3045
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003046size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003047 {
3048 size_t vmap_tables_offset = relative_offset;
3049 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
3050 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3051 return 0;
3052 }
3053 relative_offset = visitor.GetOffset();
3054 size_vmap_table_ = relative_offset - vmap_tables_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003055 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07003056 {
3057 size_t method_infos_offset = relative_offset;
3058 WriteMethodInfoVisitor visitor(this, out, file_offset, relative_offset);
3059 if (UNLIKELY(!VisitDexMethods(&visitor))) {
3060 return 0;
3061 }
3062 relative_offset = visitor.GetOffset();
3063 size_method_info_ = relative_offset - method_infos_offset;
3064 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003065
Vladimir Marko96c6ab92014-04-08 14:00:50 +01003066 return relative_offset;
3067}
3068
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003069
Vladimir Markof3c52b42017-11-17 17:32:12 +00003070template <typename GetBssOffset>
3071size_t WriteIndexBssMapping(OutputStream* out,
3072 size_t number_of_indexes,
3073 size_t slot_size,
3074 const BitVector& indexes,
3075 GetBssOffset get_bss_offset) {
3076 // Allocate the IndexBssMapping.
3077 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
3078 number_of_indexes, slot_size, indexes, get_bss_offset);
3079 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
3080 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
3081 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
3082 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
3083 mappings->ClearPadding();
3084 // Encode the IndexBssMapping.
3085 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
3086 auto init_it = mappings->begin();
3087 bool first_index = true;
3088 for (uint32_t index : indexes.Indexes()) {
3089 size_t bss_offset = get_bss_offset(index);
3090 if (first_index) {
3091 first_index = false;
3092 encoder.Reset(index, bss_offset);
3093 } else if (!encoder.TryMerge(index, bss_offset)) {
3094 *init_it = encoder.GetEntry();
3095 ++init_it;
3096 encoder.Reset(index, bss_offset);
3097 }
3098 }
3099 // Store the last entry.
3100 *init_it = encoder.GetEntry();
3101 ++init_it;
3102 DCHECK(init_it == mappings->end());
3103
3104 if (!out->WriteFully(storage.get(), mappings_size)) {
3105 return 0u;
3106 }
3107 return mappings_size;
3108}
3109
3110size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
3111 size_t file_offset,
3112 size_t relative_offset) {
3113 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
3114 if (bss_method_entry_references_.empty() &&
3115 bss_type_entry_references_.empty() &&
3116 bss_string_entry_references_.empty()) {
3117 return relative_offset;
3118 }
3119 // If there are any classes, the class offsets allocation aligns the offset
3120 // and we cannot have method bss mappings without class offsets.
3121 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
3122 "IndexBssMapping alignment check.");
3123 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
3124
3125 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003126 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
3127 const DexFile* dex_file = (*dex_files_)[i];
3128 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00003129 auto method_it = bss_method_entry_references_.find(dex_file);
3130 if (method_it != bss_method_entry_references_.end()) {
3131 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003132 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
3133 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00003134 size_t method_mappings_size = WriteIndexBssMapping(
3135 out,
3136 dex_file->NumMethodIds(),
3137 static_cast<size_t>(pointer_size),
3138 method_indexes,
3139 [=](uint32_t index) {
3140 return bss_method_entries_.Get({dex_file, index});
3141 });
3142 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003143 return 0u;
3144 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003145 size_method_bss_mappings_ += method_mappings_size;
3146 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003147 } else {
3148 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
3149 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00003150
3151 auto type_it = bss_type_entry_references_.find(dex_file);
3152 if (type_it != bss_type_entry_references_.end()) {
3153 const BitVector& type_indexes = type_it->second;
3154 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3155 DCHECK_OFFSET();
3156 size_t type_mappings_size = WriteIndexBssMapping(
3157 out,
3158 dex_file->NumTypeIds(),
3159 sizeof(GcRoot<mirror::Class>),
3160 type_indexes,
3161 [=](uint32_t index) {
3162 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3163 });
3164 if (type_mappings_size == 0u) {
3165 return 0u;
3166 }
3167 size_type_bss_mappings_ += type_mappings_size;
3168 relative_offset += type_mappings_size;
3169 } else {
3170 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3171 }
3172
3173 auto string_it = bss_string_entry_references_.find(dex_file);
3174 if (string_it != bss_string_entry_references_.end()) {
3175 const BitVector& string_indexes = string_it->second;
3176 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3177 DCHECK_OFFSET();
3178 size_t string_mappings_size = WriteIndexBssMapping(
3179 out,
3180 dex_file->NumStringIds(),
3181 sizeof(GcRoot<mirror::String>),
3182 string_indexes,
3183 [=](uint32_t index) {
3184 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3185 });
3186 if (string_mappings_size == 0u) {
3187 return 0u;
3188 }
3189 size_string_bss_mappings_ += string_mappings_size;
3190 relative_offset += string_mappings_size;
3191 } else {
3192 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3193 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003194 }
3195 return relative_offset;
3196}
3197
3198size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3199 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3200
3201 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3202 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3203 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3204 DCHECK_OFFSET();
3205
3206 // Write OatDexFile.
3207 if (!oat_dex_file->Write(this, out)) {
3208 return 0u;
3209 }
3210 relative_offset += oat_dex_file->SizeOf();
3211 }
3212
3213 return relative_offset;
3214}
3215
3216size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00003217 if (compiler_driver_->GetCompilerOptions().IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003218 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003219
Ian Rogers848871b2013-08-05 10:56:33 -07003220 #define DO_TRAMPOLINE(field) \
3221 do { \
3222 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3223 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003224 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003225 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003226 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003227 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003228 return false; \
3229 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003230 size_ ## field += (field)->size(); \
3231 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003232 DCHECK_OFFSET(); \
3233 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003234
Ian Rogers848871b2013-08-05 10:56:33 -07003235 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003236 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003237 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003238 DO_TRAMPOLINE(quick_resolution_trampoline_);
3239 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3240 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003241 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003242 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003243}
3244
Ian Rogers3d504072014-03-01 09:16:49 -08003245size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003246 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003247 size_t relative_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003248 if (!compiler_driver_->GetCompilerOptions().IsAnyCompilationEnabled()) {
3249 // As with InitOatCodeDexFiles, also skip the writer if
3250 // compilation was disabled.
3251 if (kOatWriterDebugOatCodeLayout) {
3252 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3253 << this << "), "
3254 << "compilation is disabled";
3255 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003256
Igor Murashkin545412b2017-08-17 15:26:54 -07003257 return relative_offset;
3258 }
3259 ScopedObjectAccess soa(Thread::Current());
3260 DCHECK(ordered_methods_ != nullptr);
3261 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3262 std::move(ordered_methods_);
3263 WriteCodeMethodVisitor visitor(this,
3264 out,
3265 file_offset,
3266 relative_offset,
3267 std::move(*ordered_methods_ptr));
3268 if (UNLIKELY(!visitor.Visit())) {
3269 return 0;
3270 }
3271 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003272
Vladimir Markob163bb72015-03-31 21:49:49 +01003273 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3274 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3275 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3276
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003277 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003278}
3279
Vladimir Marko944da602016-02-19 12:27:55 +00003280bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003281 // Get the elf file offset of the oat file.
3282 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3283 if (raw_file_offset == static_cast<off_t>(-1)) {
3284 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3285 return false;
3286 }
3287 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3288 return true;
3289}
3290
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003291bool OatWriter::WriteDexFiles(OutputStream* out, File* file, bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003292 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003293
David Brazdil7b49e6c2016-09-01 11:06:18 +01003294 vdex_dex_files_offset_ = vdex_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003295
3296 // Write dex files.
3297 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003298 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003299 return false;
3300 }
3301 }
3302
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003303 CloseSources();
3304 return true;
3305}
3306
3307void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003308 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3309 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3310 }
3311 zipped_dex_files_.clear();
3312 zip_archives_.clear();
3313 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003314}
3315
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003316bool OatWriter::WriteDexFile(OutputStream* out,
3317 File* file,
3318 OatDexFile* oat_dex_file,
3319 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003320 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003321 return false;
3322 }
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003323 if (profile_compilation_info_ != nullptr ||
3324 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
Nicolas Geoffray1cfea7a2017-05-24 14:44:38 +01003325 CHECK(!update_input_vdex) << "We should never update the input vdex when doing dexlayout";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003326 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3327 return false;
3328 }
3329 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003330 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003331 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003332 return false;
3333 }
3334 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003335 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003336 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003337 return false;
3338 }
3339 } else {
3340 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003341 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003342 return false;
3343 }
3344 }
3345
3346 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003347 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3348 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003349 size_dex_file_ += oat_dex_file->dex_file_size_;
3350 return true;
3351}
3352
3353bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3354 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003355 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003356 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003357 size_t file_offset = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003358 size_dex_file_alignment_ += start_offset - initial_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003359
3360 // Seek to the start of the dex file and flush any pending operations in the stream.
3361 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003362 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3363 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003364 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003365 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003366 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3367 return false;
3368 }
3369 if (!out->Flush()) {
3370 PLOG(ERROR) << "Failed to flush before writing dex file."
3371 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3372 return false;
3373 }
3374 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003375 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003376 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003377 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003378 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3379 return false;
3380 }
3381
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003382 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003383 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003384 return true;
3385}
3386
Jeff Hao608f2ce2016-10-19 11:17:11 -07003387bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3388 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3389 std::string error_msg;
3390 std::string location(oat_dex_file->GetLocation());
3391 std::unique_ptr<const DexFile> dex_file;
3392 if (oat_dex_file->source_.IsZipEntry()) {
3393 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3394 std::unique_ptr<MemMap> mem_map(
3395 zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg));
Jeff Hao41b2f532017-03-02 16:36:31 -08003396 if (mem_map == nullptr) {
3397 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3398 return false;
3399 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003400 dex_file = DexFileLoader::Open(location,
3401 zip_entry->GetCrc32(),
3402 std::move(mem_map),
3403 /* verify */ true,
3404 /* verify_checksum */ true,
3405 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003406 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003407 File* raw_file = oat_dex_file->source_.GetRawFile();
Jeff Hao68c48f02017-08-24 11:36:24 -07003408 int dup_fd = dup(raw_file->Fd());
3409 if (dup_fd < 0) {
3410 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3411 return false;
3412 }
Nicolas Geoffray095c6c92017-10-19 13:59:55 +01003413 dex_file = DexFileLoader::OpenDex(
3414 dup_fd, location, /* verify */ true, /* verify_checksum */ true, &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003415 } else {
3416 // The source data is a vdex file.
3417 CHECK(oat_dex_file->source_.IsRawData())
3418 << static_cast<size_t>(oat_dex_file->source_.GetType());
3419 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3420 // Note: The raw data has already been checked to contain the header
3421 // and all the data that the header specifies as the file size.
3422 DCHECK(raw_dex_file != nullptr);
3423 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3424 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3425 // Since the source may have had its layout changed, or may be quickened, don't verify it.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003426 dex_file = DexFileLoader::Open(raw_dex_file,
3427 header->file_size_,
3428 location,
3429 oat_dex_file->dex_file_location_checksum_,
3430 nullptr,
3431 /* verify */ false,
3432 /* verify_checksum */ false,
3433 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003434 }
Jeff Haode197542017-02-03 10:48:13 -08003435 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003436 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003437 return false;
3438 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003439 Options options;
3440 options.output_to_memmap_ = true;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003441 options.compact_dex_level_ = compact_dex_level_;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003442 DexLayout dex_layout(options, profile_compilation_info_, nullptr);
3443 dex_layout.ProcessDexFile(location.c_str(), dex_file.get(), 0);
3444 std::unique_ptr<MemMap> mem_map(dex_layout.GetAndReleaseMemMap());
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003445 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3446 // Dex layout can affect the size of the dex file, so we update here what we have set
3447 // when adding the dex file as a source.
3448 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(mem_map->Begin());
3449 oat_dex_file->dex_file_size_ = header->file_size_;
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003450 if (!WriteDexFile(out, oat_dex_file, mem_map->Begin(), /* update_input_vdex */ false)) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003451 return false;
3452 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003453 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003454 return true;
3455}
3456
David Brazdil7b49e6c2016-09-01 11:06:18 +01003457bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003458 File* file,
3459 OatDexFile* oat_dex_file,
3460 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003461 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003462 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003463
3464 // Extract the dex file and get the extracted size.
3465 std::string error_msg;
3466 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3467 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3468 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3469 return false;
3470 }
3471 if (file->Flush() != 0) {
3472 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3473 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3474 return false;
3475 }
3476 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3477 if (extracted_end == static_cast<off_t>(-1)) {
3478 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3479 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3480 return false;
3481 }
3482 if (extracted_end < static_cast<off_t>(start_offset)) {
3483 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3484 << " Start: " << start_offset
3485 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3486 return false;
3487 }
3488 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3489 if (extracted_size < sizeof(DexFile::Header)) {
3490 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3491 << extracted_size << " File: " << oat_dex_file->GetLocation();
3492 return false;
3493 }
3494
3495 // Read the dex file header and extract required data to OatDexFile.
3496 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3497 if (actual_offset != static_cast<off_t>(start_offset)) {
3498 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3499 << " Expected: " << start_offset
3500 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3501 return false;
3502 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003503 if (extracted_size < oat_dex_file->dex_file_size_) {
3504 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3505 << " file size from header: " << oat_dex_file->dex_file_size_
3506 << " File: " << oat_dex_file->GetLocation();
3507 return false;
3508 }
3509
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003510 // Seek both file and stream to the end offset.
3511 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3512 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3513 if (actual_offset != static_cast<off_t>(end_offset)) {
3514 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3515 << " Expected: " << end_offset
3516 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3517 return false;
3518 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003519 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003520 if (actual_offset != static_cast<off_t>(end_offset)) {
3521 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3522 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3523 return false;
3524 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003525 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003526 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3527 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3528 return false;
3529 }
3530
3531 // If we extracted more than the size specified in the header, truncate the file.
3532 if (extracted_size > oat_dex_file->dex_file_size_) {
3533 if (file->SetLength(end_offset) != 0) {
3534 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003535 << " File: " << oat_dex_file->GetLocation()
3536 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003537 return false;
3538 }
3539 }
3540
3541 return true;
3542}
3543
David Brazdil7b49e6c2016-09-01 11:06:18 +01003544bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003545 File* file,
3546 OatDexFile* oat_dex_file,
3547 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003548 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003549 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003550
3551 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3552 if (input_offset != static_cast<off_t>(0)) {
3553 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3554 << " Expected: 0"
3555 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3556 return false;
3557 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003558
3559 // Copy the input dex file using sendfile().
3560 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3561 PLOG(ERROR) << "Failed to copy dex file to oat file."
3562 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3563 return false;
3564 }
3565 if (file->Flush() != 0) {
3566 PLOG(ERROR) << "Failed to flush dex file."
3567 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3568 return false;
3569 }
3570
3571 // Check file position and seek the stream to the end offset.
3572 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3573 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3574 if (actual_offset != static_cast<off_t>(end_offset)) {
3575 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3576 << " Expected: " << end_offset
3577 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3578 return false;
3579 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003580 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003581 if (actual_offset != static_cast<off_t>(end_offset)) {
3582 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3583 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3584 return false;
3585 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003586 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003587 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3588 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3589 return false;
3590 }
3591
3592 return true;
3593}
3594
David Brazdil7b49e6c2016-09-01 11:06:18 +01003595bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003596 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003597 const uint8_t* dex_file,
3598 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003599 // Note: The raw data has already been checked to contain the header
3600 // and all the data that the header specifies as the file size.
3601 DCHECK(dex_file != nullptr);
3602 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3603 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3604
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003605 if (update_input_vdex) {
3606 // The vdex already contains the dex code, no need to write it again.
3607 } else {
3608 if (!out->WriteFully(dex_file, header->file_size_)) {
3609 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3610 << " to " << out->GetLocation();
3611 return false;
3612 }
3613 if (!out->Flush()) {
3614 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3615 << " File: " << oat_dex_file->GetLocation();
3616 return false;
3617 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003618 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003619 return true;
3620}
3621
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003622bool OatWriter::OpenDexFiles(
3623 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003624 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003625 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
3626 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3627 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3628
3629 if (oat_dex_files_.empty()) {
3630 // Nothing to do.
3631 return true;
3632 }
3633
3634 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003635 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003636
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003637 std::string error_msg;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003638 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(
3639 length,
3640 PROT_READ | PROT_WRITE,
3641 MAP_SHARED,
3642 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003643 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003644 /* low_4gb */ false,
3645 file->GetPath().c_str(),
3646 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003647 if (dex_files_map == nullptr) {
3648 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3649 << " error: " << error_msg;
3650 return false;
3651 }
3652 std::vector<std::unique_ptr<const DexFile>> dex_files;
3653 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003654 const uint8_t* raw_dex_file =
3655 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003656
3657 if (kIsDebugBuild) {
3658 // Sanity check our input files.
3659 // Note that ValidateDexFileHeader() logs error messages.
3660 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3661 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003662 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3663 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003664
3665 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3666 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3667 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003668 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3669 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003670 }
3671
3672 // Now, open the dex file.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07003673 dex_files.emplace_back(DexFileLoader::Open(raw_dex_file,
3674 oat_dex_file.dex_file_size_,
3675 oat_dex_file.GetLocation(),
3676 oat_dex_file.dex_file_location_checksum_,
3677 /* oat_dex_file */ nullptr,
3678 verify,
3679 verify,
3680 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003681 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003682 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3683 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003684 return false;
3685 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003686
3687 // Set the class_offsets size now that we have easy access to the DexFile and
3688 // it has been verified in DexFileLoader::Open.
3689 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003690 }
3691
3692 *opened_dex_files_map = std::move(dex_files_map);
3693 *opened_dex_files = std::move(dex_files);
3694 return true;
3695}
3696
3697bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003698 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003699 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3700 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3701
David Brazdil7b49e6c2016-09-01 11:06:18 +01003702 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3703 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3704 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3705 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3706 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3707 return false;
3708 }
3709
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003710 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3711 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3712 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003713 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3714
3715 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3716 oat_dex_file->class_offsets_.empty()) {
3717 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003718 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003719
3720 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3721 if (table_size == 0u) {
3722 continue;
3723 }
3724
3725 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003726 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003727 const DexFile& dex_file = *opened_dex_files[i];
3728 {
3729 std::unique_ptr<TypeLookupTable> type_lookup_table =
3730 TypeLookupTable::Create(dex_file, /* storage */ nullptr);
3731 type_lookup_table_oat_dex_files_.push_back(
3732 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3733 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3734 }
3735 TypeLookupTable* const table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
David Brazdil181e1cc2016-09-01 16:38:47 +00003736
3737 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003738 size_t initial_offset = oat_size_;
3739 size_t rodata_offset = RoundUp(initial_offset, 4);
3740 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003741
3742 if (padding_size != 0u) {
3743 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003744 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003745 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3746 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003747 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003748 return false;
3749 }
3750 }
3751
3752 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003753 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
David Brazdil181e1cc2016-09-01 16:38:47 +00003754 DCHECK_EQ(table_size, table->RawDataLength());
3755
David Brazdil7b49e6c2016-09-01 11:06:18 +01003756 if (!oat_rodata->WriteFully(table->RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003757 PLOG(ERROR) << "Failed to write lookup table."
3758 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003759 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003760 return false;
3761 }
3762
3763 oat_dex_file->lookup_table_offset_ = rodata_offset;
3764
David Brazdil7b49e6c2016-09-01 11:06:18 +01003765 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003766 size_oat_lookup_table_ += table_size;
3767 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003768 }
3769
David Brazdil7b49e6c2016-09-01 11:06:18 +01003770 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003771 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003772 << " File: " << oat_rodata->GetLocation();
3773 return false;
3774 }
3775
3776 return true;
3777}
3778
Mathieu Chartier120aa282017-08-05 16:03:03 -07003779bool OatWriter::WriteDexLayoutSections(
3780 OutputStream* oat_rodata,
3781 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3782 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3783
3784 if (!kWriteDexLayoutInfo) {
3785 return true;;
3786 }
3787
3788 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3789 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3790 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3791 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3792 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3793 return false;
3794 }
3795
3796 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3797 size_t rodata_offset = oat_size_;
3798 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3799 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3800 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3801
3802 // Write dex layout section alignment bytes.
3803 const size_t padding_size =
3804 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3805 if (padding_size != 0u) {
3806 std::vector<uint8_t> buffer(padding_size, 0u);
3807 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3808 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3809 << " File: " << oat_dex_file->GetLocation()
3810 << " Output: " << oat_rodata->GetLocation();
3811 return false;
3812 }
3813 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3814 rodata_offset += padding_size;
3815 }
3816
3817 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3818 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3819 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3820 DCHECK(oat_dex_file != nullptr);
3821 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3822 sizeof(oat_dex_file->dex_sections_layout_))) {
3823 PLOG(ERROR) << "Failed to write dex layout sections."
3824 << " File: " << oat_dex_file->GetLocation()
3825 << " Output: " << oat_rodata->GetLocation();
3826 return false;
3827 }
3828 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3829 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3830 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3831 }
3832 oat_size_ = rodata_offset;
3833
3834 if (!oat_rodata->Flush()) {
3835 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3836 << " File: " << oat_rodata->GetLocation();
3837 return false;
3838 }
3839
3840 return true;
3841}
3842
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003843bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003844 // Write checksums
3845 off_t actual_offset = vdex_out->Seek(sizeof(VdexFile::Header), kSeekSet);
3846 if (actual_offset != sizeof(VdexFile::Header)) {
3847 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3848 << " File: " << vdex_out->GetLocation();
3849 return false;
3850 }
3851
3852 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3853 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3854 if (!vdex_out->WriteFully(
3855 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3856 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3857 << vdex_out->GetLocation();
3858 return false;
3859 }
3860 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3861 }
3862
3863 // Write header.
3864 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003865 if (actual_offset != 0) {
3866 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3867 << " File: " << vdex_out->GetLocation();
3868 return false;
3869 }
3870
David Brazdil5d5a36b2016-09-14 15:34:10 +01003871 DCHECK_NE(vdex_dex_files_offset_, 0u);
3872 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
David Brazdil93592f52017-12-08 10:53:27 +00003873 DCHECK_NE(vdex_quickening_info_offset_, 0u);
David Brazdil5d5a36b2016-09-14 15:34:10 +01003874
3875 size_t dex_section_size = vdex_verifier_deps_offset_ - vdex_dex_files_offset_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003876 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3877 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003878
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003879 VdexFile::Header vdex_header(oat_dex_files_.size(),
3880 dex_section_size,
3881 verifier_deps_section_size,
3882 quickening_info_section_size);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003883 if (!vdex_out->WriteFully(&vdex_header, sizeof(VdexFile::Header))) {
3884 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003885 return false;
3886 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003887 size_vdex_header_ = sizeof(VdexFile::Header);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003888
David Brazdil5d5a36b2016-09-14 15:34:10 +01003889 if (!vdex_out->Flush()) {
3890 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3891 << " File: " << vdex_out->GetLocation();
3892 return false;
3893 }
3894
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003895 return true;
3896}
3897
Vladimir Markof4da6752014-08-01 19:04:18 +01003898bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003899 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3900}
3901
3902bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003903 static const uint8_t kPadding[] = {
3904 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3905 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003906 DCHECK_LE(size, sizeof(kPadding));
3907 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003908 return false;
3909 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003910 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01003911 return true;
3912}
3913
Vladimir Marko944da602016-02-19 12:27:55 +00003914void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3915 DCHECK(dex_files_ != nullptr);
3916 DCHECK(relative_patcher_ != nullptr);
3917 DCHECK_NE(oat_data_offset_, 0u);
3918 if (image_writer_ != nullptr && !dex_files_->empty()) {
3919 // The oat data begin may not be initialized yet but the oat file offset is ready.
3920 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3921 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3922 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01003923 }
3924}
3925
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003926OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3927 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003928 CreateTypeLookupTable create_type_lookup_table,
3929 uint32_t dex_file_location_checksum,
3930 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003931 : source_(source),
3932 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003933 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003934 offset_(0),
3935 dex_file_location_size_(strlen(dex_file_location)),
3936 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003937 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003938 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00003939 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003940 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00003941 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00003942 type_bss_mapping_offset_(0u),
3943 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00003944 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003945 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07003946}
3947
3948size_t OatWriter::OatDexFile::SizeOf() const {
3949 return sizeof(dex_file_location_size_)
3950 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003951 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08003952 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003953 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003954 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003955 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00003956 + sizeof(type_bss_mapping_offset_)
3957 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07003958 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003959}
3960
3961bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3962 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08003963 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003964
Vladimir Markoe079e212016-05-25 12:49:49 +01003965 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003966 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003967 return false;
3968 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003969 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003970
Vladimir Markoe079e212016-05-25 12:49:49 +01003971 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08003972 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003973 return false;
3974 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003975 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003976
Vladimir Markoe079e212016-05-25 12:49:49 +01003977 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003978 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07003979 return false;
3980 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003981 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003982
Vladimir Markoe079e212016-05-25 12:49:49 +01003983 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08003984 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08003985 return false;
3986 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003987 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003988
Vladimir Markoe079e212016-05-25 12:49:49 +01003989 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003990 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3991 return false;
3992 }
3993 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3994
Vladimir Markoe079e212016-05-25 12:49:49 +01003995 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03003996 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3997 return false;
3998 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00003999 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004000
Mathieu Chartier120aa282017-08-05 16:03:03 -07004001 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4002 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4003 return false;
4004 }
4005 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4006
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004007 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4008 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4009 return false;
4010 }
4011 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4012
Vladimir Markof3c52b42017-11-17 17:32:12 +00004013 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4014 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4015 return false;
4016 }
4017 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4018
4019 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4020 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4021 return false;
4022 }
4023 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4024
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004025 return true;
4026}
4027
4028bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004029 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004030 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4031 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004032 return false;
4033 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004034 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004035 return true;
4036}
4037
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004038OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004039 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004040 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004041 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004042 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004043 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004044
Brian Carlstromba150c32013-08-27 17:31:03 -07004045 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4046
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004047 method_offsets_.resize(compiled_methods_with_code);
4048 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004049
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004050 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4051 // We only create this instance if there are at least some compiled.
4052 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004053 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004054 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4055 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4056 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4057 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004058 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004059 method_bitmap_size_ = 0;
4060 }
4061
4062 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004063 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004064 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004065 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4066 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004067 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004068 method_bitmap_->SetBit(i);
4069 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004070 } else {
4071 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004072 }
4073 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004074}
4075
Brian Carlstrom265091e2013-01-30 14:08:26 -08004076size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004077 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004078 + method_bitmap_size_
4079 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004080}
4081
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004082bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4083 OutputStream* out,
4084 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004085 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004086 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004087 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004088 return false;
4089 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004090 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004091
Vladimir Markoe079e212016-05-25 12:49:49 +01004092 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004093 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004094 return false;
4095 }
4096 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004097 return true;
4098}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004099
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004100bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004101 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004102 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004103 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004104 return false;
4105 }
4106 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004107
Vladimir Markoe079e212016-05-25 12:49:49 +01004108 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004109 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004110 return false;
4111 }
4112 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4113 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004114
Vladimir Markoe079e212016-05-25 12:49:49 +01004115 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004116 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004117 return false;
4118 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004119 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004120 return true;
4121}
4122
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004123const uint8_t* OatWriter::LookupBootImageInternTableSlot(const DexFile& dex_file,
4124 dex::StringIndex string_idx)
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004125 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01004126 uint32_t utf16_length;
4127 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
4128 DCHECK_EQ(utf16_length, CountModifiedUtf8Chars(utf8_data));
4129 InternTable::Utf8String string(utf16_length,
4130 utf8_data,
4131 ComputeUtf16HashFromModifiedUtf8(utf8_data, utf16_length));
4132 const InternTable* intern_table = Runtime::Current()->GetClassLinker()->intern_table_;
4133 for (const InternTable::Table::UnorderedSet& table : intern_table->strong_interns_.tables_) {
4134 auto it = table.Find(string);
4135 if (it != table.end()) {
4136 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4137 }
4138 }
4139 LOG(FATAL) << "Did not find boot image string " << utf8_data;
4140 UNREACHABLE();
4141}
4142
Vladimir Marko94ec2db2017-09-06 17:21:03 +01004143const uint8_t* OatWriter::LookupBootImageClassTableSlot(const DexFile& dex_file,
4144 dex::TypeIndex type_idx)
4145 NO_THREAD_SAFETY_ANALYSIS { // Single-threaded OatWriter can avoid locking.
4146 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
4147 ClassTable::DescriptorHashPair pair(descriptor, ComputeModifiedUtf8Hash(descriptor));
4148 ClassTable* table = Runtime::Current()->GetClassLinker()->boot_class_table_.get();
4149 for (const ClassTable::ClassSet& class_set : table->classes_) {
4150 auto it = class_set.Find(pair);
4151 if (it != class_set.end()) {
4152 return reinterpret_cast<const uint8_t*>(std::addressof(*it));
4153 }
4154 }
4155 LOG(FATAL) << "Did not find boot image class " << descriptor;
4156 UNREACHABLE();
4157}
4158
Vladimir Marko74527972016-11-29 15:57:32 +00004159} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004160} // namespace art