blob: 42320028e5440da536852047aba10382a3357add [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
Vladimir Marko9bdf1082016-01-21 12:15:52 +000019#include <unistd.h>
Elliott Hughesa0e18062012-04-13 15:59:59 -070020#include <zlib.h>
21
Vladimir Markoc74658b2015-03-31 10:26:41 +010022#include "arch/arm64/instruction_set_features_arm64.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070024#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070025#include "base/bit_vector.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000026#include "base/file_magic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070029#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070030#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000031#include "compiled_method.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000032#include "debug/method_debug_info.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000033#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000034#include "dex_file-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000035#include "driver/compiler_driver.h"
36#include "driver/compiler_options.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010037#include "gc/space/image_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/space/space.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030039#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010040#include "image_writer.h"
Vladimir Marko944da602016-02-19 12:27:55 +000041#include "linker/multi_oat_relative_patcher.h"
Vladimir Marko131980f2015-12-03 18:29:23 +000042#include "linker/output_stream.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/array.h"
44#include "mirror/class_loader.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010045#include "mirror/dex_cache-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "mirror/object-inl.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010047#include "oat_quick_method_header.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070048#include "os.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070049#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070050#include "scoped_thread_state_change.h"
Artem Udovichenkod9786b02015-10-14 16:36:55 +030051#include "type_lookup_table.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010052#include "utils/dex_cache_arrays_layout-inl.h"
jeffhaoec014232012-09-05 10:42:25 -070053#include "verifier/method_verifier.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000054#include "zip_archive.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070055
56namespace art {
57
Vladimir Marko9bdf1082016-01-21 12:15:52 +000058namespace { // anonymous namespace
59
60typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
61
62const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
63 return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
64}
65
Vladimir Markoe079e212016-05-25 12:49:49 +010066class ChecksumUpdatingOutputStream : public OutputStream {
67 public:
68 ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
69 : OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
70
71 bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
72 oat_header_->UpdateChecksum(buffer, byte_count);
73 return out_->WriteFully(buffer, byte_count);
74 }
75
76 off_t Seek(off_t offset, Whence whence) OVERRIDE {
77 return out_->Seek(offset, whence);
78 }
79
80 bool Flush() OVERRIDE {
81 return out_->Flush();
82 }
83
84 private:
85 OutputStream* const out_;
86 OatHeader* const oat_header_;
87};
88
Vladimir Marko9bdf1082016-01-21 12:15:52 +000089} // anonymous namespace
90
91// Defines the location of the raw dex file to write.
92class OatWriter::DexFileSource {
93 public:
94 explicit DexFileSource(ZipEntry* zip_entry)
95 : type_(kZipEntry), source_(zip_entry) {
96 DCHECK(source_ != nullptr);
97 }
98
99 explicit DexFileSource(File* raw_file)
100 : type_(kRawFile), source_(raw_file) {
101 DCHECK(source_ != nullptr);
102 }
103
104 explicit DexFileSource(const uint8_t* dex_file)
105 : type_(kRawData), source_(dex_file) {
106 DCHECK(source_ != nullptr);
107 }
108
109 bool IsZipEntry() const { return type_ == kZipEntry; }
110 bool IsRawFile() const { return type_ == kRawFile; }
111 bool IsRawData() const { return type_ == kRawData; }
112
113 ZipEntry* GetZipEntry() const {
114 DCHECK(IsZipEntry());
115 DCHECK(source_ != nullptr);
116 return static_cast<ZipEntry*>(const_cast<void*>(source_));
117 }
118
119 File* GetRawFile() const {
120 DCHECK(IsRawFile());
121 DCHECK(source_ != nullptr);
122 return static_cast<File*>(const_cast<void*>(source_));
123 }
124
125 const uint8_t* GetRawData() const {
126 DCHECK(IsRawData());
127 DCHECK(source_ != nullptr);
128 return static_cast<const uint8_t*>(source_);
129 }
130
131 void Clear() {
132 type_ = kNone;
133 source_ = nullptr;
134 }
135
136 private:
137 enum Type {
138 kNone,
139 kZipEntry,
140 kRawFile,
141 kRawData,
142 };
143
144 Type type_;
145 const void* source_;
146};
147
Vladimir Marko49b0f452015-12-10 13:49:19 +0000148class OatWriter::OatClass {
149 public:
150 OatClass(size_t offset,
151 const dchecked_vector<CompiledMethod*>& compiled_methods,
152 uint32_t num_non_null_compiled_methods,
153 mirror::Class::Status status);
154 OatClass(OatClass&& src) = default;
155 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
156 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
157 size_t SizeOf() const;
158 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
159
160 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
161 return compiled_methods_[class_def_method_index];
162 }
163
164 // Offset of start of OatClass from beginning of OatHeader. It is
165 // used to validate file position when writing.
166 size_t offset_;
167
168 // CompiledMethods for each class_def_method_index, or null if no method is available.
169 dchecked_vector<CompiledMethod*> compiled_methods_;
170
171 // Offset from OatClass::offset_ to the OatMethodOffsets for the
172 // class_def_method_index. If 0, it means the corresponding
173 // CompiledMethod entry in OatClass::compiled_methods_ should be
174 // null and that the OatClass::type_ should be kOatClassBitmap.
175 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
176
177 // Data to write.
178
179 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
180 int16_t status_;
181
182 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
183 uint16_t type_;
184
185 uint32_t method_bitmap_size_;
186
187 // bit vector indexed by ClassDef method index. When
188 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
189 // method has an OatMethodOffsets in methods_offsets_, otherwise
190 // the entry was ommited to save space. If OatClassType::type_ is
191 // not is kOatClassBitmap, the bitmap will be null.
192 std::unique_ptr<BitVector> method_bitmap_;
193
194 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
195 // present in the OatClass. Note that some may be missing if
196 // OatClass::compiled_methods_ contains null values (and
197 // oat_method_offsets_offsets_from_oat_class_ should contain 0
198 // values in this case).
199 dchecked_vector<OatMethodOffsets> method_offsets_;
200 dchecked_vector<OatQuickMethodHeader> method_headers_;
201
202 private:
203 size_t GetMethodOffsetsRawSize() const {
204 return method_offsets_.size() * sizeof(method_offsets_[0]);
205 }
206
207 DISALLOW_COPY_AND_ASSIGN(OatClass);
208};
209
210class OatWriter::OatDexFile {
211 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000212 OatDexFile(const char* dex_file_location,
213 DexFileSource source,
214 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000215 OatDexFile(OatDexFile&& src) = default;
216
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000217 const char* GetLocation() const {
218 return dex_file_location_data_;
219 }
220
221 void ReserveTypeLookupTable(OatWriter* oat_writer);
222 void ReserveClassOffsets(OatWriter* oat_writer);
223
Vladimir Marko49b0f452015-12-10 13:49:19 +0000224 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225 bool Write(OatWriter* oat_writer, OutputStream* out) const;
226 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
227
228 // The source of the dex file.
229 DexFileSource source_;
230
231 // Whether to create the type lookup table.
232 CreateTypeLookupTable create_type_lookup_table_;
233
234 // Dex file size. Initialized when writing the dex file.
235 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000236
237 // Offset of start of OatDexFile from beginning of OatHeader. It is
238 // used to validate file position when writing.
239 size_t offset_;
240
241 // Data to write.
242 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000243 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000244 uint32_t dex_file_location_checksum_;
245 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000246 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000247 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000248
249 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000250 dchecked_vector<uint32_t> class_offsets_;
251
252 private:
253 size_t GetClassOffsetsRawSize() const {
254 return class_offsets_.size() * sizeof(class_offsets_[0]);
255 }
256
257 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
258};
259
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100260#define DCHECK_OFFSET() \
261 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
262 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
263
264#define DCHECK_OFFSET_() \
265 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
266 << "file_offset=" << file_offset << " offset_=" << offset_
267
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000268OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
269 : write_state_(WriteState::kAddingDexFileSources),
270 timings_(timings),
271 raw_dex_files_(),
272 zip_archives_(),
273 zipped_dex_files_(),
274 zipped_dex_file_locations_(),
275 compiler_driver_(nullptr),
276 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800277 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000278 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100279 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000280 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100281 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700282 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700283 size_dex_file_alignment_(0),
284 size_executable_offset_alignment_(0),
285 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700286 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700287 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700288 size_interpreter_to_interpreter_bridge_(0),
289 size_interpreter_to_compiled_code_bridge_(0),
290 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800291 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700292 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700293 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700294 size_quick_to_interpreter_bridge_(0),
295 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100296 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700297 size_code_(0),
298 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100299 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100300 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700301 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700302 size_oat_dex_file_location_size_(0),
303 size_oat_dex_file_location_data_(0),
304 size_oat_dex_file_location_checksum_(0),
305 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000306 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000307 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000308 size_oat_lookup_table_alignment_(0),
309 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000310 size_oat_class_offsets_alignment_(0),
311 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700312 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700313 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700314 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100315 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000316 relative_patcher_(nullptr),
317 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000318}
319
320bool OatWriter::AddDexFileSource(const char* filename,
321 const char* location,
322 CreateTypeLookupTable create_type_lookup_table) {
323 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
324 uint32_t magic;
325 std::string error_msg;
326 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
327 if (fd.get() == -1) {
328 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
329 return false;
330 } else if (IsDexMagic(magic)) {
331 // The file is open for reading, not writing, so it's OK to let the File destructor
332 // close it without checking for explicit Close(), so pass checkUsage = false.
333 raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
334 oat_dex_files_.emplace_back(location,
335 DexFileSource(raw_dex_files_.back().get()),
336 create_type_lookup_table);
337 } else if (IsZipMagic(magic)) {
338 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
339 return false;
340 }
341 } else {
342 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
343 return false;
344 }
345 return true;
346}
347
348// Add dex file source(s) from a zip file specified by a file handle.
349bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
350 const char* location,
351 CreateTypeLookupTable create_type_lookup_table) {
352 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
353 std::string error_msg;
354 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
355 ZipArchive* zip_archive = zip_archives_.back().get();
356 if (zip_archive == nullptr) {
357 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
358 << error_msg;
359 return false;
360 }
361 for (size_t i = 0; ; ++i) {
362 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
363 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
364 if (entry == nullptr) {
365 break;
366 }
367 zipped_dex_files_.push_back(std::move(entry));
368 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
369 const char* full_location = zipped_dex_file_locations_.back().c_str();
370 oat_dex_files_.emplace_back(full_location,
371 DexFileSource(zipped_dex_files_.back().get()),
372 create_type_lookup_table);
373 }
374 if (zipped_dex_file_locations_.empty()) {
375 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
376 return false;
377 }
378 return true;
379}
380
381// Add dex file source from raw memory.
382bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
383 const char* location,
384 uint32_t location_checksum,
385 CreateTypeLookupTable create_type_lookup_table) {
386 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
387 if (data.size() < sizeof(DexFile::Header)) {
388 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
389 << data.size() << " File: " << location;
390 return false;
391 }
392 if (!ValidateDexFileHeader(data.data(), location)) {
393 return false;
394 }
395 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
396 if (data.size() < header->file_size_) {
397 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
398 << " file size from header: " << header->file_size_ << " File: " << location;
399 return false;
400 }
401
402 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
403 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
404 return true;
405}
406
407dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
408 dchecked_vector<const char*> locations;
409 locations.reserve(oat_dex_files_.size());
410 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
411 locations.push_back(oat_dex_file.GetLocation());
412 }
413 return locations;
414}
415
416bool OatWriter::WriteAndOpenDexFiles(
417 OutputStream* rodata,
418 File* file,
419 InstructionSet instruction_set,
420 const InstructionSetFeatures* instruction_set_features,
421 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800422 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000423 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
424 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
425 CHECK(write_state_ == WriteState::kAddingDexFileSources);
426
427 size_t offset = InitOatHeader(instruction_set,
428 instruction_set_features,
429 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
430 key_value_store);
431 offset = InitOatDexFiles(offset);
432 size_ = offset;
433
434 std::unique_ptr<MemMap> dex_files_map;
435 std::vector<std::unique_ptr<const DexFile>> dex_files;
436 if (!WriteDexFiles(rodata, file)) {
437 return false;
438 }
439 // Reserve space for type lookup tables and update type_lookup_table_offset_.
440 for (OatDexFile& oat_dex_file : oat_dex_files_) {
441 oat_dex_file.ReserveTypeLookupTable(this);
442 }
443 size_t size_after_type_lookup_tables = size_;
444 // Reserve space for class offsets and update class_offsets_offset_.
445 for (OatDexFile& oat_dex_file : oat_dex_files_) {
446 oat_dex_file.ReserveClassOffsets(this);
447 }
Vladimir Markoe079e212016-05-25 12:49:49 +0100448 ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
449 if (!WriteOatDexFiles(&checksum_updating_rodata) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000450 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800451 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000452 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
453 return false;
454 }
455
Vladimir Markoe079e212016-05-25 12:49:49 +0100456 // Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
457 // piece would be difficult because we're not using the OutpuStream directly.
458 if (!oat_dex_files_.empty()) {
459 size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
460 oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
461 }
462
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000463 *opened_dex_files_map = std::move(dex_files_map);
464 *opened_dex_files = std::move(dex_files);
465 write_state_ = WriteState::kPrepareLayout;
466 return true;
467}
468
469void OatWriter::PrepareLayout(const CompilerDriver* compiler,
470 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000471 const std::vector<const DexFile*>& dex_files,
472 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000473 CHECK(write_state_ == WriteState::kPrepareLayout);
474
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000475 compiler_driver_ = compiler;
476 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000477 dex_files_ = &dex_files;
478 relative_patcher_ = relative_patcher;
479 SetMultiOatRelativePatcherAdjustment();
480
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000481 if (compiling_boot_image_) {
482 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800483 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100484 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000485 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100486
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000487 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800488 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000489 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800490 offset = InitOatClasses(offset);
491 }
492 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000493 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100494 offset = InitOatMaps(offset);
495 }
496 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800498 offset = InitOatCode(offset);
499 }
500 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000501 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800502 offset = InitOatCodeDexFiles(offset);
503 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700504 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700505
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800506 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100507 // Allocate space for app dex cache arrays in the .bss section.
508 size_t bss_start = RoundUp(size_, kPageSize);
509 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
510 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000511 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100512 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
513 DexCacheArraysLayout layout(pointer_size, dex_file);
514 bss_size_ += layout.Size();
515 }
516 }
517
Brian Carlstrome24fa612011-09-29 00:53:55 -0700518 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800519 if (compiling_boot_image_) {
520 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000521 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800522 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000523
524 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700525}
526
Ian Rogers0571d352011-11-03 19:51:38 -0700527OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700528}
529
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100530class OatWriter::DexMethodVisitor {
531 public:
532 DexMethodVisitor(OatWriter* writer, size_t offset)
533 : writer_(writer),
534 offset_(offset),
535 dex_file_(nullptr),
536 class_def_index_(DexFile::kDexNoIndex) {
537 }
538
539 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
540 DCHECK(dex_file_ == nullptr);
541 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
542 dex_file_ = dex_file;
543 class_def_index_ = class_def_index;
544 return true;
545 }
546
547 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
548
549 virtual bool EndClass() {
550 if (kIsDebugBuild) {
551 dex_file_ = nullptr;
552 class_def_index_ = DexFile::kDexNoIndex;
553 }
554 return true;
555 }
556
557 size_t GetOffset() const {
558 return offset_;
559 }
560
561 protected:
562 virtual ~DexMethodVisitor() { }
563
564 OatWriter* const writer_;
565
566 // The offset is usually advanced for each visited method by the derived class.
567 size_t offset_;
568
569 // The dex file and class def index are set in StartClass().
570 const DexFile* dex_file_;
571 size_t class_def_index_;
572};
573
574class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
575 public:
576 OatDexMethodVisitor(OatWriter* writer, size_t offset)
577 : DexMethodVisitor(writer, offset),
578 oat_class_index_(0u),
579 method_offsets_index_(0u) {
580 }
581
582 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
583 DexMethodVisitor::StartClass(dex_file, class_def_index);
584 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
585 method_offsets_index_ = 0u;
586 return true;
587 }
588
589 bool EndClass() {
590 ++oat_class_index_;
591 return DexMethodVisitor::EndClass();
592 }
593
594 protected:
595 size_t oat_class_index_;
596 size_t method_offsets_index_;
597};
598
599class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
600 public:
601 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
602 : DexMethodVisitor(writer, offset),
603 compiled_methods_(),
604 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000605 size_t num_classes = 0u;
606 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
607 num_classes += oat_dex_file.class_offsets_.size();
608 }
609 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100610 compiled_methods_.reserve(256u);
611 }
612
613 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
614 DexMethodVisitor::StartClass(dex_file, class_def_index);
615 compiled_methods_.clear();
616 num_non_null_compiled_methods_ = 0u;
617 return true;
618 }
619
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300620 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
621 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100622 // Fill in the compiled_methods_ array for methods that have a
623 // CompiledMethod. We track the number of non-null entries in
624 // num_non_null_compiled_methods_ since we only want to allocate
625 // OatMethodOffsets for the compiled methods.
626 uint32_t method_idx = it.GetMemberIndex();
627 CompiledMethod* compiled_method =
628 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
629 compiled_methods_.push_back(compiled_method);
630 if (compiled_method != nullptr) {
631 ++num_non_null_compiled_methods_;
632 }
633 return true;
634 }
635
636 bool EndClass() {
637 ClassReference class_ref(dex_file_, class_def_index_);
638 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
639 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700640 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100641 status = compiled_class->GetStatus();
642 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
643 status = mirror::Class::kStatusError;
644 } else {
645 status = mirror::Class::kStatusNotReady;
646 }
647
Vladimir Marko49b0f452015-12-10 13:49:19 +0000648 writer_->oat_classes_.emplace_back(offset_,
649 compiled_methods_,
650 num_non_null_compiled_methods_,
651 status);
652 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100653 return DexMethodVisitor::EndClass();
654 }
655
656 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000657 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100658 size_t num_non_null_compiled_methods_;
659};
660
661class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
662 public:
663 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100664 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100665 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100666 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100667 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
668 }
669
670 bool EndClass() {
671 OatDexMethodVisitor::EndClass();
672 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100673 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100674 }
675 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100676 }
677
678 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700679 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000680 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100681 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
682
683 if (compiled_method != nullptr) {
684 // Derived from CompiledMethod.
685 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100686
Vladimir Marko35831e82015-09-11 11:59:18 +0100687 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
688 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800689 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800690
David Srbecky009e2a62015-04-15 02:46:30 +0100691 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100692 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800693 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000694 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000695 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
696 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800697 // Duplicate methods, we want the same code for both of them so that the oat writer puts
698 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800699 } else {
700 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100701 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800702 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000703 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100704 quick_code_offset = dedupe_map_.GetOrCreate(
705 compiled_method,
706 [this, &deduped, compiled_method, &it, thumb_offset]() {
707 deduped = false;
708 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
709 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800710 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100711
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100712 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000713 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100714 // TODO: Should this be a hard failure?
715 LOG(WARNING) << "Multiple definitions of "
716 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000717 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
718 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100719 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000720 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100721 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800722 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100723
Elliott Hughes956af0f2014-12-11 14:34:28 -0800724 // Update quick method header.
725 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
726 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800727 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100728 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
729 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100730 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800731 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
732 // to 0-offset and we need to adjust it by code_offset.
733 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100734 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800735 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100736 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800737 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800738 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
739 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
740 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100741 *method_header = OatQuickMethodHeader(vmap_table_offset,
742 frame_size_in_bytes,
743 core_spill_mask,
744 fp_spill_mask,
745 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100746
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000747 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800748 // Update offsets. (Checksum is updated when writing.)
749 offset_ += sizeof(*method_header); // Method header is prepended before code.
750 offset_ += code_size;
751 // Record absolute patch locations.
752 if (!compiled_method->GetPatches().empty()) {
753 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
754 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000755 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100756 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100757 }
758 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100759 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800760 }
Alex Light78382fa2014-06-06 15:45:32 -0700761
David Srbecky91cc06c2016-03-07 16:13:58 +0000762 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000763 // Exclude quickened dex methods (code_size == 0) since they have no native code.
764 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
765 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800766 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000767 debug::MethodDebugInfo info = debug::MethodDebugInfo();
768 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000769 info.dex_file = dex_file_;
770 info.class_def_index = class_def_index_;
771 info.dex_method_index = it.GetMemberIndex();
772 info.access_flags = it.GetMethodAccessFlags();
773 info.code_item = it.GetMethodCodeItem();
774 info.isa = compiled_method->GetInstructionSet();
775 info.deduped = deduped;
776 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
777 info.is_optimized = method_header->IsOptimized();
778 info.is_code_address_text_relative = true;
779 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
780 info.code_size = code_size;
781 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
782 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
783 info.cfi = compiled_method->GetCFIInfo();
784 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100785 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100786
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100787 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
788 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
789 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100790 ++method_offsets_index_;
791 }
792
793 return true;
794 }
795
796 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000797 struct CodeOffsetsKeyComparator {
798 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100799 // Code is deduplicated by CompilerDriver, compare only data pointers.
800 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
801 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000802 }
803 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100804 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
805 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000806 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100807 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
808 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000809 }
810 return false;
811 }
812 };
813
David Srbecky009e2a62015-04-15 02:46:30 +0100814 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
815 const ClassDataItemIterator& it,
816 uint32_t thumb_offset) {
817 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100818 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100819 offset_ = compiled_method->AlignCode(offset_);
820 DCHECK_ALIGNED_PARAM(offset_,
821 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
822 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
823 }
824
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100825 // Deduplication is already done on a pointer basis by the compiler driver,
826 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100827 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100828
David Srbecky009e2a62015-04-15 02:46:30 +0100829 // Cache of compiler's --debuggable option.
830 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100831};
832
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100833class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
834 public:
835 InitMapMethodVisitor(OatWriter* writer, size_t offset)
836 : OatDexMethodVisitor(writer, offset) {
837 }
838
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700839 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700840 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000841 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100842 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
843
844 if (compiled_method != nullptr) {
845 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100846 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100847
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100848 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100849 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100850 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100851 size_t offset = dedupe_map_.GetOrCreate(
852 map.data(),
853 [this, map_size]() {
854 uint32_t new_offset = offset_;
855 offset_ += map_size;
856 return new_offset;
857 });
858 // Code offset is not initialized yet, so set the map offset to 0u-offset.
859 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
860 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100861 }
862 ++method_offsets_index_;
863 }
864
865 return true;
866 }
867
868 private:
869 // Deduplication is already done on a pointer basis by the compiler driver,
870 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100871 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100872};
873
874class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
875 public:
876 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800877 : OatDexMethodVisitor(writer, offset),
878 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100879 }
880
881 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700882 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800883 const DexFile::TypeId& type_id =
884 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
885 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
886 // Skip methods that are not in the image.
887 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
888 return true;
889 }
890
Vladimir Marko49b0f452015-12-10 13:49:19 +0000891 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100892 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
893
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800894 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100895 if (compiled_method != nullptr) {
896 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
897 offsets = oat_class->method_offsets_[method_offsets_index_];
898 ++method_offsets_index_;
899 }
900
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100901 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100902 // Unchecked as we hold mutator_lock_ on entry.
903 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800904 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700905 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
906 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800907 ArtMethod* method;
908 if (writer_->HasBootImage()) {
909 const InvokeType invoke_type = it.GetMethodInvokeType(
910 dex_file_->GetClassDef(class_def_index_));
911 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
912 *dex_file_,
913 it.GetMemberIndex(),
914 dex_cache,
915 ScopedNullHandle<mirror::ClassLoader>(),
916 nullptr,
917 invoke_type);
918 if (method == nullptr) {
919 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
920 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
921 soa.Self()->AssertPendingException();
922 mirror::Throwable* exc = soa.Self()->GetException();
923 std::string dump = exc->Dump();
924 LOG(FATAL) << dump;
925 UNREACHABLE();
926 }
927 } else {
928 // Should already have been resolved by the compiler, just peek into the dex cache.
929 // It may not be resolved if the class failed to verify, in this case, don't set the
930 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
931 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700932 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800933 if (method != nullptr &&
934 compiled_method != nullptr &&
935 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100936 method->SetEntryPointFromQuickCompiledCodePtrSize(
937 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
938 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939
940 return true;
941 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800942
943 protected:
944 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100945};
946
947class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
948 public:
949 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100950 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100951 : OatDexMethodVisitor(writer, relative_offset),
952 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100953 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100954 soa_(Thread::Current()),
955 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100956 class_linker_(Runtime::Current()->GetClassLinker()),
957 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100958 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800959 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100960 // If we're creating the image, the address space must be ready so that we can apply patches.
961 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100962 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100963 }
964
Vladimir Markof4da6752014-08-01 19:04:18 +0100965 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100966 }
967
968 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700969 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100970 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
971 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700972 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000973 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100974 }
975 return true;
976 }
977
Mathieu Chartier90443472015-07-16 20:32:27 -0700978 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100979 bool result = OatDexMethodVisitor::EndClass();
980 if (oat_class_index_ == writer_->oat_classes_.size()) {
981 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000982 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100983 if (UNLIKELY(offset_ == 0u)) {
984 PLOG(ERROR) << "Failed to write final relative call thunks";
985 result = false;
986 }
987 }
988 return result;
989 }
990
991 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700992 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000993 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100994 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
995
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700996 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
997 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700998 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100999 size_t file_offset = file_offset_;
1000 OutputStream* out = out_;
1001
Vladimir Marko35831e82015-09-11 11:59:18 +01001002 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1003 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001004
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001005 // Deduplicate code arrays.
1006 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1007 if (method_offsets.code_offset_ > offset_) {
1008 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1009 if (offset_ == 0u) {
1010 ReportWriteFailure("relative call thunk", it);
1011 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001012 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001013 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1014 uint32_t aligned_code_delta = aligned_offset - offset_;
1015 if (aligned_code_delta != 0) {
1016 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1017 ReportWriteFailure("code alignment padding", it);
1018 return false;
1019 }
1020 offset_ += aligned_code_delta;
1021 DCHECK_OFFSET_();
1022 }
1023 DCHECK_ALIGNED_PARAM(offset_,
1024 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1025 DCHECK_EQ(method_offsets.code_offset_,
1026 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1027 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1028 const OatQuickMethodHeader& method_header =
1029 oat_class->method_headers_[method_offsets_index_];
Vladimir Markoe079e212016-05-25 12:49:49 +01001030 if (!out->WriteFully(&method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001031 ReportWriteFailure("method header", it);
1032 return false;
1033 }
1034 writer_->size_method_header_ += sizeof(method_header);
1035 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001036 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001037
1038 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001039 patched_code_.assign(quick_code.begin(), quick_code.end());
1040 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001041 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001042 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001043 switch (patch.GetType()) {
1044 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001045 // NOTE: Relative calls across oat files are not supported.
1046 uint32_t target_offset = GetTargetOffset(patch);
1047 writer_->relative_patcher_->PatchCall(&patched_code_,
1048 literal_offset,
1049 offset_ + literal_offset,
1050 target_offset);
1051 break;
1052 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001053 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001054 uint32_t target_offset = GetDexCacheOffset(patch);
1055 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1056 patch,
1057 offset_ + literal_offset,
1058 target_offset);
1059 break;
1060 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001061 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001062 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1063 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1064 patch,
1065 offset_ + literal_offset,
1066 target_offset);
1067 break;
1068 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001069 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001070 uint32_t target_offset = GetTargetOffset(patch);
1071 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1072 break;
1073 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001074 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001075 ArtMethod* method = GetTargetMethod(patch);
1076 PatchMethodAddress(&patched_code_, literal_offset, method);
1077 break;
1078 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001079 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001080 mirror::String* string = GetTargetString(patch);
1081 PatchObjectAddress(&patched_code_, literal_offset, string);
1082 break;
1083 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001084 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001085 mirror::Class* type = GetTargetType(patch);
1086 PatchObjectAddress(&patched_code_, literal_offset, type);
1087 break;
1088 }
1089 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001090 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001091 break;
1092 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001093 }
1094 }
1095 }
1096
Vladimir Markoe079e212016-05-25 12:49:49 +01001097 if (!out->WriteFully(quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001098 ReportWriteFailure("method code", it);
1099 return false;
1100 }
1101 writer_->size_code_ += code_size;
1102 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001103 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001104 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001105 ++method_offsets_index_;
1106 }
1107
1108 return true;
1109 }
1110
1111 private:
1112 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001113 const size_t file_offset_;
1114 const ScopedObjectAccess soa_;
1115 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001116 ClassLinker* const class_linker_;
1117 mirror::DexCache* dex_cache_;
1118 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001119
1120 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1121 PLOG(ERROR) << "Failed to write " << what << " for "
1122 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1123 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001124
Mathieu Chartiere401d142015-04-22 13:56:20 -07001125 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001126 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001127 MethodReference ref = patch.TargetMethod();
1128 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001129 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1130 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001131 ArtMethod* method = dex_cache->GetResolvedMethod(
1132 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001133 CHECK(method != nullptr);
1134 return method;
1135 }
1136
Mathieu Chartier90443472015-07-16 20:32:27 -07001137 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001138 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1139 // If there's no new compiled code, either we're compiling an app and the target method
1140 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001141 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001142 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001143 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001144 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1145 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1146 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001147 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001148 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1149 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1150 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1151 target_offset = PointerToLowMemUInt32(oat_code_offset);
1152 } else {
1153 target_offset = target->IsNative()
1154 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1155 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1156 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001157 }
1158 return target_offset;
1159 }
1160
Vladimir Marko052164a2016-04-27 13:54:18 +01001161 mirror::DexCache* GetDexCache(const DexFile* target_dex_file)
1162 SHARED_REQUIRES(Locks::mutator_lock_) {
1163 return (target_dex_file == dex_file_)
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001164 ? dex_cache_
Vladimir Marko052164a2016-04-27 13:54:18 +01001165 : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1166 }
1167
1168 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1169 mirror::DexCache* dex_cache = GetDexCache(patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001170 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1171 CHECK(type != nullptr);
1172 return type;
1173 }
1174
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001175 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko052164a2016-04-27 13:54:18 +01001176 mirror::DexCache* dex_cache = GetDexCache(patch.TargetStringDexFile());
1177 mirror::String* string = dex_cache->GetResolvedString(patch.TargetStringIndex());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001178 DCHECK(string != nullptr);
1179 DCHECK(writer_->HasBootImage() ||
1180 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1181 return string;
1182 }
1183
Mathieu Chartier90443472015-07-16 20:32:27 -07001184 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001185 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001186 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1187 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1188 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1189 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001190 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001191 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001192 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1193 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001194 }
1195 }
1196
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001197 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1198 DCHECK(writer_->HasBootImage());
1199 object = writer_->image_writer_->GetImageAddress(object);
1200 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1201 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1202 // TODO: Clean up offset types. The target offset must be treated as signed.
1203 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1204 }
1205
Vladimir Markof4da6752014-08-01 19:04:18 +01001206 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001207 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001208 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001209 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001210 } else {
1211 // NOTE: We're using linker patches for app->boot references when the image can
1212 // be relocated and therefore we need to emit .oat_patches. We're not using this
1213 // for app->app references, so check that the object is in the image space.
1214 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001215 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001216 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001217 uint32_t address = PointerToLowMemUInt32(object);
1218 DCHECK_LE(offset + 4, code->size());
1219 uint8_t* data = &(*code)[offset];
1220 data[0] = address & 0xffu;
1221 data[1] = (address >> 8) & 0xffu;
1222 data[2] = (address >> 16) & 0xffu;
1223 data[3] = (address >> 24) & 0xffu;
1224 }
1225
Mathieu Chartiere401d142015-04-22 13:56:20 -07001226 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001227 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001228 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001229 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001230 } else if (kIsDebugBuild) {
1231 // NOTE: We're using linker patches for app->boot references when the image can
1232 // be relocated and therefore we need to emit .oat_patches. We're not using this
1233 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 std::vector<gc::space::ImageSpace*> image_spaces =
1235 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1236 bool contains_method = false;
1237 for (gc::space::ImageSpace* image_space : image_spaces) {
1238 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1239 contains_method |=
1240 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1241 }
1242 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001244 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001245 uint32_t address = PointerToLowMemUInt32(method);
1246 DCHECK_LE(offset + 4, code->size());
1247 uint8_t* data = &(*code)[offset];
1248 data[0] = address & 0xffu;
1249 data[1] = (address >> 8) & 0xffu;
1250 data[2] = (address >> 16) & 0xffu;
1251 data[3] = (address >> 24) & 0xffu;
1252 }
1253
Vladimir Markof4da6752014-08-01 19:04:18 +01001254 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001255 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001256 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001257 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001258 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1259 // TODO: Clean up offset types.
1260 // The target_offset must be treated as signed for cross-oat patching.
1261 const void* target = reinterpret_cast<const void*>(
1262 writer_->image_writer_->GetOatDataBegin(oat_index) +
1263 static_cast<int32_t>(target_offset));
1264 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001265 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001266 DCHECK_LE(offset + 4, code->size());
1267 uint8_t* data = &(*code)[offset];
1268 data[0] = address & 0xffu;
1269 data[1] = (address >> 8) & 0xffu;
1270 data[2] = (address >> 16) & 0xffu;
1271 data[3] = (address >> 24) & 0xffu;
1272 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001273};
1274
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001275class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1276 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001277 WriteMapMethodVisitor(OatWriter* writer,
1278 OutputStream* out,
1279 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001280 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001281 : OatDexMethodVisitor(writer, relative_offset),
1282 out_(out),
1283 file_offset_(file_offset) {
1284 }
1285
1286 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001287 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001288 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1289
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001290 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001291 size_t file_offset = file_offset_;
1292 OutputStream* out = out_;
1293
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001294 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1295 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001296 ++method_offsets_index_;
1297
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001298 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1299 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1300 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1301 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1302
1303 if (map_offset != 0u) {
1304 // Transform map_offset to actual oat data offset.
1305 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1306 DCHECK_NE(map_offset, 0u);
1307 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1308
1309 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1310 size_t map_size = map.size() * sizeof(map[0]);
1311 if (map_offset == offset_) {
1312 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Markoe079e212016-05-25 12:49:49 +01001313 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001314 ReportWriteFailure(it);
1315 return false;
1316 }
1317 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001318 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001319 }
1320 DCHECK_OFFSET_();
1321 }
1322
1323 return true;
1324 }
1325
1326 private:
1327 OutputStream* const out_;
1328 size_t const file_offset_;
1329
1330 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001331 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001332 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1333 }
1334};
1335
1336// Visit all methods from all classes in all dex files with the specified visitor.
1337bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1338 for (const DexFile* dex_file : *dex_files_) {
1339 const size_t class_def_count = dex_file->NumClassDefs();
1340 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1341 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1342 return false;
1343 }
1344 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001345 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001346 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001347 ClassDataItemIterator it(*dex_file, class_data);
1348 while (it.HasNextStaticField()) {
1349 it.Next();
1350 }
1351 while (it.HasNextInstanceField()) {
1352 it.Next();
1353 }
1354 size_t class_def_method_index = 0u;
1355 while (it.HasNextDirectMethod()) {
1356 if (!visitor->VisitMethod(class_def_method_index, it)) {
1357 return false;
1358 }
1359 ++class_def_method_index;
1360 it.Next();
1361 }
1362 while (it.HasNextVirtualMethod()) {
1363 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1364 return false;
1365 }
1366 ++class_def_method_index;
1367 it.Next();
1368 }
1369 }
1370 if (UNLIKELY(!visitor->EndClass())) {
1371 return false;
1372 }
1373 }
1374 }
1375 return true;
1376}
1377
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001378size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1379 const InstructionSetFeatures* instruction_set_features,
1380 uint32_t num_dex_files,
1381 SafeMap<std::string, std::string>* key_value_store) {
1382 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1383 oat_header_.reset(OatHeader::Create(instruction_set,
1384 instruction_set_features,
1385 num_dex_files,
1386 key_value_store));
1387 size_oat_header_ += sizeof(OatHeader);
1388 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001389 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001390}
1391
1392size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001393 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1394 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001395 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001396 oat_dex_file.offset_ = offset;
1397 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001398 }
1399 return offset;
1400}
1401
Brian Carlstrom389efb02012-01-11 12:06:26 -08001402size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001403 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001404 InitOatClassesMethodVisitor visitor(this, offset);
1405 bool success = VisitDexMethods(&visitor);
1406 CHECK(success);
1407 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001408
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001409 // Update oat_dex_files_.
1410 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001411 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1412 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001413 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001414 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001415 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001416 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001417 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001418 CHECK(oat_class_it == oat_classes_.end());
1419
1420 return offset;
1421}
1422
1423size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001424 InitMapMethodVisitor visitor(this, offset);
1425 bool success = VisitDexMethods(&visitor);
1426 DCHECK(success);
1427 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001428
Brian Carlstrome24fa612011-09-29 00:53:55 -07001429 return offset;
1430}
1431
1432size_t OatWriter::InitOatCode(size_t offset) {
1433 // calculate the offsets within OatHeader to executable code
1434 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001435 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001436 // required to be on a new page boundary
1437 offset = RoundUp(offset, kPageSize);
1438 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001439 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001440 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001441 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001442
Ian Rogers848871b2013-08-05 10:56:33 -07001443 #define DO_TRAMPOLINE(field, fn_name) \
1444 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001445 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1446 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001447 (field) = compiler_driver_->Create ## fn_name(); \
1448 offset += (field)->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001449
Ian Rogers848871b2013-08-05 10:56:33 -07001450 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001451 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001452 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001453 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1454 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001455
Ian Rogers848871b2013-08-05 10:56:33 -07001456 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001457 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001458 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1459 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1460 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001461 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001462 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001463 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001464 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001465 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001466 return offset;
1467}
1468
1469size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001470 #define VISIT(VisitorType) \
1471 do { \
1472 VisitorType visitor(this, offset); \
1473 bool success = VisitDexMethods(&visitor); \
1474 DCHECK(success); \
1475 offset = visitor.GetOffset(); \
1476 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001477
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001478 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001479 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001480 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001481 }
Logan Chien8b977d32012-02-21 19:14:55 +08001482
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001483 #undef VISIT
1484
Brian Carlstrome24fa612011-09-29 00:53:55 -07001485 return offset;
1486}
1487
David Srbeckybc90fd02015-04-22 19:40:27 +01001488bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001489 CHECK(write_state_ == WriteState::kWriteRoData);
1490
Vladimir Markoe079e212016-05-25 12:49:49 +01001491 // Wrap out to update checksum with each write.
1492 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1493 out = &checksum_updating_out;
1494
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001495 if (!WriteClassOffsets(out)) {
1496 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001497 return false;
1498 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001499
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001500 if (!WriteClasses(out)) {
1501 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001502 return false;
1503 }
1504
Vladimir Markof4da6752014-08-01 19:04:18 +01001505 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001506 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001507 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1508 return false;
1509 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001510 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001511 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001512 relative_offset = WriteMaps(out, file_offset, relative_offset);
1513 if (relative_offset == 0) {
1514 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1515 return false;
1516 }
1517
David Srbeckybc90fd02015-04-22 19:40:27 +01001518 // Write padding.
1519 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1520 relative_offset += size_executable_offset_alignment_;
1521 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1522 size_t expected_file_offset = file_offset + relative_offset;
1523 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1524 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1525 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1526 return 0;
1527 }
1528 DCHECK_OFFSET();
1529
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001530 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001531 return true;
1532}
1533
1534bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001535 CHECK(write_state_ == WriteState::kWriteText);
1536
Vladimir Markoe079e212016-05-25 12:49:49 +01001537 // Wrap out to update checksum with each write.
1538 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1539 out = &checksum_updating_out;
1540
Vladimir Marko944da602016-02-19 12:27:55 +00001541 SetMultiOatRelativePatcherAdjustment();
1542
David Srbeckybc90fd02015-04-22 19:40:27 +01001543 const size_t file_offset = oat_data_offset_;
1544 size_t relative_offset = oat_header_->GetExecutableOffset();
1545 DCHECK_OFFSET();
1546
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001547 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001548 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001549 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001550 return false;
1551 }
1552
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001553 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1554 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001555 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001556 return false;
1557 }
1558
Vladimir Markof4da6752014-08-01 19:04:18 +01001559 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001560 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001561 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1562 return false;
1563 }
1564
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001565 if (kIsDebugBuild) {
1566 uint32_t size_total = 0;
1567 #define DO_STAT(x) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001568 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
1569 size_total += (x);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001570
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001571 DO_STAT(size_dex_file_alignment_);
1572 DO_STAT(size_executable_offset_alignment_);
1573 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001574 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001575 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001576 DO_STAT(size_interpreter_to_interpreter_bridge_);
1577 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1578 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001579 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001580 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001581 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001582 DO_STAT(size_quick_to_interpreter_bridge_);
1583 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001584 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001585 DO_STAT(size_code_);
1586 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001587 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001588 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001589 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001590 DO_STAT(size_oat_dex_file_location_size_);
1591 DO_STAT(size_oat_dex_file_location_data_);
1592 DO_STAT(size_oat_dex_file_location_checksum_);
1593 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001594 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001595 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001596 DO_STAT(size_oat_lookup_table_alignment_);
1597 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001598 DO_STAT(size_oat_class_offsets_alignment_);
1599 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001600 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001601 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001602 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001603 DO_STAT(size_oat_class_method_offsets_);
1604 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001605
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001606 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001607 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001608 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001609 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001610
Vladimir Markof4da6752014-08-01 19:04:18 +01001611 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001612 CHECK_EQ(size_, relative_offset);
1613
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001614 write_state_ = WriteState::kWriteHeader;
1615 return true;
1616}
1617
1618bool OatWriter::WriteHeader(OutputStream* out,
1619 uint32_t image_file_location_oat_checksum,
1620 uintptr_t image_file_location_oat_begin,
1621 int32_t image_patch_delta) {
1622 CHECK(write_state_ == WriteState::kWriteHeader);
1623
1624 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1625 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1626 if (compiler_driver_->IsBootImage()) {
1627 CHECK_EQ(image_patch_delta, 0);
1628 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1629 } else {
1630 CHECK_ALIGNED(image_patch_delta, kPageSize);
1631 oat_header_->SetImagePatchDelta(image_patch_delta);
1632 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001633 oat_header_->UpdateChecksumWithHeaderData();
1634
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001635 const size_t file_offset = oat_data_offset_;
1636
1637 off_t current_offset = out->Seek(0, kSeekCurrent);
1638 if (current_offset == static_cast<off_t>(-1)) {
1639 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1640 return false;
1641 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001642 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001643 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1644 return false;
1645 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001646 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001647
1648 // Flush all other data before writing the header.
1649 if (!out->Flush()) {
1650 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1651 return false;
1652 }
1653 // Write the header.
1654 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001655 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001656 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1657 return false;
1658 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001659 // Flush the header data.
1660 if (!out->Flush()) {
1661 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001662 return false;
1663 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001664
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001665 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1666 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1667 return false;
1668 }
1669 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1670
1671 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001672 return true;
1673}
1674
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001675bool OatWriter::WriteClassOffsets(OutputStream* out) {
1676 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1677 if (oat_dex_file.class_offsets_offset_ != 0u) {
1678 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1679 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1680 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1681 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1682 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001683 return false;
1684 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001685 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1686 return false;
1687 }
1688 }
1689 }
1690 return true;
1691}
1692
1693bool OatWriter::WriteClasses(OutputStream* out) {
1694 for (OatClass& oat_class : oat_classes_) {
1695 if (!oat_class.Write(this, out, oat_data_offset_)) {
1696 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1697 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001698 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001699 }
1700 return true;
1701}
1702
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001703size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001704 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001705 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1706 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1707 return 0;
1708 }
1709 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001710 size_vmap_table_ = relative_offset - vmap_tables_offset;
1711
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001712 return relative_offset;
1713}
1714
1715size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001716 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001717 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001718
Ian Rogers848871b2013-08-05 10:56:33 -07001719 #define DO_TRAMPOLINE(field) \
1720 do { \
1721 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1722 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001723 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001724 size_trampoline_alignment_ += alignment_padding; \
Vladimir Markoe079e212016-05-25 12:49:49 +01001725 if (!out->WriteFully((field)->data(), (field)->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001726 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001727 return false; \
1728 } \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001729 size_ ## field += (field)->size(); \
1730 relative_offset += alignment_padding + (field)->size(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001731 DCHECK_OFFSET(); \
1732 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001733
Ian Rogers848871b2013-08-05 10:56:33 -07001734 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001735 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001736 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001737 DO_TRAMPOLINE(quick_resolution_trampoline_);
1738 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1739 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001740 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001741 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001742}
1743
Ian Rogers3d504072014-03-01 09:16:49 -08001744size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001745 const size_t file_offset,
1746 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001747 #define VISIT(VisitorType) \
1748 do { \
1749 VisitorType visitor(this, out, file_offset, relative_offset); \
1750 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1751 return 0; \
1752 } \
1753 relative_offset = visitor.GetOffset(); \
1754 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001755
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001756 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001757
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001758 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001759
Vladimir Markob163bb72015-03-31 21:49:49 +01001760 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1761 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1762 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1763
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001764 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001765}
1766
Vladimir Marko944da602016-02-19 12:27:55 +00001767bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001768 // Get the elf file offset of the oat file.
1769 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1770 if (raw_file_offset == static_cast<off_t>(-1)) {
1771 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1772 return false;
1773 }
1774 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1775 return true;
1776}
1777
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001778bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1779 // Read the dex file header and perform minimal verification.
1780 uint8_t raw_header[sizeof(DexFile::Header)];
1781 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1782 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1783 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1784 return false;
1785 }
1786 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1787 return false;
1788 }
1789
1790 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1791 oat_dex_file->dex_file_size_ = header->file_size_;
1792 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1793 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1794 return true;
1795}
1796
1797bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1798 if (!DexFile::IsMagicValid(raw_header)) {
1799 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1800 return false;
1801 }
1802 if (!DexFile::IsVersionValid(raw_header)) {
1803 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1804 return false;
1805 }
1806 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1807 if (header->file_size_ < sizeof(DexFile::Header)) {
1808 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1809 << " File: " << location;
1810 return false;
1811 }
1812 return true;
1813}
1814
1815bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1816 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1817
1818 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001819 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001820 return false;
1821 }
1822
1823 // Write dex files.
1824 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1825 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1826 return false;
1827 }
1828 }
1829
1830 // Close sources.
1831 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1832 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1833 }
1834 zipped_dex_files_.clear();
1835 zip_archives_.clear();
1836 raw_dex_files_.clear();
1837 return true;
1838}
1839
1840bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1841 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1842 return false;
1843 }
1844 if (oat_dex_file->source_.IsZipEntry()) {
1845 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1846 return false;
1847 }
1848 } else if (oat_dex_file->source_.IsRawFile()) {
1849 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1850 return false;
1851 }
1852 } else {
1853 DCHECK(oat_dex_file->source_.IsRawData());
1854 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1855 return false;
1856 }
1857 }
1858
1859 // Update current size and account for the written data.
1860 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1861 size_ += oat_dex_file->dex_file_size_;
1862 size_dex_file_ += oat_dex_file->dex_file_size_;
1863 return true;
1864}
1865
1866bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1867 // Dex files are required to be 4 byte aligned.
1868 size_t original_offset = size_;
1869 size_t offset = RoundUp(original_offset, 4);
1870 size_dex_file_alignment_ += offset - original_offset;
1871
1872 // Seek to the start of the dex file and flush any pending operations in the stream.
1873 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1874 uint32_t start_offset = oat_data_offset_ + offset;
1875 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1876 if (actual_offset != static_cast<off_t>(start_offset)) {
1877 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1878 << " Expected: " << start_offset
1879 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1880 return false;
1881 }
1882 if (!out->Flush()) {
1883 PLOG(ERROR) << "Failed to flush before writing dex file."
1884 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1885 return false;
1886 }
1887 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1888 if (actual_offset != static_cast<off_t>(start_offset)) {
1889 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1890 << " Expected: " << start_offset
1891 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1892 return false;
1893 }
1894
1895 size_ = offset;
1896 oat_dex_file->dex_file_offset_ = offset;
1897 return true;
1898}
1899
1900bool OatWriter::WriteDexFile(OutputStream* rodata,
1901 File* file,
1902 OatDexFile* oat_dex_file,
1903 ZipEntry* dex_file) {
1904 size_t start_offset = oat_data_offset_ + size_;
1905 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1906
1907 // Extract the dex file and get the extracted size.
1908 std::string error_msg;
1909 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1910 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1911 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1912 return false;
1913 }
1914 if (file->Flush() != 0) {
1915 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1916 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1917 return false;
1918 }
1919 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1920 if (extracted_end == static_cast<off_t>(-1)) {
1921 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1922 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1923 return false;
1924 }
1925 if (extracted_end < static_cast<off_t>(start_offset)) {
1926 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1927 << " Start: " << start_offset
1928 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1929 return false;
1930 }
1931 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1932 if (extracted_size < sizeof(DexFile::Header)) {
1933 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1934 << extracted_size << " File: " << oat_dex_file->GetLocation();
1935 return false;
1936 }
1937
1938 // Read the dex file header and extract required data to OatDexFile.
1939 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1940 if (actual_offset != static_cast<off_t>(start_offset)) {
1941 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1942 << " Expected: " << start_offset
1943 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1944 return false;
1945 }
1946 if (!ReadDexFileHeader(file, oat_dex_file)) {
1947 return false;
1948 }
1949 if (extracted_size < oat_dex_file->dex_file_size_) {
1950 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1951 << " file size from header: " << oat_dex_file->dex_file_size_
1952 << " File: " << oat_dex_file->GetLocation();
1953 return false;
1954 }
1955
1956 // Override the checksum from header with the CRC from ZIP entry.
1957 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1958
1959 // Seek both file and stream to the end offset.
1960 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1961 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1962 if (actual_offset != static_cast<off_t>(end_offset)) {
1963 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1964 << " Expected: " << end_offset
1965 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1966 return false;
1967 }
1968 actual_offset = rodata->Seek(end_offset, kSeekSet);
1969 if (actual_offset != static_cast<off_t>(end_offset)) {
1970 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1971 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1972 return false;
1973 }
1974 if (!rodata->Flush()) {
1975 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1976 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1977 return false;
1978 }
1979
1980 // If we extracted more than the size specified in the header, truncate the file.
1981 if (extracted_size > oat_dex_file->dex_file_size_) {
1982 if (file->SetLength(end_offset) != 0) {
1983 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1984 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1985 return false;
1986 }
1987 }
1988
1989 return true;
1990}
1991
1992bool OatWriter::WriteDexFile(OutputStream* rodata,
1993 File* file,
1994 OatDexFile* oat_dex_file,
1995 File* dex_file) {
1996 size_t start_offset = oat_data_offset_ + size_;
1997 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1998
1999 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
2000 if (input_offset != static_cast<off_t>(0)) {
2001 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
2002 << " Expected: 0"
2003 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2004 return false;
2005 }
2006 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2007 return false;
2008 }
2009
2010 // Copy the input dex file using sendfile().
2011 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2012 PLOG(ERROR) << "Failed to copy dex file to oat file."
2013 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2014 return false;
2015 }
2016 if (file->Flush() != 0) {
2017 PLOG(ERROR) << "Failed to flush dex file."
2018 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2019 return false;
2020 }
2021
2022 // Check file position and seek the stream to the end offset.
2023 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2024 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2025 if (actual_offset != static_cast<off_t>(end_offset)) {
2026 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2027 << " Expected: " << end_offset
2028 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2029 return false;
2030 }
2031 actual_offset = rodata->Seek(end_offset, kSeekSet);
2032 if (actual_offset != static_cast<off_t>(end_offset)) {
2033 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2034 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2035 return false;
2036 }
2037 if (!rodata->Flush()) {
2038 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2039 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2040 return false;
2041 }
2042
2043 return true;
2044}
2045
2046bool OatWriter::WriteDexFile(OutputStream* rodata,
2047 OatDexFile* oat_dex_file,
2048 const uint8_t* dex_file) {
2049 // Note: The raw data has already been checked to contain the header
2050 // and all the data that the header specifies as the file size.
2051 DCHECK(dex_file != nullptr);
2052 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2053 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2054
Vladimir Markoe079e212016-05-25 12:49:49 +01002055 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002056 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2057 << " to " << rodata->GetLocation();
2058 return false;
2059 }
2060 if (!rodata->Flush()) {
2061 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2062 << " File: " << oat_dex_file->GetLocation();
2063 return false;
2064 }
2065
2066 // Update dex file size and resize class offsets in the OatDexFile.
2067 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2068 oat_dex_file->dex_file_size_ = header->file_size_;
2069 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2070 return true;
2071}
2072
2073bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2074 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2075
2076 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2077 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2078 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2079 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2080 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2081 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2082 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2083 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2084 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2085 return false;
2086 }
2087
2088 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2089 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2090
2091 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2092 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2093
2094 // Write OatDexFile.
2095 if (!oat_dex_file->Write(this, rodata)) {
2096 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2097 return false;
2098 }
2099 }
2100
2101 return true;
2102}
2103
2104bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2105 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2106
2107 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2108 if (file->SetLength(new_length) != 0) {
2109 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2110 << "File: " << file->GetPath();
2111 return false;
2112 }
2113 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2114 if (actual_offset != static_cast<off_t>(new_length)) {
2115 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2116 << " Actual: " << actual_offset << " Expected: " << new_length
2117 << " File: " << rodata->GetLocation();
2118 return false;
2119 }
2120 if (!rodata->Flush()) {
2121 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2122 << " File: " << rodata->GetLocation();
2123 return false;
2124 }
2125 return true;
2126}
2127
2128bool OatWriter::OpenDexFiles(
2129 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002130 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002131 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2132 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2133 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2134
2135 if (oat_dex_files_.empty()) {
2136 // Nothing to do.
2137 return true;
2138 }
2139
2140 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2141 size_t length = size_ - map_offset;
2142 std::string error_msg;
2143 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2144 PROT_READ | PROT_WRITE,
2145 MAP_SHARED,
2146 file->Fd(),
2147 oat_data_offset_ + map_offset,
2148 /* low_4gb */ false,
2149 file->GetPath().c_str(),
2150 &error_msg));
2151 if (dex_files_map == nullptr) {
2152 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2153 << " error: " << error_msg;
2154 return false;
2155 }
2156 std::vector<std::unique_ptr<const DexFile>> dex_files;
2157 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2158 // Make sure no one messed with input files while we were copying data.
2159 // At the very least we need consistent file size and number of class definitions.
2160 const uint8_t* raw_dex_file =
2161 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2162 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2163 // Note: ValidateDexFileHeader() already logged an error message.
2164 LOG(ERROR) << "Failed to verify written dex file header!"
2165 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2166 << " ~ " << static_cast<const void*>(raw_dex_file);
2167 return false;
2168 }
2169 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2170 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2171 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2172 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2173 << " Output: " << file->GetPath();
2174 return false;
2175 }
2176 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2177 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2178 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2179 << " Output: " << file->GetPath();
2180 return false;
2181 }
2182
2183 // Now, open the dex file.
2184 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2185 oat_dex_file.dex_file_size_,
2186 oat_dex_file.GetLocation(),
2187 oat_dex_file.dex_file_location_checksum_,
2188 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002189 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002190 &error_msg));
2191 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002192 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2193 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002194 return false;
2195 }
2196 }
2197
2198 *opened_dex_files_map = std::move(dex_files_map);
2199 *opened_dex_files = std::move(dex_files);
2200 return true;
2201}
2202
2203bool OatWriter::WriteTypeLookupTables(
2204 MemMap* opened_dex_files_map,
2205 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2206 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2207
2208 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2209 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2210 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2211 if (oat_dex_file->lookup_table_offset_ != 0u) {
2212 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2213 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2214 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2215 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2216 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2217 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2218 }
2219 }
2220
2221 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2222 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2223 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2224 return false;
2225 }
2226
2227 return true;
2228}
2229
Vladimir Markof4da6752014-08-01 19:04:18 +01002230bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2231 static const uint8_t kPadding[] = {
2232 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2233 };
2234 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Markoe079e212016-05-25 12:49:49 +01002235 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002236 return false;
2237 }
2238 size_code_alignment_ += aligned_code_delta;
2239 return true;
2240}
2241
Vladimir Marko944da602016-02-19 12:27:55 +00002242void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2243 DCHECK(dex_files_ != nullptr);
2244 DCHECK(relative_patcher_ != nullptr);
2245 DCHECK_NE(oat_data_offset_, 0u);
2246 if (image_writer_ != nullptr && !dex_files_->empty()) {
2247 // The oat data begin may not be initialized yet but the oat file offset is ready.
2248 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2249 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2250 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002251 }
2252}
2253
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002254OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2255 DexFileSource source,
2256 CreateTypeLookupTable create_type_lookup_table)
2257 : source_(source),
2258 create_type_lookup_table_(create_type_lookup_table),
2259 dex_file_size_(0),
2260 offset_(0),
2261 dex_file_location_size_(strlen(dex_file_location)),
2262 dex_file_location_data_(dex_file_location),
2263 dex_file_location_checksum_(0u),
2264 dex_file_offset_(0u),
2265 class_offsets_offset_(0u),
2266 lookup_table_offset_(0u),
2267 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002268}
2269
2270size_t OatWriter::OatDexFile::SizeOf() const {
2271 return sizeof(dex_file_location_size_)
2272 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002273 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002274 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002275 + sizeof(class_offsets_offset_)
2276 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002277}
2278
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002279void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2280 DCHECK_EQ(lookup_table_offset_, 0u);
2281 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2282 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2283 if (table_size != 0u) {
2284 // Type tables are required to be 4 byte aligned.
2285 size_t original_offset = oat_writer->size_;
2286 size_t offset = RoundUp(original_offset, 4);
2287 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2288 lookup_table_offset_ = offset;
2289 oat_writer->size_ = offset + table_size;
2290 oat_writer->size_oat_lookup_table_ += table_size;
2291 }
2292 }
2293}
2294
2295void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2296 DCHECK_EQ(class_offsets_offset_, 0u);
2297 if (!class_offsets_.empty()) {
2298 // Class offsets are required to be 4 byte aligned.
2299 size_t original_offset = oat_writer->size_;
2300 size_t offset = RoundUp(original_offset, 4);
2301 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2302 class_offsets_offset_ = offset;
2303 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2304 }
2305}
2306
2307bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2308 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002309 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002310
Vladimir Markoe079e212016-05-25 12:49:49 +01002311 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002312 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002313 return false;
2314 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002315 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002316
Vladimir Markoe079e212016-05-25 12:49:49 +01002317 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002318 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002319 return false;
2320 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002321 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002322
Vladimir Markoe079e212016-05-25 12:49:49 +01002323 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002324 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002325 return false;
2326 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002327 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002328
Vladimir Markoe079e212016-05-25 12:49:49 +01002329 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002330 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002331 return false;
2332 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002333 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002334
Vladimir Markoe079e212016-05-25 12:49:49 +01002335 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002336 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2337 return false;
2338 }
2339 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2340
Vladimir Markoe079e212016-05-25 12:49:49 +01002341 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002342 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2343 return false;
2344 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002345 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002346
2347 return true;
2348}
2349
2350bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Markoe079e212016-05-25 12:49:49 +01002351 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002352 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2353 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002354 return false;
2355 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002356 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002357 return true;
2358}
2359
Brian Carlstromba150c32013-08-27 17:31:03 -07002360OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002361 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002362 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002363 mirror::Class::Status status)
2364 : compiled_methods_(compiled_methods) {
2365 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002366 CHECK_LE(num_non_null_compiled_methods, num_methods);
2367
Brian Carlstrom265091e2013-01-30 14:08:26 -08002368 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002369 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2370
2371 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2372 // apply when there are 0 methods, we just arbitrarily say that 0
2373 // methods means kOatClassNoneCompiled and that we won't use
2374 // kOatClassAllCompiled unless there is at least one compiled
2375 // method. This means in an interpretter only system, we can assert
2376 // that all classes are kOatClassNoneCompiled.
2377 if (num_non_null_compiled_methods == 0) {
2378 type_ = kOatClassNoneCompiled;
2379 } else if (num_non_null_compiled_methods == num_methods) {
2380 type_ = kOatClassAllCompiled;
2381 } else {
2382 type_ = kOatClassSomeCompiled;
2383 }
2384
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002385 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002386 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002387 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002388
2389 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2390 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002391 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002392 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2393 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2394 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2395 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002396 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002397 method_bitmap_size_ = 0;
2398 }
2399
2400 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002401 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002402 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002403 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2404 } else {
2405 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2406 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2407 if (type_ == kOatClassSomeCompiled) {
2408 method_bitmap_->SetBit(i);
2409 }
2410 }
2411 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002412}
2413
Brian Carlstrom265091e2013-01-30 14:08:26 -08002414size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2415 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002416 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2417 if (method_offset == 0) {
2418 return 0;
2419 }
2420 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002421}
2422
2423size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2424 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002425 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002426}
2427
2428size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002429 return sizeof(status_)
2430 + sizeof(type_)
2431 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2432 + method_bitmap_size_
2433 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002434}
2435
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002436bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002437 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002438 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002439 DCHECK_OFFSET_();
Vladimir Markoe079e212016-05-25 12:49:49 +01002440 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002441 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002442 return false;
2443 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002444 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002445
Vladimir Markoe079e212016-05-25 12:49:49 +01002446 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002447 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002448 return false;
2449 }
2450 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002451
Brian Carlstromba150c32013-08-27 17:31:03 -07002452 if (method_bitmap_size_ != 0) {
2453 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markoe079e212016-05-25 12:49:49 +01002454 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002455 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002456 return false;
2457 }
2458 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002459
Vladimir Markoe079e212016-05-25 12:49:49 +01002460 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002461 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002462 return false;
2463 }
2464 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2465 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002466
Vladimir Markoe079e212016-05-25 12:49:49 +01002467 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002468 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002469 return false;
2470 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002471 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002472 return true;
2473}
2474
Brian Carlstrome24fa612011-09-29 00:53:55 -07002475} // namespace art