blob: f7de593a25d2538d20f2badb436603d033e469cf [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Igor Murashkin545412b2017-08-17 15:26:54 -070019#include <algorithm>
Vladimir Marko9bdf1082016-01-21 12:15:52 +000020#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070021#include <zlib.h>
22
Vladimir Markoc74658b2015-03-31 10:26:41 +010023#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070025#include "base/allocator.h"
Vladimir Marko0eb882b2017-05-15 13:39:18 +010026#include "base/bit_vector-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070027#include "base/enums.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000028#include "base/file_magic.h"
Andreas Gampedfcd82c2018-10-16 20:22:37 -070029#include "base/file_utils.h"
David Srbeckyb73323c2018-07-15 23:58:44 +010030#include "base/indenter.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080031#include "base/logging.h" // For VLOG
David Sehrc431b9d2018-03-02 12:01:51 -080032#include "base/os.h"
David Sehr67bf42e2018-02-26 16:43:04 -080033#include "base/safe_map.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080034#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080035#include "base/unix_file/fd_file.h"
David Sehr79e26072018-04-06 17:58:50 -070036#include "base/zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070037#include "class_linker.h"
Vladimir Marko94ec2db2017-09-06 17:21:03 +010038#include "class_table-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010039#include "compiled_method-inl.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000040#include "debug/method_debug_info.h"
David Sehr013fd802018-01-11 22:55:24 -080041#include "dex/art_dex_file_loader.h"
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -070042#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080043#include "dex/dex_file-inl.h"
44#include "dex/dex_file_loader.h"
45#include "dex/dex_file_types.h"
46#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070047#include "dex/type_lookup_table.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000048#include "dex/verification_results.h"
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080049#include "dex_container.h"
Jeff Hao608f2ce2016-10-19 11:17:11 -070050#include "dexlayout.h"
Andreas Gamped482e732017-04-24 17:59:09 -070051#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000052#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010053#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070054#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030055#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010056#include "image_writer.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010057#include "linker/buffered_output_stream.h"
58#include "linker/file_output_stream.h"
Vladimir Markof3c52b42017-11-17 17:32:12 +000059#include "linker/index_bss_mapping_encoder.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010060#include "linker/linker_patch.h"
Vladimir Marko944da602016-02-19 12:27:55 +000061#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000062#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "mirror/array.h"
64#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010065#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070066#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010067#include "oat_quick_method_header.h"
David Sehr82d046e2018-04-23 08:14:19 -070068#include "profile/profile_compilation_info.h"
Mathieu Chartier210531f2018-01-12 10:15:51 -080069#include "quicken_info.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070070#include "scoped_thread_state_change-inl.h"
David Srbeckyb73323c2018-07-15 23:58:44 +010071#include "stack_map.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010072#include "utils/dex_cache_arrays_layout-inl.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010073#include "vdex_file.h"
David Brazdil5d5a36b2016-09-14 15:34:10 +010074#include "verifier/verifier_deps.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070075
76namespace art {
Vladimir Marko74527972016-11-29 15:57:32 +000077namespace linker {
Brian Carlstrome24fa612011-09-29 00:53:55 -070078
Vladimir Marko9bdf1082016-01-21 12:15:52 +000079namespace { // anonymous namespace
80
Mathieu Chartier120aa282017-08-05 16:03:03 -070081// If we write dex layout info in the oat file.
82static constexpr bool kWriteDexLayoutInfo = true;
83
Igor Murashkin545412b2017-08-17 15:26:54 -070084// Force the OAT method layout to be sorted-by-name instead of
85// the default (class_def_idx, method_idx).
86//
87// Otherwise if profiles are used, that will act as
88// the primary sort order.
89//
90// A bit easier to use for development since oatdump can easily
91// show that things are being re-ordered when two methods aren't adjacent.
92static constexpr bool kOatWriterForceOatCodeLayout = false;
93
94static constexpr bool kOatWriterDebugOatCodeLayout = false;
95
Andreas Gampec55bb392018-09-21 00:02:02 +000096using UnalignedDexFileHeader __attribute__((__aligned__(1))) = DexFile::Header;
Vladimir Marko9bdf1082016-01-21 12:15:52 +000097
98const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
Andreas Gampec55bb392018-09-21 00:02:02 +000099 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000100}
101
Vladimir Markoc10a0c62018-11-16 11:39:22 +0000102inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
103 // We want to align the code rather than the preheader.
104 uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
105 uint32_t aligned_code_offset = compiled_method.AlignCode(unaligned_code_offset);
106 return aligned_code_offset - unaligned_code_offset;
107}
108
109} // anonymous namespace
110
111class OatWriter::ChecksumUpdatingOutputStream : public OutputStream {
Vladimir Markoe079e212016-05-25 12:49:49 +0100112 public:
Vladimir Markoc10a0c62018-11-16 11:39:22 +0000113 ChecksumUpdatingOutputStream(OutputStream* out, OatWriter* writer)
114 : OutputStream(out->GetLocation()), out_(out), writer_(writer) { }
Vladimir Markoe079e212016-05-25 12:49:49 +0100115
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100116 bool WriteFully(const void* buffer, size_t byte_count) override {
Vladimir Markoc10a0c62018-11-16 11:39:22 +0000117 if (buffer != nullptr) {
118 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(buffer);
119 uint32_t old_checksum = writer_->oat_checksum_;
120 writer_->oat_checksum_ = adler32(old_checksum, bytes, byte_count);
121 } else {
122 DCHECK_EQ(0U, byte_count);
123 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100124 return out_->WriteFully(buffer, byte_count);
125 }
126
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100127 off_t Seek(off_t offset, Whence whence) override {
Vladimir Markoe079e212016-05-25 12:49:49 +0100128 return out_->Seek(offset, whence);
129 }
130
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100131 bool Flush() override {
Vladimir Markoe079e212016-05-25 12:49:49 +0100132 return out_->Flush();
133 }
134
135 private:
136 OutputStream* const out_;
Vladimir Markoc10a0c62018-11-16 11:39:22 +0000137 OatWriter* const writer_;
Vladimir Markoe079e212016-05-25 12:49:49 +0100138};
139
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000140// Defines the location of the raw dex file to write.
141class OatWriter::DexFileSource {
142 public:
Mathieu Chartier497d5262017-02-28 20:17:30 -0800143 enum Type {
144 kNone,
145 kZipEntry,
146 kRawFile,
147 kRawData,
148 };
149
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000150 explicit DexFileSource(ZipEntry* zip_entry)
151 : type_(kZipEntry), source_(zip_entry) {
152 DCHECK(source_ != nullptr);
153 }
154
155 explicit DexFileSource(File* raw_file)
156 : type_(kRawFile), source_(raw_file) {
157 DCHECK(source_ != nullptr);
158 }
159
160 explicit DexFileSource(const uint8_t* dex_file)
161 : type_(kRawData), source_(dex_file) {
162 DCHECK(source_ != nullptr);
163 }
164
Mathieu Chartier497d5262017-02-28 20:17:30 -0800165 Type GetType() const { return type_; }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000166 bool IsZipEntry() const { return type_ == kZipEntry; }
167 bool IsRawFile() const { return type_ == kRawFile; }
168 bool IsRawData() const { return type_ == kRawData; }
169
170 ZipEntry* GetZipEntry() const {
171 DCHECK(IsZipEntry());
172 DCHECK(source_ != nullptr);
173 return static_cast<ZipEntry*>(const_cast<void*>(source_));
174 }
175
176 File* GetRawFile() const {
177 DCHECK(IsRawFile());
178 DCHECK(source_ != nullptr);
179 return static_cast<File*>(const_cast<void*>(source_));
180 }
181
182 const uint8_t* GetRawData() const {
183 DCHECK(IsRawData());
184 DCHECK(source_ != nullptr);
185 return static_cast<const uint8_t*>(source_);
186 }
187
188 void Clear() {
189 type_ = kNone;
190 source_ = nullptr;
191 }
192
193 private:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000194 Type type_;
195 const void* source_;
196};
197
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700198// OatClassHeader is the header only part of the oat class that is required even when compilation
199// is not enabled.
200class OatWriter::OatClassHeader {
201 public:
202 OatClassHeader(uint32_t offset,
203 uint32_t num_non_null_compiled_methods,
204 uint32_t num_methods,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000205 ClassStatus status)
206 : status_(enum_cast<uint16_t>(status)),
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700207 offset_(offset) {
208 // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
209 // kOatClassAllCompiled unless there is at least one compiled method. This means in an
210 // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
211 if (num_non_null_compiled_methods == 0) {
212 type_ = kOatClassNoneCompiled;
213 } else if (num_non_null_compiled_methods == num_methods) {
214 type_ = kOatClassAllCompiled;
215 } else {
216 type_ = kOatClassSomeCompiled;
217 }
218 }
219
220 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
221
222 static size_t SizeOf() {
223 return sizeof(status_) + sizeof(type_);
224 }
225
226 // Data to write.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000227 static_assert(enum_cast<>(ClassStatus::kLast) < (1 << 16), "class status won't fit in 16bits");
228 uint16_t status_;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700229
230 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
231 uint16_t type_;
232
233 // Offset of start of OatClass from beginning of OatHeader. It is
234 // used to validate file position when writing.
235 uint32_t offset_;
236};
237
238// The actual oat class body contains the information about compiled methods. It is only required
239// for compiler filters that have any compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000240class OatWriter::OatClass {
241 public:
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700242 OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100243 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700244 uint16_t oat_class_type);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000245 OatClass(OatClass&& src) = default;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000246 size_t SizeOf() const;
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700247 bool Write(OatWriter* oat_writer, OutputStream* out) const;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000248
249 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
250 return compiled_methods_[class_def_method_index];
251 }
252
Vladimir Marko49b0f452015-12-10 13:49:19 +0000253 // CompiledMethods for each class_def_method_index, or null if no method is available.
254 dchecked_vector<CompiledMethod*> compiled_methods_;
255
256 // Offset from OatClass::offset_ to the OatMethodOffsets for the
257 // class_def_method_index. If 0, it means the corresponding
258 // CompiledMethod entry in OatClass::compiled_methods_ should be
259 // null and that the OatClass::type_ should be kOatClassBitmap.
260 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
261
262 // Data to write.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000263 uint32_t method_bitmap_size_;
264
265 // bit vector indexed by ClassDef method index. When
266 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
267 // method has an OatMethodOffsets in methods_offsets_, otherwise
268 // the entry was ommited to save space. If OatClassType::type_ is
269 // not is kOatClassBitmap, the bitmap will be null.
270 std::unique_ptr<BitVector> method_bitmap_;
271
272 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
273 // present in the OatClass. Note that some may be missing if
274 // OatClass::compiled_methods_ contains null values (and
275 // oat_method_offsets_offsets_from_oat_class_ should contain 0
276 // values in this case).
277 dchecked_vector<OatMethodOffsets> method_offsets_;
278 dchecked_vector<OatQuickMethodHeader> method_headers_;
279
280 private:
281 size_t GetMethodOffsetsRawSize() const {
282 return method_offsets_.size() * sizeof(method_offsets_[0]);
283 }
284
285 DISALLOW_COPY_AND_ASSIGN(OatClass);
286};
287
288class OatWriter::OatDexFile {
289 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000290 OatDexFile(const char* dex_file_location,
291 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000292 CreateTypeLookupTable create_type_lookup_table,
293 uint32_t dex_file_location_checksun,
294 size_t dex_file_size);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000295 OatDexFile(OatDexFile&& src) = default;
296
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000297 const char* GetLocation() const {
298 return dex_file_location_data_;
299 }
300
Vladimir Marko49b0f452015-12-10 13:49:19 +0000301 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000302 bool Write(OatWriter* oat_writer, OutputStream* out) const;
303 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
304
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100305 size_t GetClassOffsetsRawSize() const {
306 return class_offsets_.size() * sizeof(class_offsets_[0]);
307 }
308
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000309 // The source of the dex file.
310 DexFileSource source_;
311
312 // Whether to create the type lookup table.
313 CreateTypeLookupTable create_type_lookup_table_;
314
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000315 // Dex file size. Passed in the constructor, but could be
316 // overwritten by LayoutAndWriteDexFile.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000317 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000318
319 // Offset of start of OatDexFile from beginning of OatHeader. It is
320 // used to validate file position when writing.
321 size_t offset_;
322
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000323 ///// Start of data to write to vdex/oat file.
324
325 const uint32_t dex_file_location_size_;
326 const char* const dex_file_location_data_;
327
328 // The checksum of the dex file.
329 const uint32_t dex_file_location_checksum_;
330
331 // Offset of the dex file in the vdex file. Set when writing dex files in
332 // SeekToDexFile.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000333 uint32_t dex_file_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000334
335 // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000336 uint32_t lookup_table_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000337
338 // Class and BSS offsets set in PrepareLayout.
339 uint32_t class_offsets_offset_;
Nicolas Geoffray715d6722017-11-20 22:28:46 +0000340 uint32_t method_bss_mapping_offset_;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000341 uint32_t type_bss_mapping_offset_;
342 uint32_t string_bss_mapping_offset_;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000343
344 // Offset of dex sections that will have different runtime madvise states.
345 // Set in WriteDexLayoutSections.
Mathieu Chartier120aa282017-08-05 16:03:03 -0700346 uint32_t dex_sections_layout_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000347
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000348 // Data to write to a separate section. We set the length
349 // of the vector in OpenDexFiles.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000350 dchecked_vector<uint32_t> class_offsets_;
351
Mathieu Chartier120aa282017-08-05 16:03:03 -0700352 // Dex section layout info to serialize.
353 DexLayoutSections dex_sections_layout_;
354
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000355 ///// End of data to write to vdex/oat file.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000356 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000357 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
358};
359
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100360#define DCHECK_OFFSET() \
361 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
362 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
363
364#define DCHECK_OFFSET_() \
365 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
366 << "file_offset=" << file_offset << " offset_=" << offset_
367
Vladimir Markoa0431112018-06-25 09:32:54 +0100368OatWriter::OatWriter(const CompilerOptions& compiler_options,
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700369 TimingLogger* timings,
370 ProfileCompilationInfo* info,
371 CompactDexLevel compact_dex_level)
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000372 : write_state_(WriteState::kAddingDexFileSources),
373 timings_(timings),
374 raw_dex_files_(),
375 zip_archives_(),
376 zipped_dex_files_(),
377 zipped_dex_file_locations_(),
378 compiler_driver_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100379 compiler_options_(compiler_options),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000380 image_writer_(nullptr),
Mathieu Chartier792111c2018-02-15 13:02:15 -0800381 extract_dex_files_into_vdex_(true),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000382 dex_files_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100383 vdex_size_(0u),
384 vdex_dex_files_offset_(0u),
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800385 vdex_dex_shared_data_offset_(0u),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100386 vdex_verifier_deps_offset_(0u),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100387 vdex_quickening_info_offset_(0u),
Vladimir Markoc10a0c62018-11-16 11:39:22 +0000388 oat_checksum_(adler32(0L, Z_NULL, 0)),
Vladimir Markob066d432018-01-03 13:14:37 +0000389 code_size_(0u),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100390 oat_size_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000391 data_bimg_rel_ro_start_(0u),
392 data_bimg_rel_ro_size_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000393 bss_start_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000394 bss_size_(0u),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100395 bss_methods_offset_(0u),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000396 bss_roots_offset_(0u),
Vladimir Markob066d432018-01-03 13:14:37 +0000397 data_bimg_rel_ro_entries_(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100398 bss_method_entry_references_(),
399 bss_method_entries_(),
Vladimir Marko6bec91c2017-01-09 15:03:12 +0000400 bss_type_entries_(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000401 bss_string_entries_(),
Vladimir Markof4da6752014-08-01 19:04:18 +0100402 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700403 oat_header_(nullptr),
David Brazdil7b49e6c2016-09-01 11:06:18 +0100404 size_vdex_header_(0),
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000405 size_vdex_checksums_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700406 size_dex_file_alignment_(0),
407 size_executable_offset_alignment_(0),
408 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700409 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700410 size_dex_file_(0),
David Brazdil5d5a36b2016-09-14 15:34:10 +0100411 size_verifier_deps_(0),
412 size_verifier_deps_alignment_(0),
Nicolas Geoffray4acefd32016-10-24 13:14:58 +0100413 size_quickening_info_(0),
414 size_quickening_info_alignment_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700415 size_interpreter_to_interpreter_bridge_(0),
416 size_interpreter_to_compiled_code_bridge_(0),
417 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800418 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700419 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700420 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700421 size_quick_to_interpreter_bridge_(0),
422 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100423 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700424 size_code_(0),
425 size_code_alignment_(0),
Vladimir Markob066d432018-01-03 13:14:37 +0000426 size_data_bimg_rel_ro_(0),
427 size_data_bimg_rel_ro_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100428 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100429 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700430 size_vmap_table_(0),
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -0700431 size_method_info_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700432 size_oat_dex_file_location_size_(0),
433 size_oat_dex_file_location_data_(0),
434 size_oat_dex_file_location_checksum_(0),
435 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000436 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000437 size_oat_dex_file_lookup_table_offset_(0),
Mathieu Chartier120aa282017-08-05 16:03:03 -0700438 size_oat_dex_file_dex_layout_sections_offset_(0),
439 size_oat_dex_file_dex_layout_sections_(0),
440 size_oat_dex_file_dex_layout_sections_alignment_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100441 size_oat_dex_file_method_bss_mapping_offset_(0),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000442 size_oat_dex_file_type_bss_mapping_offset_(0),
443 size_oat_dex_file_string_bss_mapping_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000444 size_oat_lookup_table_alignment_(0),
445 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000446 size_oat_class_offsets_alignment_(0),
447 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700448 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700449 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700450 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100451 size_oat_class_method_offsets_(0),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100452 size_method_bss_mappings_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +0000453 size_type_bss_mappings_(0u),
454 size_string_bss_mappings_(0u),
Vladimir Marko944da602016-02-19 12:27:55 +0000455 relative_patcher_(nullptr),
Mathieu Chartier603ccab2017-10-20 14:34:28 -0700456 profile_compilation_info_(info),
457 compact_dex_level_(compact_dex_level) {
Mathieu Chartierddf39552018-04-03 10:22:27 -0700458 // If we have a profile, always use at least the default compact dex level. The reason behind
459 // this is that CompactDex conversion is not more expensive than normal dexlayout.
460 if (info != nullptr && compact_dex_level_ == CompactDexLevel::kCompactDexLevelNone) {
461 compact_dex_level_ = kDefaultCompactDexLevel;
462 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000463}
464
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000465static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
466 const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
467 if (!valid_standard_dex_magic) {
468 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
469 return false;
470 }
471 if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
472 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
473 return false;
474 }
475 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
476 if (header->file_size_ < sizeof(DexFile::Header)) {
477 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
478 << " File: " << location;
479 return false;
480 }
481 return true;
482}
483
484static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
485 uint8_t* raw_header,
486 const char* location) {
487 // Read the dex file header and perform minimal verification.
488 if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
489 PLOG(ERROR) << "Failed to read dex file header. Actual: "
490 << " File: " << location << " Output: " << file->GetPath();
491 return nullptr;
492 }
493 if (!ValidateDexFileHeader(raw_header, location)) {
494 return nullptr;
495 }
496
497 return AsUnalignedDexFileHeader(raw_header);
498}
499
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000500bool OatWriter::AddDexFileSource(const char* filename,
501 const char* location,
502 CreateTypeLookupTable create_type_lookup_table) {
503 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
504 uint32_t magic;
505 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700506 File fd = OpenAndReadMagic(filename, &magic, &error_msg);
507 if (fd.Fd() == -1) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000508 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
509 return false;
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700510 } else if (DexFileLoader::IsMagicValid(magic)) {
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000511 uint8_t raw_header[sizeof(DexFile::Header)];
512 const UnalignedDexFileHeader* header = GetDexFileHeader(&fd, raw_header, location);
513 if (header == nullptr) {
514 return false;
515 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000516 // The file is open for reading, not writing, so it's OK to let the File destructor
517 // close it without checking for explicit Close(), so pass checkUsage = false.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700518 raw_dex_files_.emplace_back(new File(fd.Release(), location, /* checkUsage */ false));
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000519 oat_dex_files_.emplace_back(/* OatDexFile */
520 location,
521 DexFileSource(raw_dex_files_.back().get()),
522 create_type_lookup_table,
523 header->checksum_,
524 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000525 } else if (IsZipMagic(magic)) {
526 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
527 return false;
528 }
529 } else {
530 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
531 return false;
532 }
533 return true;
534}
535
536// Add dex file source(s) from a zip file specified by a file handle.
Andreas Gampe43e10b02016-07-15 17:17:34 -0700537bool OatWriter::AddZippedDexFilesSource(File&& zip_fd,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000538 const char* location,
539 CreateTypeLookupTable create_type_lookup_table) {
540 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
541 std::string error_msg;
Andreas Gampe43e10b02016-07-15 17:17:34 -0700542 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.Release(), location, &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 ZipArchive* zip_archive = zip_archives_.back().get();
544 if (zip_archive == nullptr) {
545 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
546 << error_msg;
547 return false;
548 }
549 for (size_t i = 0; ; ++i) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700550 std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000551 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
552 if (entry == nullptr) {
553 break;
554 }
555 zipped_dex_files_.push_back(std::move(entry));
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700556 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000557 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000558 // We override the checksum from header with the CRC from ZIP entry.
559 oat_dex_files_.emplace_back(/* OatDexFile */
560 full_location,
561 DexFileSource(zipped_dex_files_.back().get()),
562 create_type_lookup_table,
563 zipped_dex_files_.back()->GetCrc32(),
564 zipped_dex_files_.back()->GetUncompressedLength());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000565 }
566 if (zipped_dex_file_locations_.empty()) {
567 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
568 return false;
569 }
570 return true;
571}
572
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000573// Add dex file source(s) from a vdex file specified by a file handle.
574bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
575 const char* location,
576 CreateTypeLookupTable create_type_lookup_table) {
577 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000578 DCHECK(vdex_file.HasDexSection());
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000579 const uint8_t* current_dex_data = nullptr;
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000580 for (size_t i = 0; i < vdex_file.GetVerifierDepsHeader().GetNumberOfDexFiles(); ++i) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000581 current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
582 if (current_dex_data == nullptr) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000583 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
584 return false;
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000585 }
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700586
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700587 if (!DexFileLoader::IsMagicValid(current_dex_data)) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000588 LOG(ERROR) << "Invalid magic in vdex file created from " << location;
589 return false;
590 }
591 // We used `zipped_dex_file_locations_` to keep the strings in memory.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700592 zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000593 const char* full_location = zipped_dex_file_locations_.back().c_str();
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000594 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
595 oat_dex_files_.emplace_back(/* OatDexFile */
596 full_location,
597 DexFileSource(current_dex_data),
598 create_type_lookup_table,
599 vdex_file.GetLocationChecksum(i),
600 header->file_size_);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000601 }
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +0000602
603 if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
604 LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
605 return false;
606 }
607
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000608 if (oat_dex_files_.empty()) {
609 LOG(ERROR) << "No dex files in vdex file created from " << location;
610 return false;
611 }
612 return true;
613}
614
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000615// Add dex file source from raw memory.
616bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
617 const char* location,
618 uint32_t location_checksum,
619 CreateTypeLookupTable create_type_lookup_table) {
620 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
621 if (data.size() < sizeof(DexFile::Header)) {
622 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
623 << data.size() << " File: " << location;
624 return false;
625 }
626 if (!ValidateDexFileHeader(data.data(), location)) {
627 return false;
628 }
629 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
630 if (data.size() < header->file_size_) {
631 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
632 << " file size from header: " << header->file_size_ << " File: " << location;
633 return false;
634 }
635
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +0000636 oat_dex_files_.emplace_back(/* OatDexFile */
637 location,
638 DexFileSource(data.data()),
639 create_type_lookup_table,
640 location_checksum,
641 header->file_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000642 return true;
643}
644
Calin Juravle1ce70852017-06-28 10:59:03 -0700645dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
646 dchecked_vector<std::string> locations;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000647 locations.reserve(oat_dex_files_.size());
648 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
649 locations.push_back(oat_dex_file.GetLocation());
650 }
651 return locations;
652}
653
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700654bool OatWriter::MayHaveCompiledMethods() const {
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100655 return GetCompilerOptions().IsAnyCompilationEnabled();
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700656}
657
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000658bool OatWriter::WriteAndOpenDexFiles(
David Brazdil7b49e6c2016-09-01 11:06:18 +0100659 File* vdex_file,
660 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000661 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800662 bool verify,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +0000663 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +0000664 CopyOption copy_dex_files,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100665 /*out*/ std::vector<MemMap>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000666 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
667 CHECK(write_state_ == WriteState::kAddingDexFileSources);
668
David Brazdil7b49e6c2016-09-01 11:06:18 +0100669 // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
670 if (!RecordOatDataOffset(oat_rodata)) {
671 return false;
672 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000673
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100674 std::vector<MemMap> dex_files_map;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000675 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100676
677 // Initialize VDEX and OAT headers.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000678
679 // Reserve space for Vdex header and checksums.
Nicolas Geoffray3a293552018-03-02 10:52:16 +0000680 vdex_size_ = sizeof(VdexFile::VerifierDepsHeader) +
681 oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
Vladimir Markoa0431112018-06-25 09:32:54 +0100682 oat_size_ = InitOatHeader(dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100683 key_value_store);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100684
Vladimir Markoc10a0c62018-11-16 11:39:22 +0000685 ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, this);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100686
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000687 std::unique_ptr<BufferedOutputStream> vdex_out =
688 std::make_unique<BufferedOutputStream>(std::make_unique<FileOutputStream>(vdex_file));
689 // Write DEX files into VDEX, mmap and open them.
Mathieu Chartier792111c2018-02-15 13:02:15 -0800690 if (!WriteDexFiles(vdex_out.get(), vdex_file, update_input_vdex, copy_dex_files) ||
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000691 !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
692 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000693 }
David Brazdil181e1cc2016-09-01 16:38:47 +0000694
Mathieu Chartier120aa282017-08-05 16:03:03 -0700695 // Write type lookup tables into the oat file.
David Brazdil181e1cc2016-09-01 16:38:47 +0000696 if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
697 return false;
698 }
699
Mathieu Chartier120aa282017-08-05 16:03:03 -0700700 // Write dex layout sections into the oat file.
701 if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
702 return false;
703 }
704
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000705 *opened_dex_files_map = std::move(dex_files_map);
706 *opened_dex_files = std::move(dex_files);
707 write_state_ = WriteState::kPrepareLayout;
708 return true;
709}
710
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100711// Initialize the writer with the given parameters.
712void OatWriter::Initialize(const CompilerDriver* compiler_driver,
713 ImageWriter* image_writer,
714 const std::vector<const DexFile*>& dex_files) {
715 compiler_driver_ = compiler_driver;
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100716 image_writer_ = image_writer;
717 dex_files_ = &dex_files;
718}
719
Vladimir Marko74527972016-11-29 15:57:32 +0000720void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000721 CHECK(write_state_ == WriteState::kPrepareLayout);
722
Vladimir Marko944da602016-02-19 12:27:55 +0000723 relative_patcher_ = relative_patcher;
724 SetMultiOatRelativePatcherAdjustment();
725
Vladimir Markoa0431112018-06-25 09:32:54 +0100726 if (GetCompilerOptions().IsBootImage()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000727 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800728 }
Vladimir Markoa0431112018-06-25 09:32:54 +0100729 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000730 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100731
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100732 {
733 TimingLogger::ScopedTiming split("InitBssLayout", timings_);
734 InitBssLayout(instruction_set);
735 }
736
David Brazdil7b49e6c2016-09-01 11:06:18 +0100737 uint32_t offset = oat_size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800738 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100739 TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
740 offset = InitClassOffsets(offset);
741 }
742 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000743 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800744 offset = InitOatClasses(offset);
745 }
746 {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000747 TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
748 offset = InitIndexBssMappings(offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100749 }
750 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000751 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100752 offset = InitOatMaps(offset);
753 }
754 {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100755 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
756 oat_header_->SetOatDexFilesOffset(offset);
757 offset = InitOatDexFiles(offset);
758 }
759 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000760 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800761 offset = InitOatCode(offset);
762 }
763 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000764 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800765 offset = InitOatCodeDexFiles(offset);
Vladimir Markob066d432018-01-03 13:14:37 +0000766 code_size_ = offset - GetOatHeader().GetExecutableOffset();
Ian Rogersca368cb2013-11-15 15:52:08 -0800767 }
Vladimir Markob066d432018-01-03 13:14:37 +0000768 {
769 TimingLogger::ScopedTiming split("InitDataBimgRelRoLayout", timings_);
770 offset = InitDataBimgRelRoLayout(offset);
771 }
772 oat_size_ = offset; // .bss does not count towards oat_size_.
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100773 bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
Vladimir Marko09d09432015-09-08 13:47:48 +0100774
Brian Carlstrome24fa612011-09-29 00:53:55 -0700775 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000776
777 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700778}
779
Ian Rogers0571d352011-11-03 19:51:38 -0700780OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700781}
782
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100783class OatWriter::DexMethodVisitor {
784 public:
785 DexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100786 : writer_(writer),
787 offset_(offset),
788 dex_file_(nullptr),
Andreas Gampee2abbc62017-09-15 11:59:26 -0700789 class_def_index_(dex::kDexNoIndex) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100790
791 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
792 DCHECK(dex_file_ == nullptr);
Andreas Gampee2abbc62017-09-15 11:59:26 -0700793 DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794 dex_file_ = dex_file;
795 class_def_index_ = class_def_index;
796 return true;
797 }
798
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -0700799 virtual bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100800
801 virtual bool EndClass() {
802 if (kIsDebugBuild) {
803 dex_file_ = nullptr;
Andreas Gampee2abbc62017-09-15 11:59:26 -0700804 class_def_index_ = dex::kDexNoIndex;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100805 }
806 return true;
807 }
808
809 size_t GetOffset() const {
810 return offset_;
811 }
812
813 protected:
814 virtual ~DexMethodVisitor() { }
815
816 OatWriter* const writer_;
817
818 // The offset is usually advanced for each visited method by the derived class.
819 size_t offset_;
820
821 // The dex file and class def index are set in StartClass().
822 const DexFile* dex_file_;
823 size_t class_def_index_;
824};
825
826class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
827 public:
828 OatDexMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100829 : DexMethodVisitor(writer, offset),
830 oat_class_index_(0u),
831 method_offsets_index_(0u) {}
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100832
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100833 bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100834 DexMethodVisitor::StartClass(dex_file, class_def_index);
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700835 if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
836 // There are no oat classes if there aren't any compiled methods.
837 CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
838 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100839 method_offsets_index_ = 0u;
840 return true;
841 }
842
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100843 bool EndClass() override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100844 ++oat_class_index_;
845 return DexMethodVisitor::EndClass();
846 }
847
848 protected:
849 size_t oat_class_index_;
850 size_t method_offsets_index_;
851};
852
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100853static bool HasCompiledCode(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000854 return method != nullptr && !method->GetQuickCode().empty();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100855}
856
857static bool HasQuickeningInfo(const CompiledMethod* method) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000858 // The dextodexcompiler puts the quickening info table into the CompiledMethod
859 // for simplicity.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100860 return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
861}
862
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100863class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
864 public:
865 explicit InitBssLayoutMethodVisitor(OatWriter* writer)
866 : DexMethodVisitor(writer, /* offset */ 0u) {}
867
868 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100869 const ClassAccessor::Method& method) override {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100870 // Look for patches with .bss references and prepare maps with placeholders for their offsets.
871 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -0700872 MethodReference(dex_file_, method.GetIndex()));
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100873 if (HasCompiledCode(compiled_method)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100874 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Markob066d432018-01-03 13:14:37 +0000875 if (patch.GetType() == LinkerPatch::Type::kDataBimgRelRo) {
876 writer_->data_bimg_rel_ro_entries_.Overwrite(patch.BootImageOffset(),
877 /* placeholder */ 0u);
878 } else if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100879 MethodReference target_method = patch.TargetMethod();
Vladimir Markof3c52b42017-11-17 17:32:12 +0000880 AddBssReference(target_method,
881 target_method.dex_file->NumMethodIds(),
882 &writer_->bss_method_entry_references_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100883 writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
884 } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000885 TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
886 AddBssReference(target_type,
887 target_type.dex_file->NumTypeIds(),
888 &writer_->bss_type_entry_references_);
889 writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100890 } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
Vladimir Markof3c52b42017-11-17 17:32:12 +0000891 StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
892 AddBssReference(target_string,
893 target_string.dex_file->NumStringIds(),
894 &writer_->bss_string_entry_references_);
895 writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100896 }
897 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100898 } else {
899 DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100900 }
901 return true;
902 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000903
904 private:
905 void AddBssReference(const DexFileReference& ref,
906 size_t number_of_indexes,
907 /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
908 // We currently support inlining of throwing instructions only when they originate in the
909 // same dex file as the outer method. All .bss references are used by throwing instructions.
910 DCHECK_EQ(dex_file_, ref.dex_file);
911
912 auto refs_it = references->find(ref.dex_file);
913 if (refs_it == references->end()) {
914 refs_it = references->Put(
915 ref.dex_file,
916 BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
917 refs_it->second.ClearAllBits();
918 }
919 refs_it->second.SetBit(ref.index);
920 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100921};
922
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
924 public:
925 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100926 : DexMethodVisitor(writer, offset),
927 compiled_methods_(),
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100928 compiled_methods_with_code_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000929 size_t num_classes = 0u;
930 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
931 num_classes += oat_dex_file.class_offsets_.size();
932 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700933 // If we aren't compiling only reserve headers.
934 writer_->oat_class_headers_.reserve(num_classes);
935 if (writer->MayHaveCompiledMethods()) {
936 writer->oat_classes_.reserve(num_classes);
937 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100938 compiled_methods_.reserve(256u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100939 // If there are any classes, the class offsets allocation aligns the offset.
940 DCHECK(num_classes == 0u || IsAligned<4u>(offset));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100941 }
942
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100943 bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100944 DexMethodVisitor::StartClass(dex_file, class_def_index);
945 compiled_methods_.clear();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100946 compiled_methods_with_code_ = 0u;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100947 return true;
948 }
949
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300950 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100951 const ClassAccessor::Method& method) override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100952 // Fill in the compiled_methods_ array for methods that have a
953 // CompiledMethod. We track the number of non-null entries in
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100954 // compiled_methods_with_code_ since we only want to allocate
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100955 // OatMethodOffsets for the compiled methods.
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -0700956 uint32_t method_idx = method.GetIndex();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100957 CompiledMethod* compiled_method =
958 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
959 compiled_methods_.push_back(compiled_method);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100960 if (HasCompiledCode(compiled_method)) {
961 ++compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100962 }
963 return true;
964 }
965
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100966 bool EndClass() override {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100967 ClassReference class_ref(dex_file_, class_def_index_);
Vladimir Marko2c64a832018-01-04 11:31:56 +0000968 ClassStatus status;
Andreas Gampebb846102017-05-11 21:03:35 -0700969 bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
970 if (!found) {
Vladimir Marko2afaff72018-11-30 17:01:50 +0000971 const VerificationResults* results = writer_->compiler_options_.GetVerificationResults();
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700972 if (results != nullptr && results->IsClassRejected(class_ref)) {
Andreas Gampebb846102017-05-11 21:03:35 -0700973 // The oat class status is used only for verification of resolved classes,
Vladimir Marko2c64a832018-01-04 11:31:56 +0000974 // so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
Andreas Gampebb846102017-05-11 21:03:35 -0700975 // during compile-time verification.
Vladimir Marko2c64a832018-01-04 11:31:56 +0000976 status = ClassStatus::kErrorResolved;
Andreas Gampebb846102017-05-11 21:03:35 -0700977 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +0000978 status = ClassStatus::kNotReady;
Andreas Gampebb846102017-05-11 21:03:35 -0700979 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100980 }
981
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700982 writer_->oat_class_headers_.emplace_back(offset_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100983 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700984 compiled_methods_.size(),
985 status);
986 OatClassHeader& header = writer_->oat_class_headers_.back();
987 offset_ += header.SizeOf();
988 if (writer_->MayHaveCompiledMethods()) {
989 writer_->oat_classes_.emplace_back(compiled_methods_,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100990 compiled_methods_with_code_,
Mathieu Chartier3957bff2017-07-16 13:55:27 -0700991 header.type_);
992 offset_ += writer_->oat_classes_.back().SizeOf();
993 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100994 return DexMethodVisitor::EndClass();
995 }
996
997 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000998 dchecked_vector<CompiledMethod*> compiled_methods_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +0100999 size_t compiled_methods_with_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001000};
1001
Igor Murashkin545412b2017-08-17 15:26:54 -07001002// CompiledMethod + metadata required to do ordered method layout.
1003//
1004// See also OrderedMethodVisitor.
1005struct OatWriter::OrderedMethodData {
1006 ProfileCompilationInfo::MethodHotness method_hotness;
1007 OatClass* oat_class;
1008 CompiledMethod* compiled_method;
1009 MethodReference method_reference;
1010 size_t method_offsets_index;
1011
1012 size_t class_def_index;
1013 uint32_t access_flags;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001014 const dex::CodeItem* code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001015
1016 // A value of -1 denotes missing debug info
1017 static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
1018 // Index into writer_->method_info_
1019 size_t debug_info_idx;
1020
1021 bool HasDebugInfo() const {
1022 return debug_info_idx != kDebugInfoIdxInvalid;
1023 }
1024
1025 // Bin each method according to the profile flags.
1026 //
1027 // Groups by e.g.
1028 // -- not hot at all
1029 // -- hot
1030 // -- hot and startup
1031 // -- hot and post-startup
1032 // -- hot and startup and poststartup
1033 // -- startup
1034 // -- startup and post-startup
1035 // -- post-startup
1036 //
1037 // (See MethodHotness enum definition for up-to-date binning order.)
1038 bool operator<(const OrderedMethodData& other) const {
1039 if (kOatWriterForceOatCodeLayout) {
1040 // Development flag: Override default behavior by sorting by name.
1041
1042 std::string name = method_reference.PrettyMethod();
1043 std::string other_name = other.method_reference.PrettyMethod();
1044 return name < other_name;
1045 }
1046
1047 // Use the profile's method hotness to determine sort order.
1048 if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1049 return true;
1050 }
1051
1052 // Default: retain the original order.
1053 return false;
1054 }
1055
1056 private:
1057 // Used to determine relative order for OAT code layout when determining
1058 // binning.
1059 size_t GetMethodHotnessOrder() const {
1060 bool hotness[] = {
1061 method_hotness.IsHot(),
1062 method_hotness.IsStartup(),
1063 method_hotness.IsPostStartup()
1064 };
1065
1066
1067 // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1068 // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1069 // time that memory is referenced in the process.
1070
1071 size_t hotness_bits = 0;
1072 for (size_t i = 0; i < arraysize(hotness); ++i) {
1073 if (hotness[i]) {
1074 hotness_bits |= (1 << i);
1075 }
1076 }
1077
1078 if (kIsDebugBuild) {
1079 // Check for bins that are always-empty given a real profile.
1080 if (method_hotness.IsHot() &&
1081 !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1082 std::string name = method_reference.PrettyMethod();
Mathieu Chartierc46cf802017-09-28 11:52:19 -07001083 LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1084 << "either start-up or post-startup. Possible corrupted profile?";
Igor Murashkin545412b2017-08-17 15:26:54 -07001085 // This is not fatal, so only warn.
1086 }
1087 }
1088
1089 return hotness_bits;
1090 }
1091};
1092
1093// Given a queue of CompiledMethod in some total order,
1094// visit each one in that order.
1095class OatWriter::OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001096 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001097 explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1098 : ordered_methods_(std::move(ordered_methods)) {
1099 }
1100
1101 virtual ~OrderedMethodVisitor() {}
1102
1103 // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
1104 bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1105 if (!VisitStart()) {
1106 return false;
1107 }
1108
1109 for (const OrderedMethodData& method_data : ordered_methods_) {
1110 if (!VisitMethod(method_data)) {
1111 return false;
1112 }
1113 }
1114
1115 return VisitComplete();
1116 }
1117
1118 // Invoked once at the beginning, prior to visiting anything else.
1119 //
1120 // Return false to abort further visiting.
1121 virtual bool VisitStart() { return true; }
1122
1123 // Invoked repeatedly in the order specified by `ordered_methods`.
1124 //
1125 // Return false to short-circuit and to stop visiting further methods.
1126 virtual bool VisitMethod(const OrderedMethodData& method_data)
1127 REQUIRES_SHARED(Locks::mutator_lock_) = 0;
1128
1129 // Invoked once at the end, after every other method has been successfully visited.
1130 //
1131 // Return false to indicate the overall `Visit` has failed.
1132 virtual bool VisitComplete() = 0;
1133
1134 OrderedMethodList ReleaseOrderedMethods() {
1135 return std::move(ordered_methods_);
1136 }
1137
1138 private:
1139 // List of compiled methods, sorted by the order defined in OrderedMethodData.
1140 // Methods can be inserted more than once in case of duplicated methods.
1141 OrderedMethodList ordered_methods_;
1142};
1143
1144// Visit every compiled method in order to determine its order within the OAT file.
1145// Methods from the same class do not need to be adjacent in the OAT code.
1146class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1147 public:
1148 LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1149 : OatDexMethodVisitor(writer, offset) {
1150 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001151
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001152 bool EndClass() override {
Vladimir Markof4da6752014-08-01 19:04:18 +01001153 OatDexMethodVisitor::EndClass();
Vladimir Markof4da6752014-08-01 19:04:18 +01001154 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001155 }
1156
Igor Murashkin545412b2017-08-17 15:26:54 -07001157 bool VisitMethod(size_t class_def_method_index,
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001158 const ClassAccessor::Method& method)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001159 override
Igor Murashkin545412b2017-08-17 15:26:54 -07001160 REQUIRES_SHARED(Locks::mutator_lock_) {
1161 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1162
Vladimir Marko49b0f452015-12-10 13:49:19 +00001163 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001164 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1165
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001166 if (HasCompiledCode(compiled_method)) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001167 size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001168
Igor Murashkin545412b2017-08-17 15:26:54 -07001169 {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001170 const CompilerOptions& compiler_options = writer_->GetCompilerOptions();
Igor Murashkin545412b2017-08-17 15:26:54 -07001171 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1172 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -08001173
Igor Murashkin545412b2017-08-17 15:26:54 -07001174 // Debug method info must be pushed in the original order
1175 // (i.e. all methods from the same class must be adjacent in the debug info sections)
1176 // ElfCompilationUnitWriter::Write requires this.
1177 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1178 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1179 writer_->method_info_.push_back(info);
1180
1181 // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1182 // once we know the offsets.
1183 //
1184 // Store the index into writer_->method_info_ since future push-backs
1185 // could reallocate and change the underlying data address.
1186 debug_info_idx = writer_->method_info_.size() - 1;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001187 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001188 }
1189
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001190 MethodReference method_ref(dex_file_, method.GetIndex());
Igor Murashkin545412b2017-08-17 15:26:54 -07001191
1192 // Lookup method hotness from profile, if available.
1193 // Otherwise assume a default of none-hotness.
1194 ProfileCompilationInfo::MethodHotness method_hotness =
1195 writer_->profile_compilation_info_ != nullptr
1196 ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1197 : ProfileCompilationInfo::MethodHotness();
1198
1199 // Handle duplicate methods by pushing them repeatedly.
1200 OrderedMethodData method_data = {
1201 method_hotness,
1202 oat_class,
1203 compiled_method,
1204 method_ref,
1205 method_offsets_index_,
1206 class_def_index_,
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001207 method.GetAccessFlags(),
1208 method.GetCodeItem(),
Igor Murashkin545412b2017-08-17 15:26:54 -07001209 debug_info_idx
1210 };
1211 ordered_methods_.push_back(method_data);
1212
1213 method_offsets_index_++;
1214 }
1215
1216 return true;
1217 }
1218
1219 OrderedMethodList ReleaseOrderedMethods() {
1220 if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1221 // Sort by the method ordering criteria (in OrderedMethodData).
1222 // Since most methods will have the same ordering criteria,
1223 // we preserve the original insertion order within the same sort order.
1224 std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1225 } else {
1226 // The profile-less behavior is as if every method had 0 hotness
1227 // associated with it.
1228 //
1229 // Since sorting all methods with hotness=0 should give back the same
1230 // order as before, don't do anything.
1231 DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1232 }
1233
1234 return std::move(ordered_methods_);
1235 }
1236
1237 private:
1238 // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1239 // Methods can be inserted more than once in case of duplicated methods.
1240 OrderedMethodList ordered_methods_;
1241};
1242
1243// Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1244class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1245 public:
1246 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1247 size_t offset,
1248 OrderedMethodList ordered_methods)
1249 : LayoutReserveOffsetCodeMethodVisitor(writer,
1250 offset,
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001251 writer->GetCompilerOptions(),
Igor Murashkin545412b2017-08-17 15:26:54 -07001252 std::move(ordered_methods)) {
1253 }
1254
Roland Levillainf73caca2018-08-24 17:19:07 +01001255 bool VisitComplete() override {
Igor Murashkin545412b2017-08-17 15:26:54 -07001256 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1257 if (generate_debug_info_) {
1258 std::vector<debug::MethodDebugInfo> thunk_infos =
1259 relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1260 writer_->method_info_.insert(writer_->method_info_.end(),
1261 std::make_move_iterator(thunk_infos.begin()),
1262 std::make_move_iterator(thunk_infos.end()));
1263 }
1264 return true;
1265 }
1266
Roland Levillainf73caca2018-08-24 17:19:07 +01001267 bool VisitMethod(const OrderedMethodData& method_data) override
Igor Murashkin545412b2017-08-17 15:26:54 -07001268 REQUIRES_SHARED(Locks::mutator_lock_) {
1269 OatClass* oat_class = method_data.oat_class;
1270 CompiledMethod* compiled_method = method_data.compiled_method;
1271 const MethodReference& method_ref = method_data.method_reference;
1272 uint16_t method_offsets_index_ = method_data.method_offsets_index;
1273 size_t class_def_index = method_data.class_def_index;
1274 uint32_t access_flags = method_data.access_flags;
Igor Murashkin545412b2017-08-17 15:26:54 -07001275 bool has_debug_info = method_data.HasDebugInfo();
1276 size_t debug_info_idx = method_data.debug_info_idx;
1277
1278 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1279
1280 // Derived from CompiledMethod.
1281 uint32_t quick_code_offset = 0;
1282
1283 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1284 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1285 uint32_t thumb_offset = compiled_method->CodeDelta();
1286
1287 // Deduplicate code arrays if we are not producing debuggable code.
1288 bool deduped = true;
1289 if (debuggable_) {
1290 quick_code_offset = relative_patcher_->GetOffset(method_ref);
1291 if (quick_code_offset != 0u) {
1292 // Duplicate methods, we want the same code for both of them so that the oat writer puts
1293 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001294 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001295 quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1296 deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001297 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001298 } else {
1299 quick_code_offset = dedupe_map_.GetOrCreate(
1300 compiled_method,
1301 [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1302 deduped = false;
1303 return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1304 });
1305 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001306
Igor Murashkin545412b2017-08-17 15:26:54 -07001307 if (code_size != 0) {
1308 if (relative_patcher_->GetOffset(method_ref) != 0u) {
1309 // TODO: Should this be a hard failure?
1310 LOG(WARNING) << "Multiple definitions of "
1311 << method_ref.dex_file->PrettyMethod(method_ref.index)
1312 << " offsets " << relative_patcher_->GetOffset(method_ref)
1313 << " " << quick_code_offset;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01001314 } else {
Igor Murashkin545412b2017-08-17 15:26:54 -07001315 relative_patcher_->SetOffset(method_ref, quick_code_offset);
1316 }
1317 }
1318
1319 // Update quick method header.
1320 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1321 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Nicolas Geoffray57083762019-03-05 09:24:45 +00001322 uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1323 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1324 // to 0-offset and we need to adjust it by code_offset.
Igor Murashkin545412b2017-08-17 15:26:54 -07001325 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001326 CHECK(!compiled_method->GetQuickCode().empty());
1327 // If the code is compiled, we write the offset of the stack map relative
Nicolas Geoffray57083762019-03-05 09:24:45 +00001328 // to the code.
1329 if (vmap_table_offset != 0u) {
1330 vmap_table_offset += code_offset;
1331 DCHECK_LT(vmap_table_offset, code_offset);
Igor Murashkin545412b2017-08-17 15:26:54 -07001332 }
Nicolas Geoffray57083762019-03-05 09:24:45 +00001333 *method_header = OatQuickMethodHeader(vmap_table_offset, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001334
Igor Murashkin545412b2017-08-17 15:26:54 -07001335 if (!deduped) {
1336 // Update offsets. (Checksum is updated when writing.)
1337 offset_ += sizeof(*method_header); // Method header is prepended before code.
1338 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001339 }
1340
Igor Murashkin545412b2017-08-17 15:26:54 -07001341 // Exclude quickened dex methods (code_size == 0) since they have no native code.
1342 if (generate_debug_info_ && code_size != 0) {
1343 DCHECK(has_debug_info);
David Srbecky88087562018-06-23 22:05:56 +01001344 const uint8_t* code_info = compiled_method->GetVmapTable().data();
1345 DCHECK(code_info != nullptr);
Igor Murashkin545412b2017-08-17 15:26:54 -07001346
Igor Murashkin545412b2017-08-17 15:26:54 -07001347 // Record debug information for this function if we are doing that.
1348 debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
David Srbeckyc684f332018-01-19 17:38:06 +00001349 DCHECK(info.custom_name.empty());
Igor Murashkin545412b2017-08-17 15:26:54 -07001350 info.dex_file = method_ref.dex_file;
1351 info.class_def_index = class_def_index;
1352 info.dex_method_index = method_ref.index;
1353 info.access_flags = access_flags;
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001354 // For intrinsics emitted by codegen, the code has no relation to the original code item.
1355 info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
Igor Murashkin545412b2017-08-17 15:26:54 -07001356 info.isa = compiled_method->GetInstructionSet();
1357 info.deduped = deduped;
1358 info.is_native_debuggable = native_debuggable_;
1359 info.is_optimized = method_header->IsOptimized();
1360 info.is_code_address_text_relative = true;
1361 info.code_address = code_offset - executable_offset_;
1362 info.code_size = code_size;
David Srbecky88087562018-06-23 22:05:56 +01001363 info.frame_size_in_bytes = CodeInfo::DecodeFrameInfo(code_info).FrameSizeInBytes();
1364 info.code_info = code_info;
Igor Murashkin545412b2017-08-17 15:26:54 -07001365 info.cfi = compiled_method->GetCFIInfo();
1366 } else {
1367 DCHECK(!has_debug_info);
1368 }
1369
1370 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1371 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1372 offsets->code_offset_ = quick_code_offset;
1373
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001374 return true;
1375 }
1376
Igor Murashkin545412b2017-08-17 15:26:54 -07001377 size_t GetOffset() const {
1378 return offset_;
1379 }
1380
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001381 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001382 LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1383 size_t offset,
1384 const CompilerOptions& compiler_options,
1385 OrderedMethodList ordered_methods)
1386 : OrderedMethodVisitor(std::move(ordered_methods)),
1387 writer_(writer),
1388 offset_(offset),
Vladimir Marko1b404a82017-09-01 13:35:26 +01001389 relative_patcher_(writer->relative_patcher_),
1390 executable_offset_(writer->oat_header_->GetExecutableOffset()),
1391 debuggable_(compiler_options.GetDebuggable()),
1392 native_debuggable_(compiler_options.GetNativeDebuggable()),
Vladimir Marko8e524ad2018-07-13 10:27:43 +01001393 generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {}
Vladimir Marko1b404a82017-09-01 13:35:26 +01001394
Vladimir Marko20f85592015-03-19 10:07:02 +00001395 struct CodeOffsetsKeyComparator {
1396 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +01001397 // Code is deduplicated by CompilerDriver, compare only data pointers.
1398 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1399 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001400 }
1401 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +01001402 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1403 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001404 }
Vladimir Marko35831e82015-09-11 11:59:18 +01001405 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1406 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +00001407 }
Vladimir Marko92f7f3c2017-10-31 11:38:30 +00001408 if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1409 return rhs->IsIntrinsic();
1410 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001411 return false;
1412 }
1413 };
1414
David Srbecky009e2a62015-04-15 02:46:30 +01001415 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
Igor Murashkin545412b2017-08-17 15:26:54 -07001416 const MethodReference& method_ref,
David Srbecky009e2a62015-04-15 02:46:30 +01001417 uint32_t thumb_offset) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001418 offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
Vladimir Marko0c737df2016-08-01 16:33:16 +01001419 offset_ += CodeAlignmentSize(offset_, *compiled_method);
1420 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
David Srbecky009e2a62015-04-15 02:46:30 +01001421 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1422 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1423 }
1424
Igor Murashkin545412b2017-08-17 15:26:54 -07001425 OatWriter* writer_;
1426
1427 // Offset of the code of the compiled methods.
1428 size_t offset_;
1429
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001430 // Deduplication is already done on a pointer basis by the compiler driver,
1431 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001432 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +01001433
Vladimir Marko1b404a82017-09-01 13:35:26 +01001434 // Cache writer_'s members and compiler options.
Vladimir Markod8dbc8d2017-09-20 13:37:47 +01001435 MultiOatRelativePatcher* relative_patcher_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001436 uint32_t executable_offset_;
David Srbecky009e2a62015-04-15 02:46:30 +01001437 const bool debuggable_;
Vladimir Marko1b404a82017-09-01 13:35:26 +01001438 const bool native_debuggable_;
1439 const bool generate_debug_info_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001440};
1441
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001442class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1443 public:
1444 InitMapMethodVisitor(OatWriter* writer, size_t offset)
David Srbeckyd1606412018-07-31 15:05:14 +01001445 : OatDexMethodVisitor(writer, offset),
1446 dedupe_bit_table_(&writer_->code_info_data_) {
1447 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001448
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001449 bool VisitMethod(size_t class_def_method_index,
1450 const ClassAccessor::Method& method ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001451 override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001452 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001453 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1454
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001455 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001456 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001457 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001458
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001459 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
David Srbeckyb73323c2018-07-15 23:58:44 +01001460 if (map.size() != 0u) {
David Srbeckyb73323c2018-07-15 23:58:44 +01001461 size_t offset = dedupe_code_info_.GetOrCreate(map.data(), [=]() {
David Srbeckyd1606412018-07-31 15:05:14 +01001462 // Deduplicate the inner BitTable<>s within the CodeInfo.
1463 return offset_ + dedupe_bit_table_.Dedupe(map.data());
David Srbeckyb73323c2018-07-15 23:58:44 +01001464 });
Nicolas Geoffray57083762019-03-05 09:24:45 +00001465 // Code offset is not initialized yet, so set the map offset to 0u-offset.
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001466 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
Nicolas Geoffray57083762019-03-05 09:24:45 +00001467 oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 }
1469 ++method_offsets_index_;
1470 }
1471
1472 return true;
1473 }
1474
1475 private:
David Srbeckyb73323c2018-07-15 23:58:44 +01001476 // Deduplicate at CodeInfo level. The value is byte offset within code_info_data_.
1477 // This deduplicates the whole CodeInfo object without going into the inner tables.
1478 // The compiler already deduplicated the pointers but it did not dedupe the tables.
1479 SafeMap<const uint8_t*, size_t> dedupe_code_info_;
1480
David Srbeckyd1606412018-07-31 15:05:14 +01001481 // Deduplicate at BitTable level.
1482 CodeInfo::Deduper dedupe_bit_table_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001483};
1484
1485class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1486 public:
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001487 InitImageMethodVisitor(OatWriter* writer,
1488 size_t offset,
1489 const std::vector<const DexFile*>* dex_files)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001490 : OatDexMethodVisitor(writer, offset),
Vladimir Markoa0431112018-06-25 09:32:54 +01001491 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001492 class_loader_(writer->HasImage() ? writer->image_writer_->GetAppClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001493 dex_files_(dex_files),
1494 class_linker_(Runtime::Current()->GetClassLinker()) {}
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001495
1496 // Handle copied methods here. Copy pointer to quick code from
1497 // an origin method to a copied method only if they are
1498 // in the same oat file. If the origin and the copied methods are
1499 // in different oat files don't touch the copied method.
1500 // References to other oat files are not supported yet.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001501 bool StartClass(const DexFile* dex_file, size_t class_def_index) override
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001502 REQUIRES_SHARED(Locks::mutator_lock_) {
1503 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1504 // Skip classes that are not in the image.
1505 if (!IsImageClass()) {
1506 return true;
1507 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001508 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001509 const dex::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Vladimir Marko38cf60a2018-11-13 16:17:02 +00001510 ObjPtr<mirror::Class> klass =
1511 class_linker_->LookupResolvedType(class_def.class_idx_, dex_cache, class_loader_);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001512 if (klass != nullptr) {
1513 for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1514 // Find origin method. Declaring class and dex_method_idx
1515 // in the copied method should be the same as in the origin
1516 // method.
Vladimir Markoc945e0d2018-07-18 17:26:45 +01001517 ObjPtr<mirror::Class> declaring_class = method.GetDeclaringClass();
Vladimir Markoba118822017-06-12 15:41:56 +01001518 ArtMethod* origin = declaring_class->FindClassMethod(
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001519 declaring_class->GetDexCache(),
1520 method.GetDexMethodIndex(),
1521 pointer_size_);
1522 CHECK(origin != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01001523 CHECK(!origin->IsDirect());
1524 CHECK(origin->GetDeclaringClass() == declaring_class);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001525 if (IsInOatFile(&declaring_class->GetDexFile())) {
1526 const void* code_ptr =
1527 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1528 if (code_ptr == nullptr) {
1529 methods_to_process_.push_back(std::make_pair(&method, origin));
1530 } else {
1531 method.SetEntryPointFromQuickCompiledCodePtrSize(
1532 code_ptr, pointer_size_);
1533 }
1534 }
1535 }
1536 }
1537 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001538 }
1539
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001540 bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001541 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001542 // Skip methods that are not in the image.
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001543 if (!IsImageClass()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001544 return true;
1545 }
1546
Vladimir Marko49b0f452015-12-10 13:49:19 +00001547 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001548 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1549
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001550 OatMethodOffsets offsets(0u);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01001551 if (HasCompiledCode(compiled_method)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001552 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1553 offsets = oat_class->method_offsets_[method_offsets_index_];
1554 ++method_offsets_index_;
1555 }
1556
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001557 Thread* self = Thread::Current();
1558 ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001559 ArtMethod* resolved_method;
Vladimir Markoa0431112018-06-25 09:32:54 +01001560 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Marko38cf60a2018-11-13 16:17:02 +00001561 resolved_method = class_linker_->LookupResolvedMethod(
1562 method.GetIndex(), dex_cache, /*class_loader=*/ nullptr);
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001563 if (resolved_method == nullptr) {
Vladimir Marko38cf60a2018-11-13 16:17:02 +00001564 LOG(FATAL) << "Unexpected failure to look up a method: "
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001565 << dex_file_->PrettyMethod(method.GetIndex(), true);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001566 UNREACHABLE();
1567 }
1568 } else {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001569 // Should already have been resolved by the compiler.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001570 // 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 +01001571 // entrypoint. This is not fatal since we shall use a resolution method.
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001572 resolved_method = class_linker_->LookupResolvedMethod(method.GetIndex(),
1573 dex_cache,
1574 class_loader_);
Andreas Gamped9efea62014-07-21 22:56:08 -07001575 }
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001576 if (resolved_method != nullptr &&
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001577 compiled_method != nullptr &&
1578 compiled_method->GetQuickCode().size() != 0) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001579 resolved_method->SetEntryPointFromQuickCompiledCodePtrSize(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001580 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1581 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001582
1583 return true;
1584 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001585
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001586 // Check whether current class is image class
1587 bool IsImageClass() {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001588 const dex::TypeId& type_id =
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001589 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1590 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001591 return writer_->GetCompilerOptions().IsImageClass(class_descriptor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001592 }
1593
1594 // Check whether specified dex file is in the compiled oat file.
1595 bool IsInOatFile(const DexFile* dex_file) {
1596 return ContainsElement(*dex_files_, dex_file);
1597 }
1598
1599 // Assign a pointer to quick code for copied methods
1600 // not handled in the method StartClass
1601 void Postprocess() {
1602 for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1603 ArtMethod* method = p.first;
1604 ArtMethod* origin = p.second;
1605 const void* code_ptr =
1606 origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1607 if (code_ptr != nullptr) {
1608 method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1609 }
1610 }
1611 }
1612
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001613 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001614 const PointerSize pointer_size_;
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001615 ObjPtr<mirror::ClassLoader> class_loader_;
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03001616 const std::vector<const DexFile*>* dex_files_;
1617 ClassLinker* const class_linker_;
1618 std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001619};
1620
Igor Murashkin545412b2017-08-17 15:26:54 -07001621class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001622 public:
Igor Murashkin545412b2017-08-17 15:26:54 -07001623 WriteCodeMethodVisitor(OatWriter* writer,
1624 OutputStream* out,
1625 const size_t file_offset,
1626 size_t relative_offset,
1627 OrderedMethodList ordered_methods)
1628 : OrderedMethodVisitor(std::move(ordered_methods)),
1629 writer_(writer),
1630 offset_(relative_offset),
1631 dex_file_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +01001632 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001633 class_loader_(writer->HasImage() ? writer->image_writer_->GetAppClassLoader() : nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001634 out_(out),
1635 file_offset_(file_offset),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001636 class_linker_(Runtime::Current()->GetClassLinker()),
Igor Murashkin545412b2017-08-17 15:26:54 -07001637 dex_cache_(nullptr),
1638 no_thread_suspension_("OatWriter patching") {
Vladimir Marko09d09432015-09-08 13:47:48 +01001639 patched_code_.reserve(16 * KB);
Vladimir Markoa0431112018-06-25 09:32:54 +01001640 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001641 // If we're creating the image, the address space must be ready so that we can apply patches.
1642 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +01001643 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001644 }
1645
Roland Levillainf73caca2018-08-24 17:19:07 +01001646 bool VisitStart() override {
Igor Murashkin545412b2017-08-17 15:26:54 -07001647 return true;
Vladimir Markof4da6752014-08-01 19:04:18 +01001648 }
1649
Igor Murashkin545412b2017-08-17 15:26:54 -07001650 void UpdateDexFileAndDexCache(const DexFile* dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001651 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001652 dex_file_ = dex_file;
1653
1654 // Ordered method visiting is only for compiled methods.
1655 DCHECK(writer_->MayHaveCompiledMethods());
1656
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001657 if (writer_->GetCompilerOptions().IsAotCompilationEnabled()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001658 // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1659 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1660 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1661 DCHECK(dex_cache_ != nullptr);
1662 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001663 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001664 }
1665
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001666 bool VisitComplete() override {
Igor Murashkin545412b2017-08-17 15:26:54 -07001667 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1668 if (UNLIKELY(offset_ == 0u)) {
1669 PLOG(ERROR) << "Failed to write final relative call thunks";
1670 return false;
1671 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001672 return true;
1673 }
1674
Roland Levillainf73caca2018-08-24 17:19:07 +01001675 bool VisitMethod(const OrderedMethodData& method_data) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001676 REQUIRES_SHARED(Locks::mutator_lock_) {
Igor Murashkin545412b2017-08-17 15:26:54 -07001677 const MethodReference& method_ref = method_data.method_reference;
1678 UpdateDexFileAndDexCache(method_ref.dex_file);
1679
1680 OatClass* oat_class = method_data.oat_class;
1681 CompiledMethod* compiled_method = method_data.compiled_method;
1682 uint16_t method_offsets_index = method_data.method_offsets_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001683
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001684 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
Mathieu Chartier268764d2016-09-13 12:09:38 -07001685 ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
Igor Murashkin545412b2017-08-17 15:26:54 -07001686 DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001687
Igor Murashkin545412b2017-08-17 15:26:54 -07001688 // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1689 size_t file_offset = file_offset_; // Used by DCHECK_OFFSET_ macro.
1690 OutputStream* out = out_;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001691
Igor Murashkin545412b2017-08-17 15:26:54 -07001692 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1693 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1694
1695 // Deduplicate code arrays.
1696 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1697 if (method_offsets.code_offset_ > offset_) {
1698 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1699 if (offset_ == 0u) {
1700 ReportWriteFailure("relative call thunk", method_ref);
1701 return false;
1702 }
1703 uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1704 if (alignment_size != 0) {
1705 if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1706 ReportWriteFailure("code alignment padding", method_ref);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001707 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001708 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001709 offset_ += alignment_size;
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001710 DCHECK_OFFSET_();
Igor Murashkin545412b2017-08-17 15:26:54 -07001711 }
1712 DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1713 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1714 DCHECK_EQ(method_offsets.code_offset_,
1715 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1716 << dex_file_->PrettyMethod(method_ref.index);
1717 const OatQuickMethodHeader& method_header =
1718 oat_class->method_headers_[method_offsets_index];
1719 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1720 ReportWriteFailure("method header", method_ref);
1721 return false;
1722 }
1723 writer_->size_method_header_ += sizeof(method_header);
1724 offset_ += sizeof(method_header);
1725 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001726
Igor Murashkin545412b2017-08-17 15:26:54 -07001727 if (!compiled_method->GetPatches().empty()) {
1728 patched_code_.assign(quick_code.begin(), quick_code.end());
1729 quick_code = ArrayRef<const uint8_t>(patched_code_);
1730 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1731 uint32_t literal_offset = patch.LiteralOffset();
1732 switch (patch.GetType()) {
Vladimir Marko6fd16062018-06-26 11:02:04 +01001733 case LinkerPatch::Type::kIntrinsicReference: {
1734 uint32_t target_offset = GetTargetIntrinsicReferenceOffset(patch);
1735 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1736 patch,
1737 offset_ + literal_offset,
1738 target_offset);
1739 break;
1740 }
Vladimir Markob066d432018-01-03 13:14:37 +00001741 case LinkerPatch::Type::kDataBimgRelRo: {
1742 uint32_t target_offset =
1743 writer_->data_bimg_rel_ro_start_ +
1744 writer_->data_bimg_rel_ro_entries_.Get(patch.BootImageOffset());
1745 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1746 patch,
1747 offset_ + literal_offset,
1748 target_offset);
1749 break;
1750 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001751 case LinkerPatch::Type::kMethodBssEntry: {
1752 uint32_t target_offset =
1753 writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1754 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1755 patch,
1756 offset_ + literal_offset,
1757 target_offset);
1758 break;
1759 }
1760 case LinkerPatch::Type::kCallRelative: {
1761 // NOTE: Relative calls across oat files are not supported.
1762 uint32_t target_offset = GetTargetOffset(patch);
1763 writer_->relative_patcher_->PatchCall(&patched_code_,
1764 literal_offset,
1765 offset_ + literal_offset,
1766 target_offset);
1767 break;
1768 }
1769 case LinkerPatch::Type::kStringRelative: {
1770 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1771 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1772 patch,
1773 offset_ + literal_offset,
1774 target_offset);
1775 break;
1776 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001777 case LinkerPatch::Type::kStringBssEntry: {
1778 StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1779 uint32_t target_offset =
1780 writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1781 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1782 patch,
1783 offset_ + literal_offset,
1784 target_offset);
1785 break;
1786 }
1787 case LinkerPatch::Type::kTypeRelative: {
1788 uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1789 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1790 patch,
1791 offset_ + literal_offset,
1792 target_offset);
1793 break;
1794 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001795 case LinkerPatch::Type::kTypeBssEntry: {
1796 TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1797 uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1798 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1799 patch,
1800 offset_ + literal_offset,
1801 target_offset);
1802 break;
1803 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001804 case LinkerPatch::Type::kMethodRelative: {
1805 uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1806 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1807 patch,
1808 offset_ + literal_offset,
1809 target_offset);
1810 break;
1811 }
1812 case LinkerPatch::Type::kBakerReadBarrierBranch: {
1813 writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1814 patch,
1815 offset_ + literal_offset);
1816 break;
1817 }
1818 default: {
1819 DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1820 break;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001821 }
1822 }
1823 }
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001824 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001825
1826 if (!out->WriteFully(quick_code.data(), code_size)) {
1827 ReportWriteFailure("method code", method_ref);
1828 return false;
1829 }
1830 writer_->size_code_ += code_size;
1831 offset_ += code_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001832 }
Igor Murashkin545412b2017-08-17 15:26:54 -07001833 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001834
1835 return true;
1836 }
1837
Igor Murashkin545412b2017-08-17 15:26:54 -07001838 size_t GetOffset() const {
1839 return offset_;
1840 }
1841
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001842 private:
Igor Murashkin545412b2017-08-17 15:26:54 -07001843 OatWriter* const writer_;
1844
1845 // Updated in VisitMethod as methods are written out.
1846 size_t offset_;
1847
1848 // Potentially varies with every different VisitMethod.
1849 // Used to determine which DexCache to use when finding ArtMethods.
1850 const DexFile* dex_file_;
1851
1852 // Pointer size we are compiling to.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001853 const PointerSize pointer_size_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001854 // The image writer's classloader, if there is one, else null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001855 ObjPtr<mirror::ClassLoader> class_loader_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001856 // Stream to output file, where the OAT code will be written to.
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001857 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001858 const size_t file_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001859 ClassLinker* const class_linker_;
Vladimir Markocd556b02017-02-03 11:47:34 +00001860 ObjPtr<mirror::DexCache> dex_cache_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001861 std::vector<uint8_t> patched_code_;
Igor Murashkin545412b2017-08-17 15:26:54 -07001862 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001863
Igor Murashkin545412b2017-08-17 15:26:54 -07001864 void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001865 PLOG(ERROR) << "Failed to write " << what << " for "
Igor Murashkin545412b2017-08-17 15:26:54 -07001866 << method_ref.PrettyMethod() << " to " << out_->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001867 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001868
Mathieu Chartiere401d142015-04-22 13:56:20 -07001869 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001870 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001871 MethodReference ref = patch.TargetMethod();
Vladimir Markocd556b02017-02-03 11:47:34 +00001872 ObjPtr<mirror::DexCache> dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001873 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1874 Thread::Current(), *ref.dex_file);
Igor Murashkin545412b2017-08-17 15:26:54 -07001875 ArtMethod* method =
1876 class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001877 CHECK(method != nullptr);
1878 return method;
1879 }
1880
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001881 uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001882 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1883 // If there's no new compiled code, either we're compiling an app and the target method
1884 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001885 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001886 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001887 DCHECK(target != nullptr);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001888 const void* oat_code_offset =
1889 target->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Yi Kong4b22b342018-08-02 14:43:21 -07001890 if (oat_code_offset != nullptr) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001891 DCHECK(!writer_->GetCompilerOptions().IsBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001892 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1893 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1894 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1895 target_offset = PointerToLowMemUInt32(oat_code_offset);
1896 } else {
1897 target_offset = target->IsNative()
1898 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1899 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1900 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001901 }
1902 return target_offset;
1903 }
1904
Vladimir Markocd556b02017-02-03 11:47:34 +00001905 ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001906 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001907 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001908 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001909 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1910 }
1911
Vladimir Marko28e012a2017-12-07 11:22:59 +00001912 ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1913 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001914 DCHECK(writer_->HasImage());
Vladimir Markocd556b02017-02-03 11:47:34 +00001915 ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001916 ObjPtr<mirror::Class> type =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001917 class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001918 CHECK(type != nullptr);
Vladimir Marko28e012a2017-12-07 11:22:59 +00001919 return type;
Vladimir Markof4da6752014-08-01 19:04:18 +01001920 }
1921
Vladimir Marko28e012a2017-12-07 11:22:59 +00001922 ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1923 REQUIRES_SHARED(Locks::mutator_lock_) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001924 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Markoa64b52d2017-12-08 16:27:49 +00001925 ObjPtr<mirror::String> string =
1926 linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001927 DCHECK(string != nullptr);
Vladimir Markoa0431112018-06-25 09:32:54 +01001928 DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001929 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1930 return string;
1931 }
1932
Vladimir Marko6fd16062018-06-26 11:02:04 +01001933 uint32_t GetTargetIntrinsicReferenceOffset(const LinkerPatch& patch)
1934 REQUIRES_SHARED(Locks::mutator_lock_) {
1935 DCHECK(writer_->GetCompilerOptions().IsBootImage());
1936 const void* address =
1937 writer_->image_writer_->GetIntrinsicReferenceAddress(patch.IntrinsicData());
1938 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1939 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1940 // TODO: Clean up offset types. The target offset must be treated as signed.
1941 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(address) - oat_data_begin);
1942 }
1943
Vladimir Marko65979462017-05-19 17:25:12 +01001944 uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001945 DCHECK(writer_->GetCompilerOptions().IsBootImage());
Vladimir Marko65979462017-05-19 17:25:12 +01001946 method = writer_->image_writer_->GetImageMethodAddress(method);
1947 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1948 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1949 // TODO: Clean up offset types. The target offset must be treated as signed.
1950 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1951 }
1952
Vladimir Marko28e012a2017-12-07 11:22:59 +00001953 uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
1954 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001955 DCHECK(writer_->GetCompilerOptions().IsBootImage());
Vladimir Marko28e012a2017-12-07 11:22:59 +00001956 object = writer_->image_writer_->GetImageAddress(object.Ptr());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001957 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1958 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1959 // TODO: Clean up offset types. The target offset must be treated as signed.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001960 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001961 }
1962
Vladimir Markof4da6752014-08-01 19:04:18 +01001963 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001964 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001965 if (writer_->GetCompilerOptions().IsBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001966 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001967 } else {
1968 // NOTE: We're using linker patches for app->boot references when the image can
1969 // be relocated and therefore we need to emit .oat_patches. We're not using this
1970 // for app->app references, so check that the object is in the image space.
1971 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001972 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001973 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001974 uint32_t address = PointerToLowMemUInt32(object);
1975 DCHECK_LE(offset + 4, code->size());
1976 uint8_t* data = &(*code)[offset];
1977 data[0] = address & 0xffu;
1978 data[1] = (address >> 8) & 0xffu;
1979 data[2] = (address >> 16) & 0xffu;
1980 data[3] = (address >> 24) & 0xffu;
1981 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001982};
1983
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001984// Visit all methods from all classes in all dex files with the specified visitor.
1985bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1986 for (const DexFile* dex_file : *dex_files_) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001987 for (ClassAccessor accessor : dex_file->GetClasses()) {
1988 if (UNLIKELY(!visitor->StartClass(dex_file, accessor.GetClassDefIndex()))) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001989 return false;
1990 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07001991 if (MayHaveCompiledMethods()) {
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001992 size_t class_def_method_index = 0u;
1993 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1994 if (!visitor->VisitMethod(class_def_method_index, method)) {
1995 return false;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00001996 }
Mathieu Chartierbee5e2d2018-08-02 11:00:16 -07001997 ++class_def_method_index;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001998 }
1999 }
2000 if (UNLIKELY(!visitor->EndClass())) {
2001 return false;
2002 }
2003 }
2004 }
2005 return true;
2006}
2007
Vladimir Markoa0431112018-06-25 09:32:54 +01002008size_t OatWriter::InitOatHeader(uint32_t num_dex_files,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002009 SafeMap<std::string, std::string>* key_value_store) {
2010 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
Vladimir Markoa0431112018-06-25 09:32:54 +01002011 oat_header_.reset(OatHeader::Create(GetCompilerOptions().GetInstructionSet(),
2012 GetCompilerOptions().GetInstructionSetFeatures(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002013 num_dex_files,
2014 key_value_store));
2015 size_oat_header_ += sizeof(OatHeader);
2016 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002017 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002018}
2019
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002020size_t OatWriter::InitClassOffsets(size_t offset) {
2021 // Reserve space for class offsets in OAT and update class_offsets_offset_.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002022 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002023 DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2024 if (!oat_dex_file.class_offsets_.empty()) {
2025 // Class offsets are required to be 4 byte aligned.
2026 offset = RoundUp(offset, 4u);
2027 oat_dex_file.class_offsets_offset_ = offset;
2028 offset += oat_dex_file.GetClassOffsetsRawSize();
2029 DCHECK_ALIGNED(offset, 4u);
2030 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002031 }
2032 return offset;
2033}
2034
Brian Carlstrom389efb02012-01-11 12:06:26 -08002035size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08002036 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002037 InitOatClassesMethodVisitor visitor(this, offset);
2038 bool success = VisitDexMethods(&visitor);
2039 CHECK(success);
2040 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07002041
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002042 // Update oat_dex_files_.
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002043 auto oat_class_it = oat_class_headers_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002044 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2045 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002046 DCHECK(oat_class_it != oat_class_headers_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00002047 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002048 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002049 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002050 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002051 CHECK(oat_class_it == oat_class_headers_.end());
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002052
2053 return offset;
2054}
2055
2056size_t OatWriter::InitOatMaps(size_t offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002057 if (!MayHaveCompiledMethods()) {
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002058 return offset;
2059 }
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002060 {
2061 InitMapMethodVisitor visitor(this, offset);
2062 bool success = VisitDexMethods(&visitor);
2063 DCHECK(success);
David Srbeckyd1606412018-07-31 15:05:14 +01002064 code_info_data_.shrink_to_fit();
David Srbeckyb73323c2018-07-15 23:58:44 +01002065 offset += code_info_data_.size();
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002066 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002067 return offset;
2068}
2069
Vladimir Markof3c52b42017-11-17 17:32:12 +00002070template <typename GetBssOffset>
2071static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2072 size_t slot_size,
2073 const BitVector& indexes,
2074 GetBssOffset get_bss_offset) {
2075 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2076 size_t number_of_entries = 0u;
2077 bool first_index = true;
2078 for (uint32_t index : indexes.Indexes()) {
2079 uint32_t bss_offset = get_bss_offset(index);
2080 if (first_index || !encoder.TryMerge(index, bss_offset)) {
2081 encoder.Reset(index, bss_offset);
2082 ++number_of_entries;
2083 first_index = false;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002084 }
2085 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002086 DCHECK_NE(number_of_entries, 0u);
2087 return number_of_entries;
2088}
2089
2090template <typename GetBssOffset>
2091static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2092 size_t slot_size,
2093 const BitVector& indexes,
2094 GetBssOffset get_bss_offset) {
2095 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2096 slot_size,
2097 indexes,
2098 get_bss_offset);
2099 return IndexBssMapping::ComputeSize(number_of_entries);
2100}
2101
2102size_t OatWriter::InitIndexBssMappings(size_t offset) {
2103 if (bss_method_entry_references_.empty() &&
2104 bss_type_entry_references_.empty() &&
2105 bss_string_entry_references_.empty()) {
2106 return offset;
2107 }
2108 // If there are any classes, the class offsets allocation aligns the offset
2109 // and we cannot have any index bss mappings without class offsets.
2110 static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2111 DCHECK_ALIGNED(offset, 4u);
2112
2113 size_t number_of_method_dex_files = 0u;
2114 size_t number_of_type_dex_files = 0u;
2115 size_t number_of_string_dex_files = 0u;
2116 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2117 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2118 const DexFile* dex_file = (*dex_files_)[i];
2119 auto method_it = bss_method_entry_references_.find(dex_file);
2120 if (method_it != bss_method_entry_references_.end()) {
2121 const BitVector& method_indexes = method_it->second;
2122 ++number_of_method_dex_files;
2123 oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2124 offset += CalculateIndexBssMappingSize(
2125 dex_file->NumMethodIds(),
2126 static_cast<size_t>(pointer_size),
2127 method_indexes,
2128 [=](uint32_t index) {
2129 return bss_method_entries_.Get({dex_file, index});
2130 });
2131 }
2132
2133 auto type_it = bss_type_entry_references_.find(dex_file);
2134 if (type_it != bss_type_entry_references_.end()) {
2135 const BitVector& type_indexes = type_it->second;
2136 ++number_of_type_dex_files;
2137 oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2138 offset += CalculateIndexBssMappingSize(
2139 dex_file->NumTypeIds(),
2140 sizeof(GcRoot<mirror::Class>),
2141 type_indexes,
2142 [=](uint32_t index) {
2143 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2144 });
2145 }
2146
2147 auto string_it = bss_string_entry_references_.find(dex_file);
2148 if (string_it != bss_string_entry_references_.end()) {
2149 const BitVector& string_indexes = string_it->second;
2150 ++number_of_string_dex_files;
2151 oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2152 offset += CalculateIndexBssMappingSize(
2153 dex_file->NumStringIds(),
2154 sizeof(GcRoot<mirror::String>),
2155 string_indexes,
2156 [=](uint32_t index) {
2157 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2158 });
2159 }
2160 }
2161 // Check that all dex files targeted by bss entries are in `*dex_files_`.
2162 CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2163 CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2164 CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002165 return offset;
2166}
2167
2168size_t OatWriter::InitOatDexFiles(size_t offset) {
2169 // Initialize offsets of oat dex files.
2170 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2171 oat_dex_file.offset_ = offset;
2172 offset += oat_dex_file.SizeOf();
2173 }
2174 return offset;
2175}
2176
Brian Carlstrome24fa612011-09-29 00:53:55 -07002177size_t OatWriter::InitOatCode(size_t offset) {
2178 // calculate the offsets within OatHeader to executable code
2179 size_t old_offset = offset;
2180 // required to be on a new page boundary
2181 offset = RoundUp(offset, kPageSize);
2182 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002183 size_executable_offset_alignment_ = offset - old_offset;
Vladimir Marko1b404a82017-09-01 13:35:26 +01002184 // TODO: Remove unused trampoline offsets from the OatHeader (requires oat version change).
2185 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
2186 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002187 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markoa0431112018-06-25 09:32:54 +01002188 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002189 const bool generate_debug_info = GetCompilerOptions().GenerateAnyDebugInfo();
Vladimir Marko1b404a82017-09-01 13:35:26 +01002190 size_t adjusted_offset = offset;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002191
Vladimir Marko1b404a82017-09-01 13:35:26 +01002192 #define DO_TRAMPOLINE(field, fn_name) \
2193 offset = CompiledCode::AlignCode(offset, instruction_set); \
2194 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
2195 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
2196 (field) = compiler_driver_->Create ## fn_name(); \
2197 if (generate_debug_info) { \
2198 debug::MethodDebugInfo info = {}; \
David Srbeckyc684f332018-01-19 17:38:06 +00002199 info.custom_name = #fn_name; \
Vladimir Marko1b404a82017-09-01 13:35:26 +01002200 info.isa = instruction_set; \
2201 info.is_code_address_text_relative = true; \
2202 /* Use the code offset rather than the `adjusted_offset`. */ \
2203 info.code_address = offset - oat_header_->GetExecutableOffset(); \
2204 info.code_size = (field)->size(); \
2205 method_info_.push_back(std::move(info)); \
2206 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002207 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002208
Ian Rogers848871b2013-08-05 10:56:33 -07002209 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08002210 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07002211 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07002212 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2213 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002214
Ian Rogers848871b2013-08-05 10:56:33 -07002215 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002216 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002217 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08002218 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07002219 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002220 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07002221 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002222 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002223 return offset;
2224}
2225
2226size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002227 if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07002228 if (kOatWriterDebugOatCodeLayout) {
2229 LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2230 << this << "), "
2231 << "compilation is disabled";
2232 }
2233
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002234 return offset;
2235 }
Igor Murashkin545412b2017-08-17 15:26:54 -07002236 bool success = false;
2237
2238 {
2239 ScopedObjectAccess soa(Thread::Current());
2240
2241 LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2242 success = VisitDexMethods(&layout_code_visitor);
2243 DCHECK(success);
2244
2245 LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2246 this,
2247 offset,
2248 layout_code_visitor.ReleaseOrderedMethods());
2249 success = layout_reserve_code_visitor.Visit();
2250 DCHECK(success);
2251 offset = layout_reserve_code_visitor.GetOffset();
2252
2253 // Save the method order because the WriteCodeMethodVisitor will need this
2254 // order again.
2255 DCHECK(ordered_methods_ == nullptr);
2256 ordered_methods_.reset(
2257 new OrderedMethodList(
2258 layout_reserve_code_visitor.ReleaseOrderedMethods()));
2259
2260 if (kOatWriterDebugOatCodeLayout) {
2261 LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2262 for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2263 std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2264 LOG(INFO) << pretty_name
2265 << "@ offset "
2266 << relative_patcher_->GetOffset(ordered_method.method_reference)
2267 << " X hotness "
2268 << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2269 }
2270 }
2271 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002272
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002273 if (HasImage()) {
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002274 ScopedAssertNoThreadSuspension sants("Init image method visitor", Thread::Current());
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002275 InitImageMethodVisitor image_visitor(this, offset, dex_files_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002276 success = VisitDexMethods(&image_visitor);
Artem Udovichenkob3f2b5c2017-01-31 11:49:33 +03002277 image_visitor.Postprocess();
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002278 DCHECK(success);
2279 offset = image_visitor.GetOffset();
Ian Rogers0571d352011-11-03 19:51:38 -07002280 }
Logan Chien8b977d32012-02-21 19:14:55 +08002281
Brian Carlstrome24fa612011-09-29 00:53:55 -07002282 return offset;
2283}
2284
Vladimir Markob066d432018-01-03 13:14:37 +00002285size_t OatWriter::InitDataBimgRelRoLayout(size_t offset) {
2286 DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
2287 if (data_bimg_rel_ro_entries_.empty()) {
2288 // Nothing to put to the .data.bimg.rel.ro section.
2289 return offset;
2290 }
2291
2292 data_bimg_rel_ro_start_ = RoundUp(offset, kPageSize);
2293
2294 for (auto& entry : data_bimg_rel_ro_entries_) {
2295 size_t& entry_offset = entry.second;
2296 entry_offset = data_bimg_rel_ro_size_;
2297 data_bimg_rel_ro_size_ += sizeof(uint32_t);
2298 }
2299
2300 offset = data_bimg_rel_ro_start_ + data_bimg_rel_ro_size_;
2301 return offset;
2302}
2303
Vladimir Markoaad75c62016-10-03 08:46:48 +00002304void OatWriter::InitBssLayout(InstructionSet instruction_set) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002305 {
2306 InitBssLayoutMethodVisitor visitor(this);
2307 bool success = VisitDexMethods(&visitor);
2308 DCHECK(success);
2309 }
2310
2311 DCHECK_EQ(bss_size_, 0u);
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002312 if (bss_method_entries_.empty() &&
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002313 bss_type_entries_.empty() &&
2314 bss_string_entries_.empty()) {
2315 // Nothing to put to the .bss section.
2316 return;
Vladimir Marko1998cd02017-01-13 13:02:58 +00002317 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002318
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002319 PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002320 bss_methods_offset_ = bss_size_;
2321
2322 // Prepare offsets for .bss ArtMethod entries.
2323 for (auto& entry : bss_method_entries_) {
2324 DCHECK_EQ(entry.second, 0u);
2325 entry.second = bss_size_;
2326 bss_size_ += static_cast<size_t>(pointer_size);
2327 }
2328
Vladimir Markoaad75c62016-10-03 08:46:48 +00002329 bss_roots_offset_ = bss_size_;
2330
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002331 // Prepare offsets for .bss Class entries.
2332 for (auto& entry : bss_type_entries_) {
2333 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002334 entry.second = bss_size_;
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002335 bss_size_ += sizeof(GcRoot<mirror::Class>);
2336 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002337 // Prepare offsets for .bss String entries.
2338 for (auto& entry : bss_string_entries_) {
2339 DCHECK_EQ(entry.second, 0u);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002340 entry.second = bss_size_;
Vladimir Markoaad75c62016-10-03 08:46:48 +00002341 bss_size_ += sizeof(GcRoot<mirror::String>);
2342 }
2343}
2344
David Srbeckybc90fd02015-04-22 19:40:27 +01002345bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002346 CHECK(write_state_ == WriteState::kWriteRoData);
2347
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002348 size_t file_offset = oat_data_offset_;
2349 off_t current_offset = out->Seek(0, kSeekCurrent);
2350 if (current_offset == static_cast<off_t>(-1)) {
2351 PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2352 }
2353 DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2354 size_t relative_offset = current_offset - file_offset;
2355
Vladimir Markoe079e212016-05-25 12:49:49 +01002356 // Wrap out to update checksum with each write.
Vladimir Markoc10a0c62018-11-16 11:39:22 +00002357 ChecksumUpdatingOutputStream checksum_updating_out(out, this);
Vladimir Markoe079e212016-05-25 12:49:49 +01002358 out = &checksum_updating_out;
2359
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002360 relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2361 if (relative_offset == 0) {
2362 PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002363 return false;
2364 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002365
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002366 relative_offset = WriteClasses(out, file_offset, relative_offset);
2367 if (relative_offset == 0) {
2368 PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002369 return false;
2370 }
2371
Vladimir Markof3c52b42017-11-17 17:32:12 +00002372 relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002373 if (relative_offset == 0) {
2374 PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002375 return false;
2376 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002377
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002378 relative_offset = WriteMaps(out, file_offset, relative_offset);
2379 if (relative_offset == 0) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002380 PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2381 return false;
2382 }
2383
2384 relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2385 if (relative_offset == 0) {
2386 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002387 return false;
2388 }
2389
David Srbeckybc90fd02015-04-22 19:40:27 +01002390 // Write padding.
2391 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2392 relative_offset += size_executable_offset_alignment_;
2393 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2394 size_t expected_file_offset = file_offset + relative_offset;
2395 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2396 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2397 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
Andreas Gampe8351aac2018-09-10 12:37:49 -07002398 return false;
David Srbeckybc90fd02015-04-22 19:40:27 +01002399 }
2400 DCHECK_OFFSET();
2401
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002402 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01002403 return true;
2404}
2405
Mathieu Chartier210531f2018-01-12 10:15:51 -08002406class OatWriter::WriteQuickeningInfoMethodVisitor {
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002407 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002408 WriteQuickeningInfoMethodVisitor(OatWriter* writer, OutputStream* out)
2409 : writer_(writer),
2410 out_(out) {}
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002411
Mathieu Chartier210531f2018-01-12 10:15:51 -08002412 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002413 // Map of offsets for quicken info related to method indices.
2414 SafeMap<const uint8_t*, uint32_t> offset_map;
2415 // Use method index order to minimize the encoded size of the offset table.
Mathieu Chartier210531f2018-01-12 10:15:51 -08002416 for (const DexFile* dex_file : dex_files) {
2417 std::vector<uint32_t>* const offsets =
2418 &quicken_info_offset_indices_.Put(dex_file, std::vector<uint32_t>())->second;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002419 for (uint32_t method_idx = 0; method_idx < dex_file->NumMethodIds(); ++method_idx) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002420 uint32_t offset = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002421 MethodReference method_ref(dex_file, method_idx);
2422 CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(method_ref);
2423 if (compiled_method != nullptr && HasQuickeningInfo(compiled_method)) {
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002424 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Mathieu Chartier210531f2018-01-12 10:15:51 -08002425
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002426 // Record each index if required. written_bytes_ is the offset from the start of the
2427 // quicken info data.
2428 // May be already inserted for deduplicate items.
2429 // Add offset of one to make sure 0 represents unused.
2430 auto pair = offset_map.emplace(map.data(), written_bytes_ + 1);
2431 offset = pair.first->second;
2432 // Write out the map if it's not already written.
2433 if (pair.second) {
2434 const uint32_t length = map.size() * sizeof(map.front());
2435 if (!out_->WriteFully(map.data(), length)) {
2436 PLOG(ERROR) << "Failed to write quickening info for " << method_ref.PrettyMethod()
2437 << " to " << out_->GetLocation();
2438 return false;
2439 }
2440 written_bytes_ += length;
2441 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002442 }
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002443 offsets->push_back(offset);
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002444 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002445 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002446 return true;
2447 }
2448
2449 size_t GetNumberOfWrittenBytes() const {
2450 return written_bytes_;
2451 }
2452
Mathieu Chartier210531f2018-01-12 10:15:51 -08002453 SafeMap<const DexFile*, std::vector<uint32_t>>& GetQuickenInfoOffsetIndicies() {
2454 return quicken_info_offset_indices_;
2455 }
2456
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002457 private:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002458 OatWriter* const writer_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002459 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002460 size_t written_bytes_ = 0u;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002461 SafeMap<const DexFile*, std::vector<uint32_t>> quicken_info_offset_indices_;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002462};
2463
Mathieu Chartier210531f2018-01-12 10:15:51 -08002464class OatWriter::WriteQuickeningInfoOffsetsMethodVisitor {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002465 public:
Mathieu Chartier210531f2018-01-12 10:15:51 -08002466 WriteQuickeningInfoOffsetsMethodVisitor(
2467 OutputStream* out,
2468 uint32_t start_offset,
2469 SafeMap<const DexFile*, std::vector<uint32_t>>* quicken_info_offset_indices,
2470 std::vector<uint32_t>* out_table_offsets)
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002471 : out_(out),
Mathieu Chartier210531f2018-01-12 10:15:51 -08002472 start_offset_(start_offset),
2473 quicken_info_offset_indices_(quicken_info_offset_indices),
2474 out_table_offsets_(out_table_offsets) {}
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002475
Mathieu Chartier210531f2018-01-12 10:15:51 -08002476 bool VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002477 for (const DexFile* dex_file : dex_files) {
Mathieu Chartier210531f2018-01-12 10:15:51 -08002478 auto it = quicken_info_offset_indices_->find(dex_file);
2479 DCHECK(it != quicken_info_offset_indices_->end()) << "Failed to find dex file "
2480 << dex_file->GetLocation();
2481 const std::vector<uint32_t>* const offsets = &it->second;
2482
2483 const uint32_t current_offset = start_offset_ + written_bytes_;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002484 CHECK_ALIGNED_PARAM(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002485
2486 // Generate and write the data.
2487 std::vector<uint8_t> table_data;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002488 CompactOffsetTable::Build(*offsets, &table_data);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002489
2490 // Store the offset since we need to put those after the dex file. Table offsets are relative
2491 // to the start of the quicken info section.
2492 out_table_offsets_->push_back(current_offset);
2493
2494 const uint32_t length = table_data.size() * sizeof(table_data.front());
2495 if (!out_->WriteFully(table_data.data(), length)) {
2496 PLOG(ERROR) << "Failed to write quickening offset table for " << dex_file->GetLocation()
2497 << " to " << out_->GetLocation();
2498 return false;
2499 }
2500 written_bytes_ += length;
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002501 }
2502 return true;
2503 }
2504
2505 size_t GetNumberOfWrittenBytes() const {
2506 return written_bytes_;
2507 }
2508
2509 private:
2510 OutputStream* const out_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002511 const uint32_t start_offset_;
2512 size_t written_bytes_ = 0u;
2513 // Maps containing the offsets for the tables.
2514 SafeMap<const DexFile*, std::vector<uint32_t>>* const quicken_info_offset_indices_;
2515 std::vector<uint32_t>* const out_table_offsets_;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002516};
2517
2518bool OatWriter::WriteQuickeningInfo(OutputStream* vdex_out) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08002519 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00002520 // Nothing to write. Leave `vdex_size_` untouched and unaligned.
2521 vdex_quickening_info_offset_ = vdex_size_;
2522 size_quickening_info_alignment_ = 0;
2523 return true;
2524 }
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002525 size_t initial_offset = vdex_size_;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002526 // Make sure the table is properly aligned.
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002527 size_t start_offset = RoundUp(initial_offset, 4u);
2528
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002529 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2530 if (actual_offset != static_cast<off_t>(start_offset)) {
2531 PLOG(ERROR) << "Failed to seek to quickening info section. Actual: " << actual_offset
2532 << " Expected: " << start_offset
2533 << " Output: " << vdex_out->GetLocation();
2534 return false;
2535 }
2536
Mathieu Chartier210531f2018-01-12 10:15:51 -08002537 size_t current_offset = start_offset;
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002538 if (GetCompilerOptions().IsQuickeningCompilationEnabled()) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002539 std::vector<uint32_t> dex_files_indices;
Mathieu Chartier210531f2018-01-12 10:15:51 -08002540 WriteQuickeningInfoMethodVisitor write_quicken_info_visitor(this, vdex_out);
2541 if (!write_quicken_info_visitor.VisitDexMethods(*dex_files_)) {
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01002542 PLOG(ERROR) << "Failed to write the vdex quickening info. File: " << vdex_out->GetLocation();
2543 return false;
2544 }
2545
Mathieu Chartier210531f2018-01-12 10:15:51 -08002546 uint32_t quicken_info_offset = write_quicken_info_visitor.GetNumberOfWrittenBytes();
2547 current_offset = current_offset + quicken_info_offset;
2548 uint32_t before_offset = current_offset;
Mathieu Chartier2daa1342018-02-20 16:19:28 -08002549 current_offset = RoundUp(current_offset, CompactOffsetTable::kAlignment);
Mathieu Chartier210531f2018-01-12 10:15:51 -08002550 const size_t extra_bytes = current_offset - before_offset;
2551 quicken_info_offset += extra_bytes;
2552 actual_offset = vdex_out->Seek(current_offset, kSeekSet);
2553 if (actual_offset != static_cast<off_t>(current_offset)) {
2554 PLOG(ERROR) << "Failed to seek to quickening offset table section. Actual: " << actual_offset
2555 << " Expected: " << current_offset
2556 << " Output: " << vdex_out->GetLocation();
2557 return false;
2558 }
2559
2560 std::vector<uint32_t> table_offsets;
2561 WriteQuickeningInfoOffsetsMethodVisitor table_visitor(
2562 vdex_out,
2563 quicken_info_offset,
2564 &write_quicken_info_visitor.GetQuickenInfoOffsetIndicies(),
2565 /*out*/ &table_offsets);
2566 if (!table_visitor.VisitDexMethods(*dex_files_)) {
2567 PLOG(ERROR) << "Failed to write the vdex quickening info. File: "
2568 << vdex_out->GetLocation();
2569 return false;
2570 }
2571
2572 CHECK_EQ(table_offsets.size(), dex_files_->size());
2573
2574 current_offset += table_visitor.GetNumberOfWrittenBytes();
2575
2576 // Store the offset table offset as a preheader for each dex.
2577 size_t index = 0;
2578 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
2579 const off_t desired_offset = oat_dex_file.dex_file_offset_ -
2580 sizeof(VdexFile::QuickeningTableOffsetType);
2581 actual_offset = vdex_out->Seek(desired_offset, kSeekSet);
2582 if (actual_offset != desired_offset) {
2583 PLOG(ERROR) << "Failed to seek to before dex file for writing offset table offset: "
2584 << actual_offset << " Expected: " << desired_offset
2585 << " Output: " << vdex_out->GetLocation();
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002586 return false;
2587 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002588 uint32_t offset = table_offsets[index];
2589 if (!vdex_out->WriteFully(reinterpret_cast<const uint8_t*>(&offset), sizeof(offset))) {
2590 PLOG(ERROR) << "Failed to write verifier deps."
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00002591 << " File: " << vdex_out->GetLocation();
2592 return false;
2593 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002594 ++index;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002595 }
Mathieu Chartier210531f2018-01-12 10:15:51 -08002596 if (!vdex_out->Flush()) {
2597 PLOG(ERROR) << "Failed to flush stream after writing quickening info."
2598 << " File: " << vdex_out->GetLocation();
2599 return false;
2600 }
2601 size_quickening_info_ = current_offset - start_offset;
Nicolas Geoffray60ca9492016-12-20 21:15:00 +00002602 } else {
2603 // We know we did not quicken.
2604 size_quickening_info_ = 0;
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002605 }
2606
David Brazdil93592f52017-12-08 10:53:27 +00002607 if (size_quickening_info_ == 0) {
2608 // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2609 vdex_quickening_info_offset_ = initial_offset;
2610 size_quickening_info_alignment_ = 0;
2611 } else {
2612 vdex_size_ = start_offset + size_quickening_info_;
2613 vdex_quickening_info_offset_ = start_offset;
2614 size_quickening_info_alignment_ = start_offset - initial_offset;
2615 }
2616
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002617 return true;
2618}
2619
David Brazdil5d5a36b2016-09-14 15:34:10 +01002620bool OatWriter::WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps) {
David Brazdil5d5a36b2016-09-14 15:34:10 +01002621 if (verifier_deps == nullptr) {
2622 // Nothing to write. Record the offset, but no need
2623 // for alignment.
2624 vdex_verifier_deps_offset_ = vdex_size_;
2625 return true;
2626 }
2627
2628 size_t initial_offset = vdex_size_;
2629 size_t start_offset = RoundUp(initial_offset, 4u);
2630
2631 vdex_size_ = start_offset;
2632 vdex_verifier_deps_offset_ = vdex_size_;
2633 size_verifier_deps_alignment_ = start_offset - initial_offset;
2634
2635 off_t actual_offset = vdex_out->Seek(start_offset, kSeekSet);
2636 if (actual_offset != static_cast<off_t>(start_offset)) {
2637 PLOG(ERROR) << "Failed to seek to verifier deps section. Actual: " << actual_offset
2638 << " Expected: " << start_offset
2639 << " Output: " << vdex_out->GetLocation();
2640 return false;
2641 }
2642
2643 std::vector<uint8_t> buffer;
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +01002644 verifier_deps->Encode(*dex_files_, &buffer);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002645
2646 if (!vdex_out->WriteFully(buffer.data(), buffer.size())) {
2647 PLOG(ERROR) << "Failed to write verifier deps."
2648 << " File: " << vdex_out->GetLocation();
2649 return false;
2650 }
2651 if (!vdex_out->Flush()) {
2652 PLOG(ERROR) << "Failed to flush stream after writing verifier deps."
2653 << " File: " << vdex_out->GetLocation();
2654 return false;
2655 }
2656
2657 size_verifier_deps_ = buffer.size();
2658 vdex_size_ += size_verifier_deps_;
2659 return true;
2660}
2661
David Srbeckybc90fd02015-04-22 19:40:27 +01002662bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002663 CHECK(write_state_ == WriteState::kWriteText);
2664
Vladimir Markoe079e212016-05-25 12:49:49 +01002665 // Wrap out to update checksum with each write.
Vladimir Markoc10a0c62018-11-16 11:39:22 +00002666 ChecksumUpdatingOutputStream checksum_updating_out(out, this);
Vladimir Markoe079e212016-05-25 12:49:49 +01002667 out = &checksum_updating_out;
2668
Vladimir Marko944da602016-02-19 12:27:55 +00002669 SetMultiOatRelativePatcherAdjustment();
2670
David Srbeckybc90fd02015-04-22 19:40:27 +01002671 const size_t file_offset = oat_data_offset_;
2672 size_t relative_offset = oat_header_->GetExecutableOffset();
2673 DCHECK_OFFSET();
2674
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002675 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002676 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002677 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002678 return false;
2679 }
2680
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002681 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2682 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08002683 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002684 return false;
2685 }
2686
Vladimir Markob066d432018-01-03 13:14:37 +00002687 if (data_bimg_rel_ro_size_ != 0u) {
2688 write_state_ = WriteState::kWriteDataBimgRelRo;
2689 } else {
2690 if (!CheckOatSize(out, file_offset, relative_offset)) {
2691 return false;
2692 }
2693 write_state_ = WriteState::kWriteHeader;
2694 }
2695 return true;
2696}
2697
2698bool OatWriter::WriteDataBimgRelRo(OutputStream* out) {
2699 CHECK(write_state_ == WriteState::kWriteDataBimgRelRo);
2700
2701 // Wrap out to update checksum with each write.
Vladimir Markoc10a0c62018-11-16 11:39:22 +00002702 ChecksumUpdatingOutputStream checksum_updating_out(out, this);
Vladimir Markob066d432018-01-03 13:14:37 +00002703 out = &checksum_updating_out;
2704
2705 const size_t file_offset = oat_data_offset_;
2706 size_t relative_offset = data_bimg_rel_ro_start_;
2707
2708 // Record the padding before the .data.bimg.rel.ro section.
2709 // Do not write anything, this zero-filled part was skipped (Seek()) when starting the section.
2710 size_t code_end = GetOatHeader().GetExecutableOffset() + code_size_;
2711 DCHECK_EQ(RoundUp(code_end, kPageSize), relative_offset);
2712 size_t padding_size = relative_offset - code_end;
2713 DCHECK_EQ(size_data_bimg_rel_ro_alignment_, 0u);
2714 size_data_bimg_rel_ro_alignment_ = padding_size;
2715
2716 relative_offset = WriteDataBimgRelRo(out, file_offset, relative_offset);
2717 if (relative_offset == 0) {
2718 LOG(ERROR) << "Failed to write boot image relocations to " << out->GetLocation();
2719 return false;
2720 }
2721
2722 if (!CheckOatSize(out, file_offset, relative_offset)) {
2723 return false;
2724 }
2725 write_state_ = WriteState::kWriteHeader;
2726 return true;
2727}
2728
2729bool OatWriter::CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002730 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002731 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002732 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2733 return false;
2734 }
2735
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002736 if (kIsDebugBuild) {
2737 uint32_t size_total = 0;
2738 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07002739 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2740 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002741
David Brazdil7b49e6c2016-09-01 11:06:18 +01002742 DO_STAT(size_vdex_header_);
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00002743 DO_STAT(size_vdex_checksums_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002744 DO_STAT(size_dex_file_alignment_);
2745 DO_STAT(size_executable_offset_alignment_);
2746 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002747 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002748 DO_STAT(size_dex_file_);
David Brazdil5d5a36b2016-09-14 15:34:10 +01002749 DO_STAT(size_verifier_deps_);
2750 DO_STAT(size_verifier_deps_alignment_);
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01002751 DO_STAT(size_quickening_info_);
2752 DO_STAT(size_quickening_info_alignment_);
Ian Rogers848871b2013-08-05 10:56:33 -07002753 DO_STAT(size_interpreter_to_interpreter_bridge_);
2754 DO_STAT(size_interpreter_to_compiled_code_bridge_);
2755 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08002756 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07002757 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002758 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07002759 DO_STAT(size_quick_to_interpreter_bridge_);
2760 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002761 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002762 DO_STAT(size_code_);
2763 DO_STAT(size_code_alignment_);
Vladimir Markob066d432018-01-03 13:14:37 +00002764 DO_STAT(size_data_bimg_rel_ro_);
2765 DO_STAT(size_data_bimg_rel_ro_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01002766 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01002767 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002768 DO_STAT(size_vmap_table_);
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002769 DO_STAT(size_method_info_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002770 DO_STAT(size_oat_dex_file_location_size_);
2771 DO_STAT(size_oat_dex_file_location_data_);
2772 DO_STAT(size_oat_dex_file_location_checksum_);
2773 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002774 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002775 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002776 DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2777 DO_STAT(size_oat_dex_file_dex_layout_sections_);
2778 DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002779 DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002780 DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2781 DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002782 DO_STAT(size_oat_lookup_table_alignment_);
2783 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002784 DO_STAT(size_oat_class_offsets_alignment_);
2785 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002786 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002787 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002788 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002789 DO_STAT(size_oat_class_method_offsets_);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002790 DO_STAT(size_method_bss_mappings_);
Vladimir Markof3c52b42017-11-17 17:32:12 +00002791 DO_STAT(size_type_bss_mappings_);
2792 DO_STAT(size_string_bss_mappings_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002793 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002794
David Brazdil7b49e6c2016-09-01 11:06:18 +01002795 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2796
2797 CHECK_EQ(vdex_size_ + oat_size_, size_total);
2798 CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
Ian Rogers4bdbbc82013-06-10 16:02:31 -07002799 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002800
David Brazdil7b49e6c2016-09-01 11:06:18 +01002801 CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2802 CHECK_EQ(oat_size_, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002803
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002804 write_state_ = WriteState::kWriteHeader;
2805 return true;
2806}
2807
Vladimir Marko0ace5632018-12-14 11:11:47 +00002808bool OatWriter::WriteHeader(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002809 CHECK(write_state_ == WriteState::kWriteHeader);
2810
Vladimir Markoc10a0c62018-11-16 11:39:22 +00002811 // Update checksum with header data.
2812 DCHECK_EQ(oat_header_->GetChecksum(), 0u); // For checksum calculation.
2813 const uint8_t* header_begin = reinterpret_cast<const uint8_t*>(oat_header_.get());
2814 const uint8_t* header_end = oat_header_->GetKeyValueStore() + oat_header_->GetKeyValueStoreSize();
2815 uint32_t old_checksum = oat_checksum_;
2816 oat_checksum_ = adler32(old_checksum, header_begin, header_end - header_begin);
2817 oat_header_->SetChecksum(oat_checksum_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002818
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002819 const size_t file_offset = oat_data_offset_;
2820
2821 off_t current_offset = out->Seek(0, kSeekCurrent);
2822 if (current_offset == static_cast<off_t>(-1)) {
2823 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2824 return false;
2825 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002826 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002827 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2828 return false;
2829 }
David Srbeckybc90fd02015-04-22 19:40:27 +01002830 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002831
2832 // Flush all other data before writing the header.
2833 if (!out->Flush()) {
2834 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2835 return false;
2836 }
2837 // Write the header.
2838 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002839 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002840 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2841 return false;
2842 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002843 // Flush the header data.
2844 if (!out->Flush()) {
2845 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01002846 return false;
2847 }
Vladimir Markof4da6752014-08-01 19:04:18 +01002848
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002849 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2850 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2851 return false;
2852 }
2853 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2854
2855 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07002856 return true;
2857}
2858
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002859size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002860 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2861 if (oat_dex_file.class_offsets_offset_ != 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002862 // Class offsets are required to be 4 byte aligned.
2863 if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
2864 size_t padding_size = RoundUp(relative_offset, 4u) - relative_offset;
2865 if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
2866 return 0u;
2867 }
2868 relative_offset += padding_size;
Vladimir Marko919f5532016-01-20 19:13:01 +00002869 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002870 DCHECK_OFFSET();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002871 if (!oat_dex_file.WriteClassOffsets(this, out)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002872 return 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002873 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002874 relative_offset += oat_dex_file.GetClassOffsetsRawSize();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002875 }
2876 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002877 return relative_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002878}
2879
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002880size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002881 const bool may_have_compiled = MayHaveCompiledMethods();
2882 if (may_have_compiled) {
2883 CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
2884 }
2885 for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002886 // If there are any classes, the class offsets allocation aligns the offset.
2887 DCHECK_ALIGNED(relative_offset, 4u);
2888 DCHECK_OFFSET();
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002889 if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002890 return 0u;
Vladimir Marko919f5532016-01-20 19:13:01 +00002891 }
Mathieu Chartier3957bff2017-07-16 13:55:27 -07002892 relative_offset += oat_class_headers_[i].SizeOf();
2893 if (may_have_compiled) {
2894 if (!oat_classes_[i].Write(this, out)) {
2895 return 0u;
2896 }
2897 relative_offset += oat_classes_[i].SizeOf();
2898 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002899 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002900 return relative_offset;
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002901}
2902
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002903size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002904 {
David Srbeckyb73323c2018-07-15 23:58:44 +01002905 if (UNLIKELY(!out->WriteFully(code_info_data_.data(), code_info_data_.size()))) {
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002906 return 0;
2907 }
David Srbeckyb73323c2018-07-15 23:58:44 +01002908 relative_offset += code_info_data_.size();
2909 size_vmap_table_ = code_info_data_.size();
David Srbecky8cd54542018-07-15 23:58:44 +01002910 DCHECK_OFFSET();
Mathieu Chartiercbcedbf2017-03-12 22:24:50 -07002911 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002912
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002913 return relative_offset;
2914}
2915
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002916
Vladimir Markof3c52b42017-11-17 17:32:12 +00002917template <typename GetBssOffset>
2918size_t WriteIndexBssMapping(OutputStream* out,
2919 size_t number_of_indexes,
2920 size_t slot_size,
2921 const BitVector& indexes,
2922 GetBssOffset get_bss_offset) {
2923 // Allocate the IndexBssMapping.
2924 size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
2925 number_of_indexes, slot_size, indexes, get_bss_offset);
2926 size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
2927 DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
2928 std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
2929 IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
2930 mappings->ClearPadding();
2931 // Encode the IndexBssMapping.
2932 IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2933 auto init_it = mappings->begin();
2934 bool first_index = true;
2935 for (uint32_t index : indexes.Indexes()) {
2936 size_t bss_offset = get_bss_offset(index);
2937 if (first_index) {
2938 first_index = false;
2939 encoder.Reset(index, bss_offset);
2940 } else if (!encoder.TryMerge(index, bss_offset)) {
2941 *init_it = encoder.GetEntry();
2942 ++init_it;
2943 encoder.Reset(index, bss_offset);
2944 }
2945 }
2946 // Store the last entry.
2947 *init_it = encoder.GetEntry();
2948 ++init_it;
2949 DCHECK(init_it == mappings->end());
2950
2951 if (!out->WriteFully(storage.get(), mappings_size)) {
2952 return 0u;
2953 }
2954 return mappings_size;
2955}
2956
2957size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
2958 size_t file_offset,
2959 size_t relative_offset) {
2960 TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
2961 if (bss_method_entry_references_.empty() &&
2962 bss_type_entry_references_.empty() &&
2963 bss_string_entry_references_.empty()) {
2964 return relative_offset;
2965 }
2966 // If there are any classes, the class offsets allocation aligns the offset
2967 // and we cannot have method bss mappings without class offsets.
2968 static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
2969 "IndexBssMapping alignment check.");
2970 DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
2971
2972 PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002973 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2974 const DexFile* dex_file = (*dex_files_)[i];
2975 OatDexFile* oat_dex_file = &oat_dex_files_[i];
Vladimir Markof3c52b42017-11-17 17:32:12 +00002976 auto method_it = bss_method_entry_references_.find(dex_file);
2977 if (method_it != bss_method_entry_references_.end()) {
2978 const BitVector& method_indexes = method_it->second;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002979 DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
2980 DCHECK_OFFSET();
Vladimir Markof3c52b42017-11-17 17:32:12 +00002981 size_t method_mappings_size = WriteIndexBssMapping(
2982 out,
2983 dex_file->NumMethodIds(),
2984 static_cast<size_t>(pointer_size),
2985 method_indexes,
2986 [=](uint32_t index) {
2987 return bss_method_entries_.Get({dex_file, index});
2988 });
2989 if (method_mappings_size == 0u) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002990 return 0u;
2991 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002992 size_method_bss_mappings_ += method_mappings_size;
2993 relative_offset += method_mappings_size;
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002994 } else {
2995 DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
2996 }
Vladimir Markof3c52b42017-11-17 17:32:12 +00002997
2998 auto type_it = bss_type_entry_references_.find(dex_file);
2999 if (type_it != bss_type_entry_references_.end()) {
3000 const BitVector& type_indexes = type_it->second;
3001 DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
3002 DCHECK_OFFSET();
3003 size_t type_mappings_size = WriteIndexBssMapping(
3004 out,
3005 dex_file->NumTypeIds(),
3006 sizeof(GcRoot<mirror::Class>),
3007 type_indexes,
3008 [=](uint32_t index) {
3009 return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
3010 });
3011 if (type_mappings_size == 0u) {
3012 return 0u;
3013 }
3014 size_type_bss_mappings_ += type_mappings_size;
3015 relative_offset += type_mappings_size;
3016 } else {
3017 DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
3018 }
3019
3020 auto string_it = bss_string_entry_references_.find(dex_file);
3021 if (string_it != bss_string_entry_references_.end()) {
3022 const BitVector& string_indexes = string_it->second;
3023 DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
3024 DCHECK_OFFSET();
3025 size_t string_mappings_size = WriteIndexBssMapping(
3026 out,
3027 dex_file->NumStringIds(),
3028 sizeof(GcRoot<mirror::String>),
3029 string_indexes,
3030 [=](uint32_t index) {
3031 return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
3032 });
3033 if (string_mappings_size == 0u) {
3034 return 0u;
3035 }
3036 size_string_bss_mappings_ += string_mappings_size;
3037 relative_offset += string_mappings_size;
3038 } else {
3039 DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
3040 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003041 }
3042 return relative_offset;
3043}
3044
3045size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3046 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3047
3048 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3049 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3050 DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3051 DCHECK_OFFSET();
3052
3053 // Write OatDexFile.
3054 if (!oat_dex_file->Write(this, out)) {
3055 return 0u;
3056 }
3057 relative_offset += oat_dex_file->SizeOf();
3058 }
3059
3060 return relative_offset;
3061}
3062
3063size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003064 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markoa0431112018-06-25 09:32:54 +01003065 InstructionSet instruction_set = compiler_options_.GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003066
Ian Rogers848871b2013-08-05 10:56:33 -07003067 #define DO_TRAMPOLINE(field) \
3068 do { \
3069 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
3070 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08003071 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07003072 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01003073 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08003074 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003075 return false; \
3076 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003077 size_ ## field += (field)->size(); \
3078 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07003079 DCHECK_OFFSET(); \
3080 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003081
Ian Rogers848871b2013-08-05 10:56:33 -07003082 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08003083 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07003084 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07003085 DO_TRAMPOLINE(quick_resolution_trampoline_);
3086 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3087 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07003088 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003089 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003090}
3091
Ian Rogers3d504072014-03-01 09:16:49 -08003092size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003093 size_t file_offset,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003094 size_t relative_offset) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +01003095 if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
Igor Murashkin545412b2017-08-17 15:26:54 -07003096 // As with InitOatCodeDexFiles, also skip the writer if
3097 // compilation was disabled.
3098 if (kOatWriterDebugOatCodeLayout) {
3099 LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3100 << this << "), "
3101 << "compilation is disabled";
3102 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07003103
Igor Murashkin545412b2017-08-17 15:26:54 -07003104 return relative_offset;
3105 }
3106 ScopedObjectAccess soa(Thread::Current());
3107 DCHECK(ordered_methods_ != nullptr);
3108 std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3109 std::move(ordered_methods_);
3110 WriteCodeMethodVisitor visitor(this,
3111 out,
3112 file_offset,
3113 relative_offset,
3114 std::move(*ordered_methods_ptr));
3115 if (UNLIKELY(!visitor.Visit())) {
3116 return 0;
3117 }
3118 relative_offset = visitor.GetOffset();
Brian Carlstrom265091e2013-01-30 14:08:26 -08003119
Vladimir Markob163bb72015-03-31 21:49:49 +01003120 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3121 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3122 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3123
Brian Carlstromc50d8e12013-07-23 22:35:16 -07003124 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07003125}
3126
Vladimir Markob066d432018-01-03 13:14:37 +00003127size_t OatWriter::WriteDataBimgRelRo(OutputStream* out,
3128 size_t file_offset,
3129 size_t relative_offset) {
3130 if (data_bimg_rel_ro_entries_.empty()) {
3131 return relative_offset;
3132 }
3133
3134 // Write the entire .data.bimg.rel.ro with a single WriteFully().
3135 std::vector<uint32_t> data;
3136 data.reserve(data_bimg_rel_ro_entries_.size());
3137 for (const auto& entry : data_bimg_rel_ro_entries_) {
3138 uint32_t boot_image_offset = entry.first;
3139 data.push_back(boot_image_offset);
3140 }
3141 DCHECK_EQ(data.size(), data_bimg_rel_ro_entries_.size());
3142 DCHECK_OFFSET();
3143 if (!out->WriteFully(data.data(), data.size() * sizeof(data[0]))) {
3144 PLOG(ERROR) << "Failed to write .data.bimg.rel.ro in " << out->GetLocation();
3145 return 0u;
3146 }
3147 DCHECK_EQ(size_data_bimg_rel_ro_, 0u);
3148 size_data_bimg_rel_ro_ = data.size() * sizeof(data[0]);
3149 relative_offset += size_data_bimg_rel_ro_;
3150 return relative_offset;
3151}
3152
Vladimir Marko944da602016-02-19 12:27:55 +00003153bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00003154 // Get the elf file offset of the oat file.
3155 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3156 if (raw_file_offset == static_cast<off_t>(-1)) {
3157 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3158 return false;
3159 }
3160 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3161 return true;
3162}
3163
Mathieu Chartier792111c2018-02-15 13:02:15 -08003164bool OatWriter::WriteDexFiles(OutputStream* out,
3165 File* file,
3166 bool update_input_vdex,
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003167 CopyOption copy_dex_files) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003168 TimingLogger::ScopedTiming split("Write Dex files", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003169
Mathieu Chartier792111c2018-02-15 13:02:15 -08003170 // If extraction is enabled, only do it if not all the dex files are aligned and uncompressed.
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003171 if (copy_dex_files == CopyOption::kOnlyIfCompressed) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003172 extract_dex_files_into_vdex_ = false;
3173 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3174 if (!oat_dex_file.source_.IsZipEntry()) {
3175 extract_dex_files_into_vdex_ = true;
3176 break;
3177 }
3178 ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
David Sehr79e26072018-04-06 17:58:50 -07003179 if (!entry->IsUncompressed() || !entry->IsAlignedTo(alignof(DexFile::Header))) {
Mathieu Chartier792111c2018-02-15 13:02:15 -08003180 extract_dex_files_into_vdex_ = true;
3181 break;
3182 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003183 }
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003184 } else if (copy_dex_files == CopyOption::kAlways) {
3185 extract_dex_files_into_vdex_ = true;
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003186 } else {
Nicolas Geoffray66ff8a82018-02-28 13:27:55 +00003187 DCHECK(copy_dex_files == CopyOption::kNever);
Mathieu Chartier026dc0b2018-02-20 10:07:51 -08003188 extract_dex_files_into_vdex_ = false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003189 }
3190
Mathieu Chartier792111c2018-02-15 13:02:15 -08003191 if (extract_dex_files_into_vdex_) {
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003192 // Add the dex section header.
3193 vdex_size_ += sizeof(VdexFile::DexSectionHeader);
3194 vdex_dex_files_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003195 // Write dex files.
3196 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3197 if (!WriteDexFile(out, file, &oat_dex_file, update_input_vdex)) {
3198 return false;
3199 }
3200 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003201
3202 // Write shared dex file data section and fix up the dex file headers.
3203 vdex_dex_shared_data_offset_ = vdex_size_;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003204 uint32_t shared_data_size = 0u;
3205
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003206 if (dex_container_ != nullptr) {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003207 CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003208 DexContainer::Section* const section = dex_container_->GetDataSection();
3209 if (section->Size() > 0) {
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003210 CHECK(compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003211 const off_t existing_offset = out->Seek(0, kSeekCurrent);
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003212 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3213 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3214 << existing_offset;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003215 return false;
3216 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003217 shared_data_size = section->Size();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003218 if (!out->WriteFully(section->Begin(), shared_data_size)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003219 PLOG(ERROR) << "Failed to write shared data!";
3220 return false;
3221 }
3222 if (!out->Flush()) {
3223 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003224 return false;
3225 }
3226 // Fix up the dex headers to have correct offsets to the data section.
3227 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3228 // Overwrite the header by reading it, updating the offset, and writing it back out.
3229 DexFile::Header header;
3230 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003231 PLOG(ERROR) << "Failed to read dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003232 return false;
3233 }
Mathieu Chartiercda83be2018-03-01 23:55:55 -08003234 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3235 // Non-compact dex file, probably failed to convert due to duplicate methods.
3236 continue;
3237 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003238 CHECK_GT(vdex_dex_shared_data_offset_, oat_dex_file.dex_file_offset_);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003239 // Offset is from the dex file base.
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003240 header.data_off_ = vdex_dex_shared_data_offset_ - oat_dex_file.dex_file_offset_;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003241 // The size should already be what part of the data buffer may be used by the dex.
3242 CHECK_LE(header.data_size_, shared_data_size);
3243 if (!file->PwriteFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003244 PLOG(ERROR) << "Failed to write dex header for updating";
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003245 return false;
3246 }
3247 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003248 section->Clear();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003249 }
3250 dex_container_.reset();
Mathieu Chartierf1609832018-01-31 03:09:56 -08003251 } else {
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003252 const uint8_t* data_begin = nullptr;
3253 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3254 DexFile::Header header;
3255 if (!file->PreadFully(&header, sizeof(header), oat_dex_file.dex_file_offset_)) {
3256 PLOG(ERROR) << "Failed to read dex header";
3257 return false;
3258 }
3259 if (!CompactDexFile::IsMagicValid(header.magic_)) {
3260 // Non compact dex does not have shared data section.
3261 continue;
3262 }
3263 const uint32_t expected_data_off = vdex_dex_shared_data_offset_ -
3264 oat_dex_file.dex_file_offset_;
3265 if (header.data_off_ != expected_data_off) {
3266 PLOG(ERROR) << "Shared data section offset " << header.data_off_
3267 << " does not match expected value " << expected_data_off;
3268 return false;
3269 }
3270 if (oat_dex_file.source_.IsRawData()) {
3271 // Figure out the start of the shared data section so we can copy it below.
3272 const uint8_t* cur_data_begin = oat_dex_file.source_.GetRawData() + header.data_off_;
3273 if (data_begin != nullptr) {
3274 CHECK_EQ(data_begin, cur_data_begin);
Mathieu Chartierf1609832018-01-31 03:09:56 -08003275 }
Mathieu Chartierd27923c2018-02-08 21:00:03 -08003276 data_begin = cur_data_begin;
3277 }
3278 // The different dex files currently can have different data sizes since
3279 // the dex writer writes them one at a time into the shared section.:w
3280 shared_data_size = std::max(shared_data_size, header.data_size_);
3281 }
3282 // If we are not updating the input vdex, write out the shared data section.
3283 if (!update_input_vdex) {
3284 const off_t existing_offset = out->Seek(0, kSeekCurrent);
3285 if (static_cast<uint32_t>(existing_offset) != vdex_dex_shared_data_offset_) {
3286 PLOG(ERROR) << "Expected offset " << vdex_dex_shared_data_offset_ << " but got "
3287 << existing_offset;
3288 return false;
3289 }
3290 if (!out->WriteFully(data_begin, shared_data_size)) {
3291 PLOG(ERROR) << "Failed to write shared data!";
3292 return false;
3293 }
3294 if (!out->Flush()) {
3295 PLOG(ERROR) << "Failed to flush after writing shared dex section.";
3296 return false;
Mathieu Chartierf1609832018-01-31 03:09:56 -08003297 }
3298 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003299 }
Mathieu Chartierf1609832018-01-31 03:09:56 -08003300 vdex_size_ += shared_data_size;
3301 size_dex_file_ += shared_data_size;
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003302 } else {
Mathieu Chartierf1609832018-01-31 03:09:56 -08003303 vdex_dex_shared_data_offset_ = vdex_size_;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003304 }
3305
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003306 return true;
3307}
3308
3309void OatWriter::CloseSources() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003310 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3311 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
3312 }
3313 zipped_dex_files_.clear();
3314 zip_archives_.clear();
3315 raw_dex_files_.clear();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003316}
3317
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003318bool OatWriter::WriteDexFile(OutputStream* out,
3319 File* file,
3320 OatDexFile* oat_dex_file,
3321 bool update_input_vdex) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003322 if (!SeekToDexFile(out, file, oat_dex_file)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003323 return false;
3324 }
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003325 // update_input_vdex disables compact dex and layout.
Mathieu Chartier7c6f6362018-01-14 20:24:38 -08003326 if (profile_compilation_info_ != nullptr ||
3327 compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
3328 CHECK(!update_input_vdex)
3329 << "We should never update the input vdex when doing dexlayout or compact dex";
Jeff Hao608f2ce2016-10-19 11:17:11 -07003330 if (!LayoutAndWriteDexFile(out, oat_dex_file)) {
3331 return false;
3332 }
3333 } else if (oat_dex_file->source_.IsZipEntry()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003334 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003335 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003336 return false;
3337 }
3338 } else if (oat_dex_file->source_.IsRawFile()) {
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003339 DCHECK(!update_input_vdex);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003340 if (!WriteDexFile(out, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003341 return false;
3342 }
3343 } else {
3344 DCHECK(oat_dex_file->source_.IsRawData());
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003345 if (!WriteDexFile(out, oat_dex_file, oat_dex_file->source_.GetRawData(), update_input_vdex)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003346 return false;
3347 }
3348 }
3349
3350 // Update current size and account for the written data.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003351 DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3352 vdex_size_ += oat_dex_file->dex_file_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003353 size_dex_file_ += oat_dex_file->dex_file_size_;
3354 return true;
3355}
3356
3357bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
3358 // Dex files are required to be 4 byte aligned.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003359 size_t initial_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003360 size_t start_offset = RoundUp(initial_offset, 4);
Nicolas Geoffray67169412018-01-12 09:06:14 +00003361 size_dex_file_alignment_ += start_offset - initial_offset;
Mathieu Chartier7a26f942018-01-04 18:23:55 -08003362
Mathieu Chartier210531f2018-01-12 10:15:51 -08003363 // Leave extra room for the quicken offset table offset.
3364 start_offset += sizeof(VdexFile::QuickeningTableOffsetType);
3365 // TODO: Not count the offset as part of alignment.
3366 size_dex_file_alignment_ += sizeof(VdexFile::QuickeningTableOffsetType);
3367
3368 size_t file_offset = start_offset;
3369
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003370 // Seek to the start of the dex file and flush any pending operations in the stream.
3371 // Verify that, after flushing the stream, the file is at the same offset as the stream.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003372 off_t actual_offset = out->Seek(file_offset, kSeekSet);
3373 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003374 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003375 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003376 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3377 return false;
3378 }
3379 if (!out->Flush()) {
3380 PLOG(ERROR) << "Failed to flush before writing dex file."
3381 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3382 return false;
3383 }
3384 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003385 if (actual_offset != static_cast<off_t>(file_offset)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003386 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
David Brazdil7b49e6c2016-09-01 11:06:18 +01003387 << " Expected: " << file_offset
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003388 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3389 return false;
3390 }
3391
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003392 vdex_size_ = start_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003393 oat_dex_file->dex_file_offset_ = start_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003394 return true;
3395}
3396
Jeff Hao608f2ce2016-10-19 11:17:11 -07003397bool OatWriter::LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file) {
3398 TimingLogger::ScopedTiming split("Dex Layout", timings_);
3399 std::string error_msg;
3400 std::string location(oat_dex_file->GetLocation());
3401 std::unique_ptr<const DexFile> dex_file;
David Sehr013fd802018-01-11 22:55:24 -08003402 const ArtDexFileLoader dex_file_loader;
Jeff Hao608f2ce2016-10-19 11:17:11 -07003403 if (oat_dex_file->source_.IsZipEntry()) {
3404 ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003405 MemMap mem_map;
Andreas Gampefb008f42018-04-23 10:01:16 -07003406 {
3407 TimingLogger::ScopedTiming extract("Unzip", timings_);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003408 mem_map = zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg);
Andreas Gampefb008f42018-04-23 10:01:16 -07003409 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003410 if (!mem_map.IsValid()) {
Jeff Hao41b2f532017-03-02 16:36:31 -08003411 LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3412 return false;
3413 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003414 TimingLogger::ScopedTiming extract("Open", timings_);
David Sehr013fd802018-01-11 22:55:24 -08003415 dex_file = dex_file_loader.Open(location,
Andreas Gampefb008f42018-04-23 10:01:16 -07003416 zip_entry->GetCrc32(),
3417 std::move(mem_map),
David Brazdil20c765f2018-10-27 21:45:15 +00003418 /* verify */ true,
Andreas Gampefb008f42018-04-23 10:01:16 -07003419 /* verify_checksum */ true,
3420 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003421 } else if (oat_dex_file->source_.IsRawFile()) {
Jeff Hao608f2ce2016-10-19 11:17:11 -07003422 File* raw_file = oat_dex_file->source_.GetRawFile();
Andreas Gampedfcd82c2018-10-16 20:22:37 -07003423 int dup_fd = DupCloexec(raw_file->Fd());
Jeff Hao68c48f02017-08-24 11:36:24 -07003424 if (dup_fd < 0) {
3425 PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3426 return false;
3427 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003428 TimingLogger::ScopedTiming extract("Open", timings_);
David Brazdil2b9c35b2018-01-12 15:44:43 +00003429 dex_file = dex_file_loader.OpenDex(dup_fd, location,
David Brazdil20c765f2018-10-27 21:45:15 +00003430 /* verify */ true,
David Brazdil2b9c35b2018-01-12 15:44:43 +00003431 /* verify_checksum */ true,
3432 /* mmap_shared */ false,
3433 &error_msg);
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003434 } else {
3435 // The source data is a vdex file.
3436 CHECK(oat_dex_file->source_.IsRawData())
3437 << static_cast<size_t>(oat_dex_file->source_.GetType());
3438 const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3439 // Note: The raw data has already been checked to contain the header
3440 // and all the data that the header specifies as the file size.
3441 DCHECK(raw_dex_file != nullptr);
3442 DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3443 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3444 // Since the source may have had its layout changed, or may be quickened, don't verify it.
David Sehr013fd802018-01-11 22:55:24 -08003445 dex_file = dex_file_loader.Open(raw_dex_file,
3446 header->file_size_,
3447 location,
3448 oat_dex_file->dex_file_location_checksum_,
3449 nullptr,
3450 /* verify */ false,
3451 /* verify_checksum */ false,
3452 &error_msg);
Jeff Hao608f2ce2016-10-19 11:17:11 -07003453 }
Jeff Haode197542017-02-03 10:48:13 -08003454 if (dex_file == nullptr) {
Jeff Haod9df7802017-02-06 16:41:16 -08003455 LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
Jeff Haode197542017-02-03 10:48:13 -08003456 return false;
3457 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003458 Options options;
Mathieu Chartier603ccab2017-10-20 14:34:28 -07003459 options.compact_dex_level_ = compact_dex_level_;
Mathieu Chartier2c4b0842017-12-13 11:49:51 -08003460 options.update_checksum_ = true;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -08003461 DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003462 const uint8_t* dex_src = nullptr;
Andreas Gampefb008f42018-04-23 10:01:16 -07003463 {
3464 TimingLogger::ScopedTiming extract("ProcessDexFile", timings_);
3465 if (dex_layout.ProcessDexFile(location.c_str(),
3466 dex_file.get(),
3467 0,
3468 &dex_container_,
3469 &error_msg)) {
3470 oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3471 // Dex layout can affect the size of the dex file, so we update here what we have set
3472 // when adding the dex file as a source.
3473 const UnalignedDexFileHeader* header =
3474 AsUnalignedDexFileHeader(dex_container_->GetMainSection()->Begin());
3475 oat_dex_file->dex_file_size_ = header->file_size_;
3476 dex_src = dex_container_->GetMainSection()->Begin();
3477 } else {
3478 LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
3479 // Since we failed to convert the dex, just copy the input dex.
3480 dex_src = dex_file->Begin();
3481 }
Mathieu Chartier05f90d12018-02-07 13:47:17 -08003482 }
Andreas Gampefb008f42018-04-23 10:01:16 -07003483 {
3484 TimingLogger::ScopedTiming extract("WriteDexFile", timings_);
3485 if (!WriteDexFile(out, oat_dex_file, dex_src, /* update_input_vdex */ false)) {
3486 return false;
3487 }
Jeff Hao608f2ce2016-10-19 11:17:11 -07003488 }
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08003489 if (dex_container_ != nullptr) {
3490 // Clear the main section in case we write more data into the container.
3491 dex_container_->GetMainSection()->Clear();
3492 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003493 CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
Jeff Hao608f2ce2016-10-19 11:17:11 -07003494 return true;
3495}
3496
David Brazdil7b49e6c2016-09-01 11:06:18 +01003497bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003498 File* file,
3499 OatDexFile* oat_dex_file,
3500 ZipEntry* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003501 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003502 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003503
3504 // Extract the dex file and get the extracted size.
3505 std::string error_msg;
3506 if (!dex_file->ExtractToFile(*file, &error_msg)) {
3507 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3508 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3509 return false;
3510 }
3511 if (file->Flush() != 0) {
3512 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
3513 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3514 return false;
3515 }
3516 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
3517 if (extracted_end == static_cast<off_t>(-1)) {
3518 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
3519 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3520 return false;
3521 }
3522 if (extracted_end < static_cast<off_t>(start_offset)) {
3523 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
3524 << " Start: " << start_offset
3525 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3526 return false;
3527 }
3528 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
3529 if (extracted_size < sizeof(DexFile::Header)) {
3530 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
3531 << extracted_size << " File: " << oat_dex_file->GetLocation();
3532 return false;
3533 }
3534
3535 // Read the dex file header and extract required data to OatDexFile.
3536 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
3537 if (actual_offset != static_cast<off_t>(start_offset)) {
3538 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
3539 << " Expected: " << start_offset
3540 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3541 return false;
3542 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003543 if (extracted_size < oat_dex_file->dex_file_size_) {
3544 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
3545 << " file size from header: " << oat_dex_file->dex_file_size_
3546 << " File: " << oat_dex_file->GetLocation();
3547 return false;
3548 }
3549
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003550 // Seek both file and stream to the end offset.
3551 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3552 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
3553 if (actual_offset != static_cast<off_t>(end_offset)) {
3554 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
3555 << " Expected: " << end_offset
3556 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3557 return false;
3558 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003559 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003560 if (actual_offset != static_cast<off_t>(end_offset)) {
3561 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3562 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3563 return false;
3564 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003565 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003566 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3567 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3568 return false;
3569 }
3570
3571 // If we extracted more than the size specified in the header, truncate the file.
3572 if (extracted_size > oat_dex_file->dex_file_size_) {
3573 if (file->SetLength(end_offset) != 0) {
3574 PLOG(ERROR) << "Failed to truncate excessive dex file length."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003575 << " File: " << oat_dex_file->GetLocation()
3576 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003577 return false;
3578 }
3579 }
3580
3581 return true;
3582}
3583
David Brazdil7b49e6c2016-09-01 11:06:18 +01003584bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003585 File* file,
3586 OatDexFile* oat_dex_file,
3587 File* dex_file) {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003588 size_t start_offset = vdex_size_;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003589 DCHECK_EQ(static_cast<off_t>(start_offset), out->Seek(0, kSeekCurrent));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003590
3591 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
3592 if (input_offset != static_cast<off_t>(0)) {
3593 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
3594 << " Expected: 0"
3595 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3596 return false;
3597 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003598
3599 // Copy the input dex file using sendfile().
3600 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
3601 PLOG(ERROR) << "Failed to copy dex file to oat file."
3602 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3603 return false;
3604 }
3605 if (file->Flush() != 0) {
3606 PLOG(ERROR) << "Failed to flush dex file."
3607 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3608 return false;
3609 }
3610
3611 // Check file position and seek the stream to the end offset.
3612 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
3613 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
3614 if (actual_offset != static_cast<off_t>(end_offset)) {
3615 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
3616 << " Expected: " << end_offset
3617 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3618 return false;
3619 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003620 actual_offset = out->Seek(end_offset, kSeekSet);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003621 if (actual_offset != static_cast<off_t>(end_offset)) {
3622 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
3623 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
3624 return false;
3625 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01003626 if (!out->Flush()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003627 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
3628 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3629 return false;
3630 }
3631
3632 return true;
3633}
3634
David Brazdil7b49e6c2016-09-01 11:06:18 +01003635bool OatWriter::WriteDexFile(OutputStream* out,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003636 OatDexFile* oat_dex_file,
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003637 const uint8_t* dex_file,
3638 bool update_input_vdex) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003639 // Note: The raw data has already been checked to contain the header
3640 // and all the data that the header specifies as the file size.
3641 DCHECK(dex_file != nullptr);
3642 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3643 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
3644
Nicolas Geoffray81f57d12016-12-20 13:17:09 +00003645 if (update_input_vdex) {
3646 // The vdex already contains the dex code, no need to write it again.
3647 } else {
3648 if (!out->WriteFully(dex_file, header->file_size_)) {
3649 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
3650 << " to " << out->GetLocation();
3651 return false;
3652 }
3653 if (!out->Flush()) {
3654 PLOG(ERROR) << "Failed to flush stream after writing dex file."
3655 << " File: " << oat_dex_file->GetLocation();
3656 return false;
3657 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003658 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003659 return true;
3660}
3661
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003662bool OatWriter::OpenDexFiles(
3663 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003664 bool verify,
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003665 /*out*/ std::vector<MemMap>* opened_dex_files_map,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003666 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3667 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3668
3669 if (oat_dex_files_.empty()) {
3670 // Nothing to do.
3671 return true;
3672 }
3673
Mathieu Chartier792111c2018-02-15 13:02:15 -08003674 if (!extract_dex_files_into_vdex_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003675 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003676 std::vector<MemMap> maps;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003677 for (OatDexFile& oat_dex_file : oat_dex_files_) {
3678 std::string error_msg;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003679 maps.emplace_back(oat_dex_file.source_.GetZipEntry()->MapDirectlyOrExtract(
Colin Cross2b41cca2018-11-16 22:43:41 -08003680 oat_dex_file.dex_file_location_data_, "zipped dex", &error_msg, alignof(DexFile)));
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003681 MemMap* map = &maps.back();
3682 if (!map->IsValid()) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003683 LOG(ERROR) << error_msg;
3684 return false;
3685 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003686 // Now, open the dex file.
3687 const ArtDexFileLoader dex_file_loader;
3688 dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
3689 map->Size(),
3690 oat_dex_file.GetLocation(),
3691 oat_dex_file.dex_file_location_checksum_,
3692 /* oat_dex_file */ nullptr,
3693 verify,
3694 verify,
3695 &error_msg));
3696 if (dex_files.back() == nullptr) {
3697 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3698 << " Error: " << error_msg;
3699 return false;
3700 }
3701 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3702 }
3703 *opened_dex_files_map = std::move(maps);
3704 *opened_dex_files = std::move(dex_files);
3705 CloseSources();
3706 return true;
3707 }
3708 // We could have closed the sources at the point of writing the dex files, but to
3709 // make it consistent with the case we're not writing the dex files, we close them now.
3710 CloseSources();
3711
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003712 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003713 size_t length = vdex_size_ - map_offset;
David Brazdil7b49e6c2016-09-01 11:06:18 +01003714
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003715 std::string error_msg;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003716 MemMap dex_files_map = MemMap::MapFile(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003717 length,
3718 PROT_READ | PROT_WRITE,
3719 MAP_SHARED,
3720 file->Fd(),
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00003721 map_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003722 /* low_4gb */ false,
3723 file->GetPath().c_str(),
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003724 &error_msg);
3725 if (!dex_files_map.IsValid()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003726 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3727 << " error: " << error_msg;
3728 return false;
3729 }
David Sehr013fd802018-01-11 22:55:24 -08003730 const ArtDexFileLoader dex_file_loader;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003731 std::vector<std::unique_ptr<const DexFile>> dex_files;
3732 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003733 const uint8_t* raw_dex_file =
Vladimir Markoc34bebf2018-08-16 16:12:49 +01003734 dex_files_map.Begin() + oat_dex_file.dex_file_offset_ - map_offset;
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003735
3736 if (kIsDebugBuild) {
3737 // Sanity check our input files.
3738 // Note that ValidateDexFileHeader() logs error messages.
3739 CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3740 << "Failed to verify written dex file header!"
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003741 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
3742 << " ~ " << static_cast<const void*>(raw_dex_file);
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003743
3744 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3745 CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3746 << "File size mismatch in written dex file header! Expected: "
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003747 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3748 << " Output: " << file->GetPath();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003749 }
3750
3751 // Now, open the dex file.
David Sehr013fd802018-01-11 22:55:24 -08003752 dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
3753 oat_dex_file.dex_file_size_,
3754 oat_dex_file.GetLocation(),
3755 oat_dex_file.dex_file_location_checksum_,
3756 /* oat_dex_file */ nullptr,
3757 verify,
3758 verify,
3759 &error_msg));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003760 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08003761 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3762 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003763 return false;
3764 }
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003765
3766 // Set the class_offsets size now that we have easy access to the DexFile and
David Sehr013fd802018-01-11 22:55:24 -08003767 // it has been verified in dex_file_loader.Open.
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00003768 oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003769 }
3770
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00003771 opened_dex_files_map->push_back(std::move(dex_files_map));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003772 *opened_dex_files = std::move(dex_files);
3773 return true;
3774}
3775
3776bool OatWriter::WriteTypeLookupTables(
David Brazdil7b49e6c2016-09-01 11:06:18 +01003777 OutputStream* oat_rodata,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003778 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3779 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3780
David Brazdil7b49e6c2016-09-01 11:06:18 +01003781 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3782 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3783 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3784 PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3785 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3786 return false;
3787 }
3788
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003789 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3790 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3791 OatDexFile* oat_dex_file = &oat_dex_files_[i];
David Brazdil181e1cc2016-09-01 16:38:47 +00003792 DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3793
3794 if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3795 oat_dex_file->class_offsets_.empty()) {
3796 continue;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003797 }
David Brazdil181e1cc2016-09-01 16:38:47 +00003798
3799 size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3800 if (table_size == 0u) {
3801 continue;
3802 }
3803
3804 // Create the lookup table. When `nullptr` is given as the storage buffer,
David Sehr9aa352e2016-09-15 18:13:52 -07003805 // TypeLookupTable allocates its own and OatDexFile takes ownership.
Mathieu Chartier1b868492016-11-16 16:22:37 -08003806 const DexFile& dex_file = *opened_dex_files[i];
3807 {
Vladimir Markoea341d22018-05-11 10:33:37 +01003808 TypeLookupTable type_lookup_table = TypeLookupTable::Create(dex_file);
Mathieu Chartier1b868492016-11-16 16:22:37 -08003809 type_lookup_table_oat_dex_files_.push_back(
3810 std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3811 dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3812 }
Vladimir Markoea341d22018-05-11 10:33:37 +01003813 const TypeLookupTable& table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
3814 DCHECK(table.Valid());
David Brazdil181e1cc2016-09-01 16:38:47 +00003815
3816 // Type tables are required to be 4 byte aligned.
David Brazdil7b49e6c2016-09-01 11:06:18 +01003817 size_t initial_offset = oat_size_;
3818 size_t rodata_offset = RoundUp(initial_offset, 4);
3819 size_t padding_size = rodata_offset - initial_offset;
David Brazdil181e1cc2016-09-01 16:38:47 +00003820
3821 if (padding_size != 0u) {
3822 std::vector<uint8_t> buffer(padding_size, 0u);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003823 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003824 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3825 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003826 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003827 return false;
3828 }
3829 }
3830
3831 DCHECK_EQ(oat_data_offset_ + rodata_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +01003832 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
Vladimir Markoea341d22018-05-11 10:33:37 +01003833 DCHECK_EQ(table_size, table.RawDataLength());
David Brazdil181e1cc2016-09-01 16:38:47 +00003834
Vladimir Markoea341d22018-05-11 10:33:37 +01003835 if (!oat_rodata->WriteFully(table.RawData(), table_size)) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003836 PLOG(ERROR) << "Failed to write lookup table."
3837 << " File: " << oat_dex_file->GetLocation()
David Brazdil7b49e6c2016-09-01 11:06:18 +01003838 << " Output: " << oat_rodata->GetLocation();
David Brazdil181e1cc2016-09-01 16:38:47 +00003839 return false;
3840 }
3841
3842 oat_dex_file->lookup_table_offset_ = rodata_offset;
3843
David Brazdil7b49e6c2016-09-01 11:06:18 +01003844 oat_size_ += padding_size + table_size;
David Brazdil181e1cc2016-09-01 16:38:47 +00003845 size_oat_lookup_table_ += table_size;
3846 size_oat_lookup_table_alignment_ += padding_size;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003847 }
3848
David Brazdil7b49e6c2016-09-01 11:06:18 +01003849 if (!oat_rodata->Flush()) {
David Brazdil181e1cc2016-09-01 16:38:47 +00003850 PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
David Brazdil7b49e6c2016-09-01 11:06:18 +01003851 << " File: " << oat_rodata->GetLocation();
3852 return false;
3853 }
3854
3855 return true;
3856}
3857
Mathieu Chartier120aa282017-08-05 16:03:03 -07003858bool OatWriter::WriteDexLayoutSections(
3859 OutputStream* oat_rodata,
3860 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
3861 TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3862
3863 if (!kWriteDexLayoutInfo) {
3864 return true;;
3865 }
3866
3867 uint32_t expected_offset = oat_data_offset_ + oat_size_;
3868 off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3869 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3870 PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3871 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3872 return false;
3873 }
3874
3875 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3876 size_t rodata_offset = oat_size_;
3877 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3878 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3879 DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3880
3881 // Write dex layout section alignment bytes.
3882 const size_t padding_size =
3883 RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3884 if (padding_size != 0u) {
3885 std::vector<uint8_t> buffer(padding_size, 0u);
3886 if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3887 PLOG(ERROR) << "Failed to write lookup table alignment padding."
3888 << " File: " << oat_dex_file->GetLocation()
3889 << " Output: " << oat_rodata->GetLocation();
3890 return false;
3891 }
3892 size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3893 rodata_offset += padding_size;
3894 }
3895
3896 DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3897 DCHECK_EQ(oat_data_offset_ + rodata_offset,
3898 static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3899 DCHECK(oat_dex_file != nullptr);
3900 if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3901 sizeof(oat_dex_file->dex_sections_layout_))) {
3902 PLOG(ERROR) << "Failed to write dex layout sections."
3903 << " File: " << oat_dex_file->GetLocation()
3904 << " Output: " << oat_rodata->GetLocation();
3905 return false;
3906 }
3907 oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3908 size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3909 rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3910 }
3911 oat_size_ = rodata_offset;
3912
3913 if (!oat_rodata->Flush()) {
3914 PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3915 << " File: " << oat_rodata->GetLocation();
3916 return false;
3917 }
3918
3919 return true;
3920}
3921
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003922bool OatWriter::WriteChecksumsAndVdexHeader(OutputStream* vdex_out) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003923 // Write checksums
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003924 off_t checksums_offset = sizeof(VdexFile::VerifierDepsHeader);
3925 off_t actual_offset = vdex_out->Seek(checksums_offset, kSeekSet);
3926 if (actual_offset != checksums_offset) {
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003927 PLOG(ERROR) << "Failed to seek to the checksum location of vdex file. Actual: " << actual_offset
3928 << " File: " << vdex_out->GetLocation();
3929 return false;
3930 }
3931
3932 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3933 OatDexFile* oat_dex_file = &oat_dex_files_[i];
3934 if (!vdex_out->WriteFully(
3935 &oat_dex_file->dex_file_location_checksum_, sizeof(VdexFile::VdexChecksum))) {
3936 PLOG(ERROR) << "Failed to write dex file location checksum. File: "
3937 << vdex_out->GetLocation();
3938 return false;
3939 }
3940 size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3941 }
3942
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003943 // Maybe write dex section header.
3944 DCHECK_NE(vdex_verifier_deps_offset_, 0u);
3945 DCHECK_NE(vdex_quickening_info_offset_, 0u);
3946
3947 bool has_dex_section = extract_dex_files_into_vdex_;
3948 if (has_dex_section) {
3949 DCHECK_NE(vdex_dex_files_offset_, 0u);
3950 size_t dex_section_size = vdex_dex_shared_data_offset_ - vdex_dex_files_offset_;
3951 size_t dex_shared_data_size = vdex_verifier_deps_offset_ - vdex_dex_shared_data_offset_;
3952 size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
3953
3954 VdexFile::DexSectionHeader dex_section_header(dex_section_size,
3955 dex_shared_data_size,
3956 quickening_info_section_size);
3957 if (!vdex_out->WriteFully(&dex_section_header, sizeof(VdexFile::DexSectionHeader))) {
3958 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
3959 return false;
3960 }
3961 size_vdex_header_ += sizeof(VdexFile::DexSectionHeader);
3962 }
3963
Nicolas Geoffrayf54e5df2016-12-01 10:45:08 +00003964 // Write header.
3965 actual_offset = vdex_out->Seek(0, kSeekSet);
David Brazdil7b49e6c2016-09-01 11:06:18 +01003966 if (actual_offset != 0) {
3967 PLOG(ERROR) << "Failed to seek to the beginning of vdex file. Actual: " << actual_offset
3968 << " File: " << vdex_out->GetLocation();
3969 return false;
3970 }
3971
Nicolas Geoffray4acefd32016-10-24 13:14:58 +01003972 size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
David Brazdil5d5a36b2016-09-14 15:34:10 +01003973
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003974 VdexFile::VerifierDepsHeader deps_header(
3975 oat_dex_files_.size(), verifier_deps_section_size, has_dex_section);
3976 if (!vdex_out->WriteFully(&deps_header, sizeof(VdexFile::VerifierDepsHeader))) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01003977 PLOG(ERROR) << "Failed to write vdex header. File: " << vdex_out->GetLocation();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003978 return false;
3979 }
Nicolas Geoffray3a293552018-03-02 10:52:16 +00003980 size_vdex_header_ += sizeof(VdexFile::VerifierDepsHeader);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003981
David Brazdil5d5a36b2016-09-14 15:34:10 +01003982 if (!vdex_out->Flush()) {
3983 PLOG(ERROR) << "Failed to flush stream after writing to vdex file."
3984 << " File: " << vdex_out->GetLocation();
3985 return false;
3986 }
3987
Vladimir Marko9bdf1082016-01-21 12:15:52 +00003988 return true;
3989}
3990
Vladimir Markof4da6752014-08-01 19:04:18 +01003991bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003992 return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3993}
3994
3995bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
Vladimir Markof4da6752014-08-01 19:04:18 +01003996 static const uint8_t kPadding[] = {
3997 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3998 };
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003999 DCHECK_LE(size, sizeof(kPadding));
4000 if (UNLIKELY(!out->WriteFully(kPadding, size))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01004001 return false;
4002 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004003 *stat += size;
Vladimir Markof4da6752014-08-01 19:04:18 +01004004 return true;
4005}
4006
Vladimir Marko944da602016-02-19 12:27:55 +00004007void OatWriter::SetMultiOatRelativePatcherAdjustment() {
4008 DCHECK(dex_files_ != nullptr);
4009 DCHECK(relative_patcher_ != nullptr);
4010 DCHECK_NE(oat_data_offset_, 0u);
4011 if (image_writer_ != nullptr && !dex_files_->empty()) {
4012 // The oat data begin may not be initialized yet but the oat file offset is ready.
4013 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
4014 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
4015 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01004016 }
4017}
4018
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004019OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
4020 DexFileSource source,
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004021 CreateTypeLookupTable create_type_lookup_table,
4022 uint32_t dex_file_location_checksum,
4023 size_t dex_file_size)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004024 : source_(source),
4025 create_type_lookup_table_(create_type_lookup_table),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004026 dex_file_size_(dex_file_size),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004027 offset_(0),
4028 dex_file_location_size_(strlen(dex_file_location)),
4029 dex_file_location_data_(dex_file_location),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004030 dex_file_location_checksum_(dex_file_location_checksum),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004031 dex_file_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004032 lookup_table_offset_(0u),
Nicolas Geoffray6f73f4a2017-11-23 12:51:47 +00004033 class_offsets_offset_(0u),
Nicolas Geoffray97a042e2017-11-16 10:49:59 +00004034 method_bss_mapping_offset_(0u),
Vladimir Markof3c52b42017-11-17 17:32:12 +00004035 type_bss_mapping_offset_(0u),
4036 string_bss_mapping_offset_(0u),
Nicolas Geoffray715d6722017-11-20 22:28:46 +00004037 dex_sections_layout_offset_(0u),
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004038 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07004039}
4040
4041size_t OatWriter::OatDexFile::SizeOf() const {
4042 return sizeof(dex_file_location_size_)
4043 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08004044 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08004045 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004046 + sizeof(class_offsets_offset_)
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004047 + sizeof(lookup_table_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004048 + sizeof(method_bss_mapping_offset_)
Vladimir Markof3c52b42017-11-17 17:32:12 +00004049 + sizeof(type_bss_mapping_offset_)
4050 + sizeof(string_bss_mapping_offset_)
Mathieu Chartier120aa282017-08-05 16:03:03 -07004051 + sizeof(dex_sections_layout_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004052}
4053
4054bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
4055 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08004056 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004057
Vladimir Markoe079e212016-05-25 12:49:49 +01004058 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004059 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004060 return false;
4061 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004062 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004063
Vladimir Markoe079e212016-05-25 12:49:49 +01004064 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004065 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004066 return false;
4067 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004068 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004069
Vladimir Markoe079e212016-05-25 12:49:49 +01004070 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004071 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004072 return false;
4073 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004074 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004075
Vladimir Markoe079e212016-05-25 12:49:49 +01004076 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004077 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08004078 return false;
4079 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004080 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004081
Vladimir Markoe079e212016-05-25 12:49:49 +01004082 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004083 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
4084 return false;
4085 }
4086 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
4087
Vladimir Markoe079e212016-05-25 12:49:49 +01004088 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03004089 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
4090 return false;
4091 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004092 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004093
Mathieu Chartier120aa282017-08-05 16:03:03 -07004094 if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
4095 PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
4096 return false;
4097 }
4098 oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
4099
Vladimir Marko0eb882b2017-05-15 13:39:18 +01004100 if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
4101 PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
4102 return false;
4103 }
4104 oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
4105
Vladimir Markof3c52b42017-11-17 17:32:12 +00004106 if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
4107 PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
4108 return false;
4109 }
4110 oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
4111
4112 if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
4113 PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
4114 return false;
4115 }
4116 oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4117
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004118 return true;
4119}
4120
4121bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004122 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004123 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4124 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004125 return false;
4126 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00004127 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004128 return true;
4129}
4130
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004131OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004132 uint32_t compiled_methods_with_code,
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004133 uint16_t oat_class_type)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004134 : compiled_methods_(compiled_methods) {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004135 const uint32_t num_methods = compiled_methods.size();
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004136 CHECK_LE(compiled_methods_with_code, num_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07004137
Brian Carlstromba150c32013-08-27 17:31:03 -07004138 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4139
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004140 method_offsets_.resize(compiled_methods_with_code);
4141 method_headers_.resize(compiled_methods_with_code);
Brian Carlstromba150c32013-08-27 17:31:03 -07004142
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004143 uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4144 // We only create this instance if there are at least some compiled.
4145 if (oat_class_type == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00004146 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07004147 method_bitmap_size_ = method_bitmap_->GetSizeOf();
4148 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4149 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4150 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004151 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07004152 method_bitmap_size_ = 0;
4153 }
4154
4155 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01004156 CompiledMethod* compiled_method = compiled_methods_[i];
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004157 if (HasCompiledCode(compiled_method)) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004158 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4159 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004160 if (oat_class_type == kOatClassSomeCompiled) {
Brian Carlstromba150c32013-08-27 17:31:03 -07004161 method_bitmap_->SetBit(i);
4162 }
Nicolas Geoffrayb02ba932017-07-13 15:53:54 +01004163 } else {
4164 oat_method_offsets_offsets_from_oat_class_[i] = 0;
Brian Carlstromba150c32013-08-27 17:31:03 -07004165 }
4166 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07004167}
4168
Brian Carlstrom265091e2013-01-30 14:08:26 -08004169size_t OatWriter::OatClass::SizeOf() const {
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004170 return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
Brian Carlstromba150c32013-08-27 17:31:03 -07004171 + method_bitmap_size_
4172 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07004173}
4174
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004175bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4176 OutputStream* out,
4177 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08004178 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01004179 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004180 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08004181 return false;
4182 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07004183 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004184
Vladimir Markoe079e212016-05-25 12:49:49 +01004185 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004186 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004187 return false;
4188 }
4189 oat_writer->size_oat_class_type_ += sizeof(type_);
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004190 return true;
4191}
Vladimir Marko49b0f452015-12-10 13:49:19 +00004192
Mathieu Chartier3957bff2017-07-16 13:55:27 -07004193bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07004194 if (method_bitmap_size_ != 0) {
Vladimir Markoe079e212016-05-25 12:49:49 +01004195 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08004196 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004197 return false;
4198 }
4199 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00004200
Vladimir Markoe079e212016-05-25 12:49:49 +01004201 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08004202 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07004203 return false;
4204 }
4205 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4206 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004207
Vladimir Markoe079e212016-05-25 12:49:49 +01004208 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08004209 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004210 return false;
4211 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00004212 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07004213 return true;
4214}
4215
David Srbecky32210b92017-12-04 14:39:21 +00004216debug::DebugInfo OatWriter::GetDebugInfo() const {
4217 debug::DebugInfo debug_info{};
4218 debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
David Srbecky96c84462018-02-05 15:42:40 +00004219 if (VdexWillContainDexFiles()) {
David Srbecky25931622018-01-18 22:55:20 +00004220 DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
4221 for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
4222 const DexFile* dex_file = (*dex_files_)[i];
4223 const OatDexFile& oat_dex_file = oat_dex_files_[i];
David Srbecky96c84462018-02-05 15:42:40 +00004224 uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
4225 if (dex_file_offset != 0) {
4226 debug_info.dex_files.emplace(dex_file_offset, dex_file);
4227 }
David Srbecky32210b92017-12-04 14:39:21 +00004228 }
4229 }
4230 return debug_info;
4231}
4232
Vladimir Marko74527972016-11-29 15:57:32 +00004233} // namespace linker
Brian Carlstrome24fa612011-09-29 00:53:55 -07004234} // namespace art