blob: a02c0247b736bb3572e45d8ff76750beb77980d3 [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 Marko7eef3392016-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 Marko7eef3392016-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 Marko7eef3392016-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 Marko7eef3392016-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 Marko7eef3392016-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 Markocac5a7e2016-02-22 10:39:50 +00001161 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001162 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001163 ? dex_cache_
1164 : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001165 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1166 CHECK(type != nullptr);
1167 return type;
1168 }
1169
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001170 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1171 mirror::String* string = dex_cache_->GetResolvedString(patch.TargetStringIndex());
1172 DCHECK(string != nullptr);
1173 DCHECK(writer_->HasBootImage() ||
1174 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1175 return string;
1176 }
1177
Mathieu Chartier90443472015-07-16 20:32:27 -07001178 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001179 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001180 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1181 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1182 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1183 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001184 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001185 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001186 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1187 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001188 }
1189 }
1190
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001191 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1192 DCHECK(writer_->HasBootImage());
1193 object = writer_->image_writer_->GetImageAddress(object);
1194 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1195 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1196 // TODO: Clean up offset types. The target offset must be treated as signed.
1197 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1198 }
1199
Vladimir Markof4da6752014-08-01 19:04:18 +01001200 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001201 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001202 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001203 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001204 } else {
1205 // NOTE: We're using linker patches for app->boot references when the image can
1206 // be relocated and therefore we need to emit .oat_patches. We're not using this
1207 // for app->app references, so check that the object is in the image space.
1208 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001209 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001210 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001211 uint32_t address = PointerToLowMemUInt32(object);
1212 DCHECK_LE(offset + 4, code->size());
1213 uint8_t* data = &(*code)[offset];
1214 data[0] = address & 0xffu;
1215 data[1] = (address >> 8) & 0xffu;
1216 data[2] = (address >> 16) & 0xffu;
1217 data[3] = (address >> 24) & 0xffu;
1218 }
1219
Mathieu Chartiere401d142015-04-22 13:56:20 -07001220 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001221 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001222 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001223 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001224 } else if (kIsDebugBuild) {
1225 // NOTE: We're using linker patches for app->boot references when the image can
1226 // be relocated and therefore we need to emit .oat_patches. We're not using this
1227 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001228 std::vector<gc::space::ImageSpace*> image_spaces =
1229 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1230 bool contains_method = false;
1231 for (gc::space::ImageSpace* image_space : image_spaces) {
1232 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1233 contains_method |=
1234 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1235 }
1236 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001237 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001238 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001239 uint32_t address = PointerToLowMemUInt32(method);
1240 DCHECK_LE(offset + 4, code->size());
1241 uint8_t* data = &(*code)[offset];
1242 data[0] = address & 0xffu;
1243 data[1] = (address >> 8) & 0xffu;
1244 data[2] = (address >> 16) & 0xffu;
1245 data[3] = (address >> 24) & 0xffu;
1246 }
1247
Vladimir Markof4da6752014-08-01 19:04:18 +01001248 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001249 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001250 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001251 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001252 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1253 // TODO: Clean up offset types.
1254 // The target_offset must be treated as signed for cross-oat patching.
1255 const void* target = reinterpret_cast<const void*>(
1256 writer_->image_writer_->GetOatDataBegin(oat_index) +
1257 static_cast<int32_t>(target_offset));
1258 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001259 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001260 DCHECK_LE(offset + 4, code->size());
1261 uint8_t* data = &(*code)[offset];
1262 data[0] = address & 0xffu;
1263 data[1] = (address >> 8) & 0xffu;
1264 data[2] = (address >> 16) & 0xffu;
1265 data[3] = (address >> 24) & 0xffu;
1266 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001267};
1268
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001269class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1270 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001271 WriteMapMethodVisitor(OatWriter* writer,
1272 OutputStream* out,
1273 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001274 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001275 : OatDexMethodVisitor(writer, relative_offset),
1276 out_(out),
1277 file_offset_(file_offset) {
1278 }
1279
1280 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001281 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001282 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1283
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001284 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001285 size_t file_offset = file_offset_;
1286 OutputStream* out = out_;
1287
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001288 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1289 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001290 ++method_offsets_index_;
1291
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001292 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1293 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1294 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1295 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1296
1297 if (map_offset != 0u) {
1298 // Transform map_offset to actual oat data offset.
1299 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1300 DCHECK_NE(map_offset, 0u);
1301 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1302
1303 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1304 size_t map_size = map.size() * sizeof(map[0]);
1305 if (map_offset == offset_) {
1306 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
Vladimir Marko7eef3392016-05-25 12:49:49 +01001307 if (UNLIKELY(!out->WriteFully(map.data(), map_size))) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001308 ReportWriteFailure(it);
1309 return false;
1310 }
1311 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001312 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001313 }
1314 DCHECK_OFFSET_();
1315 }
1316
1317 return true;
1318 }
1319
1320 private:
1321 OutputStream* const out_;
1322 size_t const file_offset_;
1323
1324 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001325 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001326 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1327 }
1328};
1329
1330// Visit all methods from all classes in all dex files with the specified visitor.
1331bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1332 for (const DexFile* dex_file : *dex_files_) {
1333 const size_t class_def_count = dex_file->NumClassDefs();
1334 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1335 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1336 return false;
1337 }
1338 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001339 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001340 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001341 ClassDataItemIterator it(*dex_file, class_data);
1342 while (it.HasNextStaticField()) {
1343 it.Next();
1344 }
1345 while (it.HasNextInstanceField()) {
1346 it.Next();
1347 }
1348 size_t class_def_method_index = 0u;
1349 while (it.HasNextDirectMethod()) {
1350 if (!visitor->VisitMethod(class_def_method_index, it)) {
1351 return false;
1352 }
1353 ++class_def_method_index;
1354 it.Next();
1355 }
1356 while (it.HasNextVirtualMethod()) {
1357 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1358 return false;
1359 }
1360 ++class_def_method_index;
1361 it.Next();
1362 }
1363 }
1364 if (UNLIKELY(!visitor->EndClass())) {
1365 return false;
1366 }
1367 }
1368 }
1369 return true;
1370}
1371
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001372size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1373 const InstructionSetFeatures* instruction_set_features,
1374 uint32_t num_dex_files,
1375 SafeMap<std::string, std::string>* key_value_store) {
1376 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1377 oat_header_.reset(OatHeader::Create(instruction_set,
1378 instruction_set_features,
1379 num_dex_files,
1380 key_value_store));
1381 size_oat_header_ += sizeof(OatHeader);
1382 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001383 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001384}
1385
1386size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001387 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1388 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001389 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001390 oat_dex_file.offset_ = offset;
1391 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001392 }
1393 return offset;
1394}
1395
Brian Carlstrom389efb02012-01-11 12:06:26 -08001396size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001397 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001398 InitOatClassesMethodVisitor visitor(this, offset);
1399 bool success = VisitDexMethods(&visitor);
1400 CHECK(success);
1401 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001402
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001403 // Update oat_dex_files_.
1404 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001405 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1406 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001407 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001408 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001409 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001410 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001411 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001412 CHECK(oat_class_it == oat_classes_.end());
1413
1414 return offset;
1415}
1416
1417size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001418 InitMapMethodVisitor visitor(this, offset);
1419 bool success = VisitDexMethods(&visitor);
1420 DCHECK(success);
1421 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001422
Brian Carlstrome24fa612011-09-29 00:53:55 -07001423 return offset;
1424}
1425
1426size_t OatWriter::InitOatCode(size_t offset) {
1427 // calculate the offsets within OatHeader to executable code
1428 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001429 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001430 // required to be on a new page boundary
1431 offset = RoundUp(offset, kPageSize);
1432 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001433 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001434 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001435 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001436
Ian Rogers848871b2013-08-05 10:56:33 -07001437 #define DO_TRAMPOLINE(field, fn_name) \
1438 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001439 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1440 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Vladimir Markod1ee8092016-04-13 11:59:46 +01001441 field = compiler_driver_->Create ## fn_name(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001442 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001443
Ian Rogers848871b2013-08-05 10:56:33 -07001444 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001445 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001446 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001447 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1448 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001449
Ian Rogers848871b2013-08-05 10:56:33 -07001450 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001451 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001452 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1453 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1454 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001455 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001456 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001457 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001458 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001459 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001460 return offset;
1461}
1462
1463size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001464 #define VISIT(VisitorType) \
1465 do { \
1466 VisitorType visitor(this, offset); \
1467 bool success = VisitDexMethods(&visitor); \
1468 DCHECK(success); \
1469 offset = visitor.GetOffset(); \
1470 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001471
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001472 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001473 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001474 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001475 }
Logan Chien8b977d32012-02-21 19:14:55 +08001476
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001477 #undef VISIT
1478
Brian Carlstrome24fa612011-09-29 00:53:55 -07001479 return offset;
1480}
1481
David Srbeckybc90fd02015-04-22 19:40:27 +01001482bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001483 CHECK(write_state_ == WriteState::kWriteRoData);
1484
Vladimir Marko7eef3392016-05-25 12:49:49 +01001485 // Wrap out to update checksum with each write.
1486 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1487 out = &checksum_updating_out;
1488
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001489 if (!WriteClassOffsets(out)) {
1490 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001491 return false;
1492 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001493
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001494 if (!WriteClasses(out)) {
1495 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001496 return false;
1497 }
1498
Vladimir Markof4da6752014-08-01 19:04:18 +01001499 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001500 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001501 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1502 return false;
1503 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001504 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001505 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001506 relative_offset = WriteMaps(out, file_offset, relative_offset);
1507 if (relative_offset == 0) {
1508 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1509 return false;
1510 }
1511
David Srbeckybc90fd02015-04-22 19:40:27 +01001512 // Write padding.
1513 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1514 relative_offset += size_executable_offset_alignment_;
1515 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1516 size_t expected_file_offset = file_offset + relative_offset;
1517 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1518 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1519 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1520 return 0;
1521 }
1522 DCHECK_OFFSET();
1523
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001524 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001525 return true;
1526}
1527
1528bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001529 CHECK(write_state_ == WriteState::kWriteText);
1530
Vladimir Marko7eef3392016-05-25 12:49:49 +01001531 // Wrap out to update checksum with each write.
1532 ChecksumUpdatingOutputStream checksum_updating_out(out, oat_header_.get());
1533 out = &checksum_updating_out;
1534
Vladimir Marko944da602016-02-19 12:27:55 +00001535 SetMultiOatRelativePatcherAdjustment();
1536
David Srbeckybc90fd02015-04-22 19:40:27 +01001537 const size_t file_offset = oat_data_offset_;
1538 size_t relative_offset = oat_header_->GetExecutableOffset();
1539 DCHECK_OFFSET();
1540
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001541 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001542 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001543 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001544 return false;
1545 }
1546
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001547 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1548 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001549 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001550 return false;
1551 }
1552
Vladimir Markof4da6752014-08-01 19:04:18 +01001553 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001554 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001555 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1556 return false;
1557 }
1558
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001559 if (kIsDebugBuild) {
1560 uint32_t size_total = 0;
1561 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001562 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001563 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001564
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001565 DO_STAT(size_dex_file_alignment_);
1566 DO_STAT(size_executable_offset_alignment_);
1567 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001568 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001569 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001570 DO_STAT(size_interpreter_to_interpreter_bridge_);
1571 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1572 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001573 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001574 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001575 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001576 DO_STAT(size_quick_to_interpreter_bridge_);
1577 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001578 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001579 DO_STAT(size_code_);
1580 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001581 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001582 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001583 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001584 DO_STAT(size_oat_dex_file_location_size_);
1585 DO_STAT(size_oat_dex_file_location_data_);
1586 DO_STAT(size_oat_dex_file_location_checksum_);
1587 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001588 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001589 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001590 DO_STAT(size_oat_lookup_table_alignment_);
1591 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001592 DO_STAT(size_oat_class_offsets_alignment_);
1593 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001594 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001595 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001596 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001597 DO_STAT(size_oat_class_method_offsets_);
1598 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001599
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001600 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001601 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001602 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001603 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001604
Vladimir Markof4da6752014-08-01 19:04:18 +01001605 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001606 CHECK_EQ(size_, relative_offset);
1607
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001608 write_state_ = WriteState::kWriteHeader;
1609 return true;
1610}
1611
1612bool OatWriter::WriteHeader(OutputStream* out,
1613 uint32_t image_file_location_oat_checksum,
1614 uintptr_t image_file_location_oat_begin,
1615 int32_t image_patch_delta) {
1616 CHECK(write_state_ == WriteState::kWriteHeader);
1617
1618 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1619 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1620 if (compiler_driver_->IsBootImage()) {
1621 CHECK_EQ(image_patch_delta, 0);
1622 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1623 } else {
1624 CHECK_ALIGNED(image_patch_delta, kPageSize);
1625 oat_header_->SetImagePatchDelta(image_patch_delta);
1626 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001627 oat_header_->UpdateChecksumWithHeaderData();
1628
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001629 const size_t file_offset = oat_data_offset_;
1630
1631 off_t current_offset = out->Seek(0, kSeekCurrent);
1632 if (current_offset == static_cast<off_t>(-1)) {
1633 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1634 return false;
1635 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001636 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001637 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1638 return false;
1639 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001640 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001641
1642 // Flush all other data before writing the header.
1643 if (!out->Flush()) {
1644 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1645 return false;
1646 }
1647 // Write the header.
1648 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001649 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001650 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1651 return false;
1652 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001653 // Flush the header data.
1654 if (!out->Flush()) {
1655 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001656 return false;
1657 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001658
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001659 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1660 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1661 return false;
1662 }
1663 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1664
1665 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001666 return true;
1667}
1668
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001669bool OatWriter::WriteClassOffsets(OutputStream* out) {
1670 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1671 if (oat_dex_file.class_offsets_offset_ != 0u) {
1672 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1673 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1674 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1675 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1676 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001677 return false;
1678 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001679 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1680 return false;
1681 }
1682 }
1683 }
1684 return true;
1685}
1686
1687bool OatWriter::WriteClasses(OutputStream* out) {
1688 for (OatClass& oat_class : oat_classes_) {
1689 if (!oat_class.Write(this, out, oat_data_offset_)) {
1690 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1691 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001692 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001693 }
1694 return true;
1695}
1696
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001697size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001698 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001699 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1700 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1701 return 0;
1702 }
1703 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001704 size_vmap_table_ = relative_offset - vmap_tables_offset;
1705
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001706 return relative_offset;
1707}
1708
1709size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001710 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001711 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001712
Ian Rogers848871b2013-08-05 10:56:33 -07001713 #define DO_TRAMPOLINE(field) \
1714 do { \
1715 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1716 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001717 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001718 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko7eef3392016-05-25 12:49:49 +01001719 if (!out->WriteFully(field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001720 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001721 return false; \
1722 } \
1723 size_ ## field += field->size(); \
1724 relative_offset += alignment_padding + field->size(); \
1725 DCHECK_OFFSET(); \
1726 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001727
Ian Rogers848871b2013-08-05 10:56:33 -07001728 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001729 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001730 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001731 DO_TRAMPOLINE(quick_resolution_trampoline_);
1732 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1733 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001734 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001735 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001736}
1737
Ian Rogers3d504072014-03-01 09:16:49 -08001738size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001739 const size_t file_offset,
1740 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001741 #define VISIT(VisitorType) \
1742 do { \
1743 VisitorType visitor(this, out, file_offset, relative_offset); \
1744 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1745 return 0; \
1746 } \
1747 relative_offset = visitor.GetOffset(); \
1748 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001749
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001750 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001751
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001752 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001753
Vladimir Markob163bb72015-03-31 21:49:49 +01001754 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1755 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1756 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1757
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001758 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001759}
1760
Vladimir Marko944da602016-02-19 12:27:55 +00001761bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001762 // Get the elf file offset of the oat file.
1763 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1764 if (raw_file_offset == static_cast<off_t>(-1)) {
1765 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1766 return false;
1767 }
1768 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1769 return true;
1770}
1771
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001772bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1773 // Read the dex file header and perform minimal verification.
1774 uint8_t raw_header[sizeof(DexFile::Header)];
1775 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1776 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1777 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1778 return false;
1779 }
1780 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1781 return false;
1782 }
1783
1784 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1785 oat_dex_file->dex_file_size_ = header->file_size_;
1786 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1787 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1788 return true;
1789}
1790
1791bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1792 if (!DexFile::IsMagicValid(raw_header)) {
1793 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1794 return false;
1795 }
1796 if (!DexFile::IsVersionValid(raw_header)) {
1797 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1798 return false;
1799 }
1800 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1801 if (header->file_size_ < sizeof(DexFile::Header)) {
1802 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1803 << " File: " << location;
1804 return false;
1805 }
1806 return true;
1807}
1808
1809bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1810 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1811
1812 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001813 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001814 return false;
1815 }
1816
1817 // Write dex files.
1818 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1819 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1820 return false;
1821 }
1822 }
1823
1824 // Close sources.
1825 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1826 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1827 }
1828 zipped_dex_files_.clear();
1829 zip_archives_.clear();
1830 raw_dex_files_.clear();
1831 return true;
1832}
1833
1834bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1835 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1836 return false;
1837 }
1838 if (oat_dex_file->source_.IsZipEntry()) {
1839 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1840 return false;
1841 }
1842 } else if (oat_dex_file->source_.IsRawFile()) {
1843 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1844 return false;
1845 }
1846 } else {
1847 DCHECK(oat_dex_file->source_.IsRawData());
1848 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1849 return false;
1850 }
1851 }
1852
1853 // Update current size and account for the written data.
1854 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1855 size_ += oat_dex_file->dex_file_size_;
1856 size_dex_file_ += oat_dex_file->dex_file_size_;
1857 return true;
1858}
1859
1860bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1861 // Dex files are required to be 4 byte aligned.
1862 size_t original_offset = size_;
1863 size_t offset = RoundUp(original_offset, 4);
1864 size_dex_file_alignment_ += offset - original_offset;
1865
1866 // Seek to the start of the dex file and flush any pending operations in the stream.
1867 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1868 uint32_t start_offset = oat_data_offset_ + offset;
1869 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1870 if (actual_offset != static_cast<off_t>(start_offset)) {
1871 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1872 << " Expected: " << start_offset
1873 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1874 return false;
1875 }
1876 if (!out->Flush()) {
1877 PLOG(ERROR) << "Failed to flush before writing dex file."
1878 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1879 return false;
1880 }
1881 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1882 if (actual_offset != static_cast<off_t>(start_offset)) {
1883 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1884 << " Expected: " << start_offset
1885 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1886 return false;
1887 }
1888
1889 size_ = offset;
1890 oat_dex_file->dex_file_offset_ = offset;
1891 return true;
1892}
1893
1894bool OatWriter::WriteDexFile(OutputStream* rodata,
1895 File* file,
1896 OatDexFile* oat_dex_file,
1897 ZipEntry* dex_file) {
1898 size_t start_offset = oat_data_offset_ + size_;
1899 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1900
1901 // Extract the dex file and get the extracted size.
1902 std::string error_msg;
1903 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1904 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1905 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1906 return false;
1907 }
1908 if (file->Flush() != 0) {
1909 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1910 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1911 return false;
1912 }
1913 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1914 if (extracted_end == static_cast<off_t>(-1)) {
1915 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1916 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1917 return false;
1918 }
1919 if (extracted_end < static_cast<off_t>(start_offset)) {
1920 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1921 << " Start: " << start_offset
1922 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1923 return false;
1924 }
1925 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1926 if (extracted_size < sizeof(DexFile::Header)) {
1927 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1928 << extracted_size << " File: " << oat_dex_file->GetLocation();
1929 return false;
1930 }
1931
1932 // Read the dex file header and extract required data to OatDexFile.
1933 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1934 if (actual_offset != static_cast<off_t>(start_offset)) {
1935 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1936 << " Expected: " << start_offset
1937 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1938 return false;
1939 }
1940 if (!ReadDexFileHeader(file, oat_dex_file)) {
1941 return false;
1942 }
1943 if (extracted_size < oat_dex_file->dex_file_size_) {
1944 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1945 << " file size from header: " << oat_dex_file->dex_file_size_
1946 << " File: " << oat_dex_file->GetLocation();
1947 return false;
1948 }
1949
1950 // Override the checksum from header with the CRC from ZIP entry.
1951 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1952
1953 // Seek both file and stream to the end offset.
1954 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1955 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1956 if (actual_offset != static_cast<off_t>(end_offset)) {
1957 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1958 << " Expected: " << end_offset
1959 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1960 return false;
1961 }
1962 actual_offset = rodata->Seek(end_offset, kSeekSet);
1963 if (actual_offset != static_cast<off_t>(end_offset)) {
1964 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1965 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1966 return false;
1967 }
1968 if (!rodata->Flush()) {
1969 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1970 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1971 return false;
1972 }
1973
1974 // If we extracted more than the size specified in the header, truncate the file.
1975 if (extracted_size > oat_dex_file->dex_file_size_) {
1976 if (file->SetLength(end_offset) != 0) {
1977 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1978 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1979 return false;
1980 }
1981 }
1982
1983 return true;
1984}
1985
1986bool OatWriter::WriteDexFile(OutputStream* rodata,
1987 File* file,
1988 OatDexFile* oat_dex_file,
1989 File* dex_file) {
1990 size_t start_offset = oat_data_offset_ + size_;
1991 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1992
1993 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
1994 if (input_offset != static_cast<off_t>(0)) {
1995 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
1996 << " Expected: 0"
1997 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1998 return false;
1999 }
2000 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
2001 return false;
2002 }
2003
2004 // Copy the input dex file using sendfile().
2005 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
2006 PLOG(ERROR) << "Failed to copy dex file to oat file."
2007 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2008 return false;
2009 }
2010 if (file->Flush() != 0) {
2011 PLOG(ERROR) << "Failed to flush dex file."
2012 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2013 return false;
2014 }
2015
2016 // Check file position and seek the stream to the end offset.
2017 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
2018 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
2019 if (actual_offset != static_cast<off_t>(end_offset)) {
2020 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
2021 << " Expected: " << end_offset
2022 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2023 return false;
2024 }
2025 actual_offset = rodata->Seek(end_offset, kSeekSet);
2026 if (actual_offset != static_cast<off_t>(end_offset)) {
2027 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2028 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2029 return false;
2030 }
2031 if (!rodata->Flush()) {
2032 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2033 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2034 return false;
2035 }
2036
2037 return true;
2038}
2039
2040bool OatWriter::WriteDexFile(OutputStream* rodata,
2041 OatDexFile* oat_dex_file,
2042 const uint8_t* dex_file) {
2043 // Note: The raw data has already been checked to contain the header
2044 // and all the data that the header specifies as the file size.
2045 DCHECK(dex_file != nullptr);
2046 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2047 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2048
Vladimir Marko7eef3392016-05-25 12:49:49 +01002049 if (!rodata->WriteFully(dex_file, header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002050 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2051 << " to " << rodata->GetLocation();
2052 return false;
2053 }
2054 if (!rodata->Flush()) {
2055 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2056 << " File: " << oat_dex_file->GetLocation();
2057 return false;
2058 }
2059
2060 // Update dex file size and resize class offsets in the OatDexFile.
2061 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2062 oat_dex_file->dex_file_size_ = header->file_size_;
2063 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2064 return true;
2065}
2066
2067bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2068 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2069
2070 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2071 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2072 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2073 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2074 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2075 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2076 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2077 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2078 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2079 return false;
2080 }
2081
2082 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2083 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2084
2085 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2086 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2087
2088 // Write OatDexFile.
2089 if (!oat_dex_file->Write(this, rodata)) {
2090 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2091 return false;
2092 }
2093 }
2094
2095 return true;
2096}
2097
2098bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2099 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2100
2101 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2102 if (file->SetLength(new_length) != 0) {
2103 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2104 << "File: " << file->GetPath();
2105 return false;
2106 }
2107 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2108 if (actual_offset != static_cast<off_t>(new_length)) {
2109 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2110 << " Actual: " << actual_offset << " Expected: " << new_length
2111 << " File: " << rodata->GetLocation();
2112 return false;
2113 }
2114 if (!rodata->Flush()) {
2115 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2116 << " File: " << rodata->GetLocation();
2117 return false;
2118 }
2119 return true;
2120}
2121
2122bool OatWriter::OpenDexFiles(
2123 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002124 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002125 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2126 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2127 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2128
2129 if (oat_dex_files_.empty()) {
2130 // Nothing to do.
2131 return true;
2132 }
2133
2134 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2135 size_t length = size_ - map_offset;
2136 std::string error_msg;
2137 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2138 PROT_READ | PROT_WRITE,
2139 MAP_SHARED,
2140 file->Fd(),
2141 oat_data_offset_ + map_offset,
2142 /* low_4gb */ false,
2143 file->GetPath().c_str(),
2144 &error_msg));
2145 if (dex_files_map == nullptr) {
2146 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2147 << " error: " << error_msg;
2148 return false;
2149 }
2150 std::vector<std::unique_ptr<const DexFile>> dex_files;
2151 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2152 // Make sure no one messed with input files while we were copying data.
2153 // At the very least we need consistent file size and number of class definitions.
2154 const uint8_t* raw_dex_file =
2155 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2156 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2157 // Note: ValidateDexFileHeader() already logged an error message.
2158 LOG(ERROR) << "Failed to verify written dex file header!"
2159 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2160 << " ~ " << static_cast<const void*>(raw_dex_file);
2161 return false;
2162 }
2163 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2164 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2165 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2166 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2167 << " Output: " << file->GetPath();
2168 return false;
2169 }
2170 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2171 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2172 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2173 << " Output: " << file->GetPath();
2174 return false;
2175 }
2176
2177 // Now, open the dex file.
2178 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2179 oat_dex_file.dex_file_size_,
2180 oat_dex_file.GetLocation(),
2181 oat_dex_file.dex_file_location_checksum_,
2182 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002183 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002184 &error_msg));
2185 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002186 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2187 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002188 return false;
2189 }
2190 }
2191
2192 *opened_dex_files_map = std::move(dex_files_map);
2193 *opened_dex_files = std::move(dex_files);
2194 return true;
2195}
2196
2197bool OatWriter::WriteTypeLookupTables(
2198 MemMap* opened_dex_files_map,
2199 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2200 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2201
2202 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2203 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2204 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2205 if (oat_dex_file->lookup_table_offset_ != 0u) {
2206 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2207 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2208 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2209 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2210 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2211 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2212 }
2213 }
2214
2215 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2216 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2217 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2218 return false;
2219 }
2220
2221 return true;
2222}
2223
Vladimir Markof4da6752014-08-01 19:04:18 +01002224bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2225 static const uint8_t kPadding[] = {
2226 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2227 };
2228 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
Vladimir Marko7eef3392016-05-25 12:49:49 +01002229 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002230 return false;
2231 }
2232 size_code_alignment_ += aligned_code_delta;
2233 return true;
2234}
2235
Vladimir Marko944da602016-02-19 12:27:55 +00002236void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2237 DCHECK(dex_files_ != nullptr);
2238 DCHECK(relative_patcher_ != nullptr);
2239 DCHECK_NE(oat_data_offset_, 0u);
2240 if (image_writer_ != nullptr && !dex_files_->empty()) {
2241 // The oat data begin may not be initialized yet but the oat file offset is ready.
2242 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2243 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2244 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002245 }
2246}
2247
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002248OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2249 DexFileSource source,
2250 CreateTypeLookupTable create_type_lookup_table)
2251 : source_(source),
2252 create_type_lookup_table_(create_type_lookup_table),
2253 dex_file_size_(0),
2254 offset_(0),
2255 dex_file_location_size_(strlen(dex_file_location)),
2256 dex_file_location_data_(dex_file_location),
2257 dex_file_location_checksum_(0u),
2258 dex_file_offset_(0u),
2259 class_offsets_offset_(0u),
2260 lookup_table_offset_(0u),
2261 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002262}
2263
2264size_t OatWriter::OatDexFile::SizeOf() const {
2265 return sizeof(dex_file_location_size_)
2266 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002267 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002268 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002269 + sizeof(class_offsets_offset_)
2270 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002271}
2272
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002273void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2274 DCHECK_EQ(lookup_table_offset_, 0u);
2275 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2276 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2277 if (table_size != 0u) {
2278 // Type tables are required to be 4 byte aligned.
2279 size_t original_offset = oat_writer->size_;
2280 size_t offset = RoundUp(original_offset, 4);
2281 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2282 lookup_table_offset_ = offset;
2283 oat_writer->size_ = offset + table_size;
2284 oat_writer->size_oat_lookup_table_ += table_size;
2285 }
2286 }
2287}
2288
2289void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2290 DCHECK_EQ(class_offsets_offset_, 0u);
2291 if (!class_offsets_.empty()) {
2292 // Class offsets are required to be 4 byte aligned.
2293 size_t original_offset = oat_writer->size_;
2294 size_t offset = RoundUp(original_offset, 4);
2295 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2296 class_offsets_offset_ = offset;
2297 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2298 }
2299}
2300
2301bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2302 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002303 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002304
Vladimir Marko7eef3392016-05-25 12:49:49 +01002305 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002306 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002307 return false;
2308 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002309 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002310
Vladimir Marko7eef3392016-05-25 12:49:49 +01002311 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002312 PLOG(ERROR) << "Failed to write dex file location data 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_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002316
Vladimir Marko7eef3392016-05-25 12:49:49 +01002317 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002318 PLOG(ERROR) << "Failed to write dex file location checksum 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_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002322
Vladimir Marko7eef3392016-05-25 12:49:49 +01002323 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002324 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002325 return false;
2326 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002327 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002328
Vladimir Marko7eef3392016-05-25 12:49:49 +01002329 if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002330 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2331 return false;
2332 }
2333 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2334
Vladimir Marko7eef3392016-05-25 12:49:49 +01002335 if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002336 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2337 return false;
2338 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002339 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002340
2341 return true;
2342}
2343
2344bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko7eef3392016-05-25 12:49:49 +01002345 if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002346 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2347 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002348 return false;
2349 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002350 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002351 return true;
2352}
2353
Brian Carlstromba150c32013-08-27 17:31:03 -07002354OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002355 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002356 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002357 mirror::Class::Status status)
2358 : compiled_methods_(compiled_methods) {
2359 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002360 CHECK_LE(num_non_null_compiled_methods, num_methods);
2361
Brian Carlstrom265091e2013-01-30 14:08:26 -08002362 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002363 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2364
2365 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2366 // apply when there are 0 methods, we just arbitrarily say that 0
2367 // methods means kOatClassNoneCompiled and that we won't use
2368 // kOatClassAllCompiled unless there is at least one compiled
2369 // method. This means in an interpretter only system, we can assert
2370 // that all classes are kOatClassNoneCompiled.
2371 if (num_non_null_compiled_methods == 0) {
2372 type_ = kOatClassNoneCompiled;
2373 } else if (num_non_null_compiled_methods == num_methods) {
2374 type_ = kOatClassAllCompiled;
2375 } else {
2376 type_ = kOatClassSomeCompiled;
2377 }
2378
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002379 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002380 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002381 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002382
2383 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2384 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002385 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002386 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2387 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2388 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2389 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002390 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002391 method_bitmap_size_ = 0;
2392 }
2393
2394 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002395 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002396 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002397 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2398 } else {
2399 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2400 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2401 if (type_ == kOatClassSomeCompiled) {
2402 method_bitmap_->SetBit(i);
2403 }
2404 }
2405 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002406}
2407
Brian Carlstrom265091e2013-01-30 14:08:26 -08002408size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2409 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002410 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2411 if (method_offset == 0) {
2412 return 0;
2413 }
2414 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002415}
2416
2417size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2418 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002419 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002420}
2421
2422size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002423 return sizeof(status_)
2424 + sizeof(type_)
2425 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2426 + method_bitmap_size_
2427 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002428}
2429
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002430bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002431 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002432 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002433 DCHECK_OFFSET_();
Vladimir Marko7eef3392016-05-25 12:49:49 +01002434 if (!out->WriteFully(&status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002435 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002436 return false;
2437 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002438 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002439
Vladimir Marko7eef3392016-05-25 12:49:49 +01002440 if (!out->WriteFully(&type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002441 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002442 return false;
2443 }
2444 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002445
Brian Carlstromba150c32013-08-27 17:31:03 -07002446 if (method_bitmap_size_ != 0) {
2447 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko7eef3392016-05-25 12:49:49 +01002448 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002449 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002450 return false;
2451 }
2452 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002453
Vladimir Marko7eef3392016-05-25 12:49:49 +01002454 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002455 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002456 return false;
2457 }
2458 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2459 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002460
Vladimir Marko7eef3392016-05-25 12:49:49 +01002461 if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002462 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002463 return false;
2464 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002465 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002466 return true;
2467}
2468
Brian Carlstrome24fa612011-09-29 00:53:55 -07002469} // namespace art