blob: cf1c1146e98714a43b570faaf76e671fa88aa291 [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
66} // anonymous namespace
67
68// Defines the location of the raw dex file to write.
69class OatWriter::DexFileSource {
70 public:
71 explicit DexFileSource(ZipEntry* zip_entry)
72 : type_(kZipEntry), source_(zip_entry) {
73 DCHECK(source_ != nullptr);
74 }
75
76 explicit DexFileSource(File* raw_file)
77 : type_(kRawFile), source_(raw_file) {
78 DCHECK(source_ != nullptr);
79 }
80
81 explicit DexFileSource(const uint8_t* dex_file)
82 : type_(kRawData), source_(dex_file) {
83 DCHECK(source_ != nullptr);
84 }
85
86 bool IsZipEntry() const { return type_ == kZipEntry; }
87 bool IsRawFile() const { return type_ == kRawFile; }
88 bool IsRawData() const { return type_ == kRawData; }
89
90 ZipEntry* GetZipEntry() const {
91 DCHECK(IsZipEntry());
92 DCHECK(source_ != nullptr);
93 return static_cast<ZipEntry*>(const_cast<void*>(source_));
94 }
95
96 File* GetRawFile() const {
97 DCHECK(IsRawFile());
98 DCHECK(source_ != nullptr);
99 return static_cast<File*>(const_cast<void*>(source_));
100 }
101
102 const uint8_t* GetRawData() const {
103 DCHECK(IsRawData());
104 DCHECK(source_ != nullptr);
105 return static_cast<const uint8_t*>(source_);
106 }
107
108 void Clear() {
109 type_ = kNone;
110 source_ = nullptr;
111 }
112
113 private:
114 enum Type {
115 kNone,
116 kZipEntry,
117 kRawFile,
118 kRawData,
119 };
120
121 Type type_;
122 const void* source_;
123};
124
Vladimir Marko49b0f452015-12-10 13:49:19 +0000125class OatWriter::OatClass {
126 public:
127 OatClass(size_t offset,
128 const dchecked_vector<CompiledMethod*>& compiled_methods,
129 uint32_t num_non_null_compiled_methods,
130 mirror::Class::Status status);
131 OatClass(OatClass&& src) = default;
132 size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
133 size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
134 size_t SizeOf() const;
135 bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
136
137 CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
138 return compiled_methods_[class_def_method_index];
139 }
140
141 // Offset of start of OatClass from beginning of OatHeader. It is
142 // used to validate file position when writing.
143 size_t offset_;
144
145 // CompiledMethods for each class_def_method_index, or null if no method is available.
146 dchecked_vector<CompiledMethod*> compiled_methods_;
147
148 // Offset from OatClass::offset_ to the OatMethodOffsets for the
149 // class_def_method_index. If 0, it means the corresponding
150 // CompiledMethod entry in OatClass::compiled_methods_ should be
151 // null and that the OatClass::type_ should be kOatClassBitmap.
152 dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
153
154 // Data to write.
155
156 static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
157 int16_t status_;
158
159 static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
160 uint16_t type_;
161
162 uint32_t method_bitmap_size_;
163
164 // bit vector indexed by ClassDef method index. When
165 // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
166 // method has an OatMethodOffsets in methods_offsets_, otherwise
167 // the entry was ommited to save space. If OatClassType::type_ is
168 // not is kOatClassBitmap, the bitmap will be null.
169 std::unique_ptr<BitVector> method_bitmap_;
170
171 // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
172 // present in the OatClass. Note that some may be missing if
173 // OatClass::compiled_methods_ contains null values (and
174 // oat_method_offsets_offsets_from_oat_class_ should contain 0
175 // values in this case).
176 dchecked_vector<OatMethodOffsets> method_offsets_;
177 dchecked_vector<OatQuickMethodHeader> method_headers_;
178
179 private:
180 size_t GetMethodOffsetsRawSize() const {
181 return method_offsets_.size() * sizeof(method_offsets_[0]);
182 }
183
184 DISALLOW_COPY_AND_ASSIGN(OatClass);
185};
186
187class OatWriter::OatDexFile {
188 public:
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000189 OatDexFile(const char* dex_file_location,
190 DexFileSource source,
191 CreateTypeLookupTable create_type_lookup_table);
Vladimir Marko49b0f452015-12-10 13:49:19 +0000192 OatDexFile(OatDexFile&& src) = default;
193
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000194 const char* GetLocation() const {
195 return dex_file_location_data_;
196 }
197
198 void ReserveTypeLookupTable(OatWriter* oat_writer);
199 void ReserveClassOffsets(OatWriter* oat_writer);
200
Vladimir Marko49b0f452015-12-10 13:49:19 +0000201 size_t SizeOf() const;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000202 bool Write(OatWriter* oat_writer, OutputStream* out) const;
203 bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
204
205 // The source of the dex file.
206 DexFileSource source_;
207
208 // Whether to create the type lookup table.
209 CreateTypeLookupTable create_type_lookup_table_;
210
211 // Dex file size. Initialized when writing the dex file.
212 size_t dex_file_size_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000213
214 // Offset of start of OatDexFile from beginning of OatHeader. It is
215 // used to validate file position when writing.
216 size_t offset_;
217
218 // Data to write.
219 uint32_t dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000220 const char* dex_file_location_data_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000221 uint32_t dex_file_location_checksum_;
222 uint32_t dex_file_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000223 uint32_t class_offsets_offset_;
Vladimir Marko49b0f452015-12-10 13:49:19 +0000224 uint32_t lookup_table_offset_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000225
226 // Data to write to a separate section.
Vladimir Marko49b0f452015-12-10 13:49:19 +0000227 dchecked_vector<uint32_t> class_offsets_;
228
229 private:
230 size_t GetClassOffsetsRawSize() const {
231 return class_offsets_.size() * sizeof(class_offsets_[0]);
232 }
233
234 DISALLOW_COPY_AND_ASSIGN(OatDexFile);
235};
236
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100237#define DCHECK_OFFSET() \
238 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
239 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
240
241#define DCHECK_OFFSET_() \
242 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
243 << "file_offset=" << file_offset << " offset_=" << offset_
244
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000245OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
246 : write_state_(WriteState::kAddingDexFileSources),
247 timings_(timings),
248 raw_dex_files_(),
249 zip_archives_(),
250 zipped_dex_files_(),
251 zipped_dex_file_locations_(),
252 compiler_driver_(nullptr),
253 image_writer_(nullptr),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800254 compiling_boot_image_(compiling_boot_image),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000255 dex_files_(nullptr),
Vladimir Markof4da6752014-08-01 19:04:18 +0100256 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000257 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100258 oat_data_offset_(0u),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700259 oat_header_(nullptr),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700260 size_dex_file_alignment_(0),
261 size_executable_offset_alignment_(0),
262 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700263 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700264 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700265 size_interpreter_to_interpreter_bridge_(0),
266 size_interpreter_to_compiled_code_bridge_(0),
267 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800268 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700269 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700270 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700271 size_quick_to_interpreter_bridge_(0),
272 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100273 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700274 size_code_(0),
275 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100276 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100277 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700278 size_vmap_table_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700279 size_oat_dex_file_location_size_(0),
280 size_oat_dex_file_location_data_(0),
281 size_oat_dex_file_location_checksum_(0),
282 size_oat_dex_file_offset_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000283 size_oat_dex_file_class_offsets_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000284 size_oat_dex_file_lookup_table_offset_(0),
Vladimir Marko49b0f452015-12-10 13:49:19 +0000285 size_oat_lookup_table_alignment_(0),
286 size_oat_lookup_table_(0),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000287 size_oat_class_offsets_alignment_(0),
288 size_oat_class_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700289 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700290 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700291 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100292 size_oat_class_method_offsets_(0),
Vladimir Marko944da602016-02-19 12:27:55 +0000293 relative_patcher_(nullptr),
294 absolute_patch_locations_() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000295}
296
297bool OatWriter::AddDexFileSource(const char* filename,
298 const char* location,
299 CreateTypeLookupTable create_type_lookup_table) {
300 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
301 uint32_t magic;
302 std::string error_msg;
303 ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
304 if (fd.get() == -1) {
305 PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
306 return false;
307 } else if (IsDexMagic(magic)) {
308 // The file is open for reading, not writing, so it's OK to let the File destructor
309 // close it without checking for explicit Close(), so pass checkUsage = false.
310 raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
311 oat_dex_files_.emplace_back(location,
312 DexFileSource(raw_dex_files_.back().get()),
313 create_type_lookup_table);
314 } else if (IsZipMagic(magic)) {
315 if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
316 return false;
317 }
318 } else {
319 LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
320 return false;
321 }
322 return true;
323}
324
325// Add dex file source(s) from a zip file specified by a file handle.
326bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
327 const char* location,
328 CreateTypeLookupTable create_type_lookup_table) {
329 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
330 std::string error_msg;
331 zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
332 ZipArchive* zip_archive = zip_archives_.back().get();
333 if (zip_archive == nullptr) {
334 LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
335 << error_msg;
336 return false;
337 }
338 for (size_t i = 0; ; ++i) {
339 std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
340 std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
341 if (entry == nullptr) {
342 break;
343 }
344 zipped_dex_files_.push_back(std::move(entry));
345 zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
346 const char* full_location = zipped_dex_file_locations_.back().c_str();
347 oat_dex_files_.emplace_back(full_location,
348 DexFileSource(zipped_dex_files_.back().get()),
349 create_type_lookup_table);
350 }
351 if (zipped_dex_file_locations_.empty()) {
352 LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
353 return false;
354 }
355 return true;
356}
357
358// Add dex file source from raw memory.
359bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
360 const char* location,
361 uint32_t location_checksum,
362 CreateTypeLookupTable create_type_lookup_table) {
363 DCHECK(write_state_ == WriteState::kAddingDexFileSources);
364 if (data.size() < sizeof(DexFile::Header)) {
365 LOG(ERROR) << "Provided data is shorter than dex file header. size: "
366 << data.size() << " File: " << location;
367 return false;
368 }
369 if (!ValidateDexFileHeader(data.data(), location)) {
370 return false;
371 }
372 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
373 if (data.size() < header->file_size_) {
374 LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
375 << " file size from header: " << header->file_size_ << " File: " << location;
376 return false;
377 }
378
379 oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
380 oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
381 return true;
382}
383
384dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
385 dchecked_vector<const char*> locations;
386 locations.reserve(oat_dex_files_.size());
387 for (const OatDexFile& oat_dex_file : oat_dex_files_) {
388 locations.push_back(oat_dex_file.GetLocation());
389 }
390 return locations;
391}
392
393bool OatWriter::WriteAndOpenDexFiles(
394 OutputStream* rodata,
395 File* file,
396 InstructionSet instruction_set,
397 const InstructionSetFeatures* instruction_set_features,
398 SafeMap<std::string, std::string>* key_value_store,
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800399 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000400 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
401 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
402 CHECK(write_state_ == WriteState::kAddingDexFileSources);
403
404 size_t offset = InitOatHeader(instruction_set,
405 instruction_set_features,
406 dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
407 key_value_store);
408 offset = InitOatDexFiles(offset);
409 size_ = offset;
410
411 std::unique_ptr<MemMap> dex_files_map;
412 std::vector<std::unique_ptr<const DexFile>> dex_files;
413 if (!WriteDexFiles(rodata, file)) {
414 return false;
415 }
416 // Reserve space for type lookup tables and update type_lookup_table_offset_.
417 for (OatDexFile& oat_dex_file : oat_dex_files_) {
418 oat_dex_file.ReserveTypeLookupTable(this);
419 }
420 size_t size_after_type_lookup_tables = size_;
421 // Reserve space for class offsets and update class_offsets_offset_.
422 for (OatDexFile& oat_dex_file : oat_dex_files_) {
423 oat_dex_file.ReserveClassOffsets(this);
424 }
425 if (!WriteOatDexFiles(rodata) ||
426 !ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
Andreas Gampe3a2bd292016-01-26 17:23:47 -0800427 !OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000428 !WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
429 return false;
430 }
431
432 *opened_dex_files_map = std::move(dex_files_map);
433 *opened_dex_files = std::move(dex_files);
434 write_state_ = WriteState::kPrepareLayout;
435 return true;
436}
437
438void OatWriter::PrepareLayout(const CompilerDriver* compiler,
439 ImageWriter* image_writer,
Vladimir Marko944da602016-02-19 12:27:55 +0000440 const std::vector<const DexFile*>& dex_files,
441 linker::MultiOatRelativePatcher* relative_patcher) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000442 CHECK(write_state_ == WriteState::kPrepareLayout);
443
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 compiler_driver_ = compiler;
445 image_writer_ = image_writer;
Vladimir Marko944da602016-02-19 12:27:55 +0000446 dex_files_ = &dex_files;
447 relative_patcher_ = relative_patcher;
448 SetMultiOatRelativePatcherAdjustment();
449
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000450 if (compiling_boot_image_) {
451 CHECK(image_writer_ != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800452 }
Vladimir Markob163bb72015-03-31 21:49:49 +0100453 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000454 CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +0100455
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000456 uint32_t offset = size_;
Ian Rogersca368cb2013-11-15 15:52:08 -0800457 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000458 TimingLogger::ScopedTiming split("InitOatClasses", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800459 offset = InitOatClasses(offset);
460 }
461 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000462 TimingLogger::ScopedTiming split("InitOatMaps", timings_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100463 offset = InitOatMaps(offset);
464 }
465 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000466 TimingLogger::ScopedTiming split("InitOatCode", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800467 offset = InitOatCode(offset);
468 }
469 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000470 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
Ian Rogersca368cb2013-11-15 15:52:08 -0800471 offset = InitOatCodeDexFiles(offset);
472 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700473 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700474
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800475 if (!HasBootImage()) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100476 // Allocate space for app dex cache arrays in the .bss section.
477 size_t bss_start = RoundUp(size_, kPageSize);
478 size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
479 bss_size_ = 0u;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480 for (const DexFile* dex_file : *dex_files_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100481 dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
482 DexCacheArraysLayout layout(pointer_size, dex_file);
483 bss_size_ += layout.Size();
484 }
485 }
486
Brian Carlstrome24fa612011-09-29 00:53:55 -0700487 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800488 if (compiling_boot_image_) {
489 CHECK_EQ(image_writer_ != nullptr,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000490 oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800491 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492
493 write_state_ = WriteState::kWriteRoData;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700494}
495
Ian Rogers0571d352011-11-03 19:51:38 -0700496OatWriter::~OatWriter() {
Ian Rogers0571d352011-11-03 19:51:38 -0700497}
498
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100499class OatWriter::DexMethodVisitor {
500 public:
501 DexMethodVisitor(OatWriter* writer, size_t offset)
502 : writer_(writer),
503 offset_(offset),
504 dex_file_(nullptr),
505 class_def_index_(DexFile::kDexNoIndex) {
506 }
507
508 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
509 DCHECK(dex_file_ == nullptr);
510 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
511 dex_file_ = dex_file;
512 class_def_index_ = class_def_index;
513 return true;
514 }
515
516 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
517
518 virtual bool EndClass() {
519 if (kIsDebugBuild) {
520 dex_file_ = nullptr;
521 class_def_index_ = DexFile::kDexNoIndex;
522 }
523 return true;
524 }
525
526 size_t GetOffset() const {
527 return offset_;
528 }
529
530 protected:
531 virtual ~DexMethodVisitor() { }
532
533 OatWriter* const writer_;
534
535 // The offset is usually advanced for each visited method by the derived class.
536 size_t offset_;
537
538 // The dex file and class def index are set in StartClass().
539 const DexFile* dex_file_;
540 size_t class_def_index_;
541};
542
543class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
544 public:
545 OatDexMethodVisitor(OatWriter* writer, size_t offset)
546 : DexMethodVisitor(writer, offset),
547 oat_class_index_(0u),
548 method_offsets_index_(0u) {
549 }
550
551 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
552 DexMethodVisitor::StartClass(dex_file, class_def_index);
553 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
554 method_offsets_index_ = 0u;
555 return true;
556 }
557
558 bool EndClass() {
559 ++oat_class_index_;
560 return DexMethodVisitor::EndClass();
561 }
562
563 protected:
564 size_t oat_class_index_;
565 size_t method_offsets_index_;
566};
567
568class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
569 public:
570 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
571 : DexMethodVisitor(writer, offset),
572 compiled_methods_(),
573 num_non_null_compiled_methods_(0u) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000574 size_t num_classes = 0u;
575 for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
576 num_classes += oat_dex_file.class_offsets_.size();
577 }
578 writer_->oat_classes_.reserve(num_classes);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100579 compiled_methods_.reserve(256u);
580 }
581
582 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
583 DexMethodVisitor::StartClass(dex_file, class_def_index);
584 compiled_methods_.clear();
585 num_non_null_compiled_methods_ = 0u;
586 return true;
587 }
588
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300589 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
590 const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100591 // Fill in the compiled_methods_ array for methods that have a
592 // CompiledMethod. We track the number of non-null entries in
593 // num_non_null_compiled_methods_ since we only want to allocate
594 // OatMethodOffsets for the compiled methods.
595 uint32_t method_idx = it.GetMemberIndex();
596 CompiledMethod* compiled_method =
597 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
598 compiled_methods_.push_back(compiled_method);
599 if (compiled_method != nullptr) {
600 ++num_non_null_compiled_methods_;
601 }
602 return true;
603 }
604
605 bool EndClass() {
606 ClassReference class_ref(dex_file_, class_def_index_);
607 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
608 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700609 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100610 status = compiled_class->GetStatus();
611 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
612 status = mirror::Class::kStatusError;
613 } else {
614 status = mirror::Class::kStatusNotReady;
615 }
616
Vladimir Marko49b0f452015-12-10 13:49:19 +0000617 writer_->oat_classes_.emplace_back(offset_,
618 compiled_methods_,
619 num_non_null_compiled_methods_,
620 status);
621 offset_ += writer_->oat_classes_.back().SizeOf();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100622 return DexMethodVisitor::EndClass();
623 }
624
625 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +0000626 dchecked_vector<CompiledMethod*> compiled_methods_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100627 size_t num_non_null_compiled_methods_;
628};
629
630class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
631 public:
632 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
David Srbecky009e2a62015-04-15 02:46:30 +0100633 : OatDexMethodVisitor(writer, offset),
David Srbecky009e2a62015-04-15 02:46:30 +0100634 debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100635 writer_->absolute_patch_locations_.reserve(
Vladimir Markof4da6752014-08-01 19:04:18 +0100636 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
637 }
638
639 bool EndClass() {
640 OatDexMethodVisitor::EndClass();
641 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko71b0ddf2015-04-02 19:45:06 +0100642 offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100643 }
644 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100645 }
646
647 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700648 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000649 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100650 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
651
652 if (compiled_method != nullptr) {
653 // Derived from CompiledMethod.
654 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100655
Vladimir Marko35831e82015-09-11 11:59:18 +0100656 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
657 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800658 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800659
David Srbecky009e2a62015-04-15 02:46:30 +0100660 // Deduplicate code arrays if we are not producing debuggable code.
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100661 bool deduped = true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800662 MethodReference method_ref(dex_file_, it.GetMemberIndex());
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000663 if (debuggable_) {
Vladimir Marko944da602016-02-19 12:27:55 +0000664 quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
665 if (quick_code_offset != 0u) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800666 // Duplicate methods, we want the same code for both of them so that the oat writer puts
667 // the same code in both ArtMethods so that we do not get different oat code at runtime.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800668 } else {
669 quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100670 deduped = false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800671 }
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000672 } else {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100673 quick_code_offset = dedupe_map_.GetOrCreate(
674 compiled_method,
675 [this, &deduped, compiled_method, &it, thumb_offset]() {
676 deduped = false;
677 return NewQuickCodeOffset(compiled_method, it, thumb_offset);
678 });
Elliott Hughes956af0f2014-12-11 14:34:28 -0800679 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100680
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100681 if (code_size != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +0000682 if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100683 // TODO: Should this be a hard failure?
684 LOG(WARNING) << "Multiple definitions of "
685 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
Vladimir Marko944da602016-02-19 12:27:55 +0000686 << " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
687 << " " << quick_code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100688 } else {
Vladimir Marko944da602016-02-19 12:27:55 +0000689 writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100690 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800691 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100692
Elliott Hughes956af0f2014-12-11 14:34:28 -0800693 // Update quick method header.
694 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
695 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
Elliott Hughes956af0f2014-12-11 14:34:28 -0800696 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100697 // If we don't have quick code, then we must have a vmap, as that is how the dex2dex
698 // compiler records its transformations.
Vladimir Marko35831e82015-09-11 11:59:18 +0100699 DCHECK(!quick_code.empty() || vmap_table_offset != 0);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800700 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
701 // to 0-offset and we need to adjust it by code_offset.
702 uint32_t code_offset = quick_code_offset - thumb_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100703 if (vmap_table_offset != 0u && code_offset != 0u) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800704 vmap_table_offset += code_offset;
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100705 DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
Elliott Hughes956af0f2014-12-11 14:34:28 -0800706 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800707 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
708 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
709 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100710 *method_header = OatQuickMethodHeader(vmap_table_offset,
711 frame_size_in_bytes,
712 core_spill_mask,
713 fp_spill_mask,
714 code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100715
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +0000716 if (!deduped) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800717 // Update offsets. (Checksum is updated when writing.)
718 offset_ += sizeof(*method_header); // Method header is prepended before code.
719 offset_ += code_size;
720 // Record absolute patch locations.
721 if (!compiled_method->GetPatches().empty()) {
722 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
723 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000724 if (!patch.IsPcRelative()) {
David Srbeckyf8980872015-05-22 17:04:47 +0100725 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100726 }
727 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100728 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800729 }
Alex Light78382fa2014-06-06 15:45:32 -0700730
David Srbecky91cc06c2016-03-07 16:13:58 +0000731 const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
David Srbecky197160d2016-03-07 17:33:57 +0000732 // Exclude quickened dex methods (code_size == 0) since they have no native code.
733 if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
734 bool has_code_info = method_header->IsOptimized();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800735 // Record debug information for this function if we are doing that.
David Srbecky09c2a6b2016-03-11 17:11:44 +0000736 debug::MethodDebugInfo info = debug::MethodDebugInfo();
737 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +0000738 info.dex_file = dex_file_;
739 info.class_def_index = class_def_index_;
740 info.dex_method_index = it.GetMemberIndex();
741 info.access_flags = it.GetMethodAccessFlags();
742 info.code_item = it.GetMethodCodeItem();
743 info.isa = compiled_method->GetInstructionSet();
744 info.deduped = deduped;
745 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
746 info.is_optimized = method_header->IsOptimized();
747 info.is_code_address_text_relative = true;
748 info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
749 info.code_size = code_size;
750 info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
751 info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
752 info.cfi = compiled_method->GetCFIInfo();
753 writer_->method_info_.push_back(info);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100754 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755
756 if (kIsDebugBuild) {
757 // We expect GC maps except when the class hasn't been verified or the method is native.
758 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
759 ClassReference class_ref(dex_file_, class_def_index_);
760 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
761 mirror::Class::Status status;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700762 if (compiled_class != nullptr) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100763 status = compiled_class->GetStatus();
764 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
765 status = mirror::Class::kStatusError;
766 } else {
767 status = mirror::Class::kStatusNotReady;
768 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100769 }
770
771 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
772 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
773 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100774 ++method_offsets_index_;
775 }
776
777 return true;
778 }
779
780 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000781 struct CodeOffsetsKeyComparator {
782 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
Vladimir Marko35831e82015-09-11 11:59:18 +0100783 // Code is deduplicated by CompilerDriver, compare only data pointers.
784 if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
785 return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000786 }
787 // If the code is the same, all other fields are likely to be the same as well.
Vladimir Marko35831e82015-09-11 11:59:18 +0100788 if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
789 return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000790 }
Vladimir Marko35831e82015-09-11 11:59:18 +0100791 if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
792 return lhs->GetPatches().data() < rhs->GetPatches().data();
Vladimir Marko20f85592015-03-19 10:07:02 +0000793 }
794 return false;
795 }
796 };
797
David Srbecky009e2a62015-04-15 02:46:30 +0100798 uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
799 const ClassDataItemIterator& it,
800 uint32_t thumb_offset) {
801 offset_ = writer_->relative_patcher_->ReserveSpace(
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100802 offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
David Srbecky009e2a62015-04-15 02:46:30 +0100803 offset_ = compiled_method->AlignCode(offset_);
804 DCHECK_ALIGNED_PARAM(offset_,
805 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
806 return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
807 }
808
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100809 // Deduplication is already done on a pointer basis by the compiler driver,
810 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100811 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
David Srbecky2f6cdb02015-04-11 00:17:53 +0100812
David Srbecky009e2a62015-04-15 02:46:30 +0100813 // Cache of compiler's --debuggable option.
814 const bool debuggable_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100815};
816
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100817class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
818 public:
819 InitMapMethodVisitor(OatWriter* writer, size_t offset)
820 : OatDexMethodVisitor(writer, offset) {
821 }
822
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700823 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700824 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000825 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100826 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
827
828 if (compiled_method != nullptr) {
829 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100830 DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100831
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100832 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
Vladimir Marko35831e82015-09-11 11:59:18 +0100833 uint32_t map_size = map.size() * sizeof(map[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100834 if (map_size != 0u) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +0100835 size_t offset = dedupe_map_.GetOrCreate(
836 map.data(),
837 [this, map_size]() {
838 uint32_t new_offset = offset_;
839 offset_ += map_size;
840 return new_offset;
841 });
842 // Code offset is not initialized yet, so set the map offset to 0u-offset.
843 DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
844 oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100845 }
846 ++method_offsets_index_;
847 }
848
849 return true;
850 }
851
852 private:
853 // Deduplication is already done on a pointer basis by the compiler driver,
854 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko35831e82015-09-11 11:59:18 +0100855 SafeMap<const uint8_t*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100856};
857
858class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
859 public:
860 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800861 : OatDexMethodVisitor(writer, offset),
862 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100863 }
864
865 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700866 SHARED_REQUIRES(Locks::mutator_lock_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800867 const DexFile::TypeId& type_id =
868 dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
869 const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
870 // Skip methods that are not in the image.
871 if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
872 return true;
873 }
874
Vladimir Marko49b0f452015-12-10 13:49:19 +0000875 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100876 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
877
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800878 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100879 if (compiled_method != nullptr) {
880 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
881 offsets = oat_class->method_offsets_[method_offsets_index_];
882 ++method_offsets_index_;
883 }
884
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100885 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100886 // Unchecked as we hold mutator_lock_ on entry.
887 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800888 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700889 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
890 Thread::Current(), *dex_file_)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800891 ArtMethod* method;
892 if (writer_->HasBootImage()) {
893 const InvokeType invoke_type = it.GetMethodInvokeType(
894 dex_file_->GetClassDef(class_def_index_));
895 method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
896 *dex_file_,
897 it.GetMemberIndex(),
898 dex_cache,
899 ScopedNullHandle<mirror::ClassLoader>(),
900 nullptr,
901 invoke_type);
902 if (method == nullptr) {
903 LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
904 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
905 soa.Self()->AssertPendingException();
906 mirror::Throwable* exc = soa.Self()->GetException();
907 std::string dump = exc->Dump();
908 LOG(FATAL) << dump;
909 UNREACHABLE();
910 }
911 } else {
912 // Should already have been resolved by the compiler, just peek into the dex cache.
913 // It may not be resolved if the class failed to verify, in this case, don't set the
914 // entrypoint. This is not fatal since the dex cache will contain a resolution method.
915 method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
Andreas Gamped9efea62014-07-21 22:56:08 -0700916 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800917 if (method != nullptr &&
918 compiled_method != nullptr &&
919 compiled_method->GetQuickCode().size() != 0) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100920 method->SetEntryPointFromQuickCompiledCodePtrSize(
921 reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
922 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923
924 return true;
925 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800926
927 protected:
928 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100929};
930
931class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
932 public:
933 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100934 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100935 : OatDexMethodVisitor(writer, relative_offset),
936 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100937 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100938 soa_(Thread::Current()),
939 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100940 class_linker_(Runtime::Current()->GetClassLinker()),
941 dex_cache_(nullptr) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100942 patched_code_.reserve(16 * KB);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800943 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100944 // If we're creating the image, the address space must be ready so that we can apply patches.
945 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
Vladimir Markof4da6752014-08-01 19:04:18 +0100946 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100947 }
948
Vladimir Markof4da6752014-08-01 19:04:18 +0100949 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100950 }
951
952 bool StartClass(const DexFile* dex_file, size_t class_def_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700953 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100954 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
955 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700956 dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000957 DCHECK(dex_cache_ != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100958 }
959 return true;
960 }
961
Mathieu Chartier90443472015-07-16 20:32:27 -0700962 bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100963 bool result = OatDexMethodVisitor::EndClass();
964 if (oat_class_index_ == writer_->oat_classes_.size()) {
965 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +0000966 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100967 if (UNLIKELY(offset_ == 0u)) {
968 PLOG(ERROR) << "Failed to write final relative call thunks";
969 result = false;
970 }
971 }
972 return result;
973 }
974
975 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
Mathieu Chartier90443472015-07-16 20:32:27 -0700976 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000977 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100978 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
979
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700980 // No thread suspension since dex_cache_ that may get invalidated if that occurs.
981 ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700982 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100983 size_t file_offset = file_offset_;
984 OutputStream* out = out_;
985
Vladimir Marko35831e82015-09-11 11:59:18 +0100986 ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
987 uint32_t code_size = quick_code.size() * sizeof(uint8_t);
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000988
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100989 // Deduplicate code arrays.
990 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
991 if (method_offsets.code_offset_ > offset_) {
992 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
993 if (offset_ == 0u) {
994 ReportWriteFailure("relative call thunk", it);
995 return false;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +0000996 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +0100997 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
998 uint32_t aligned_code_delta = aligned_offset - offset_;
999 if (aligned_code_delta != 0) {
1000 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1001 ReportWriteFailure("code alignment padding", it);
1002 return false;
1003 }
1004 offset_ += aligned_code_delta;
1005 DCHECK_OFFSET_();
1006 }
1007 DCHECK_ALIGNED_PARAM(offset_,
1008 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1009 DCHECK_EQ(method_offsets.code_offset_,
1010 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1011 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1012 const OatQuickMethodHeader& method_header =
1013 oat_class->method_headers_[method_offsets_index_];
Vladimir Marko49b0f452015-12-10 13:49:19 +00001014 if (!writer_->WriteData(out, &method_header, sizeof(method_header))) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001015 ReportWriteFailure("method header", it);
1016 return false;
1017 }
1018 writer_->size_method_header_ += sizeof(method_header);
1019 offset_ += sizeof(method_header);
Nicolas Geoffrayed6195a2015-07-13 17:02:30 +00001020 DCHECK_OFFSET_();
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001021
1022 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko35831e82015-09-11 11:59:18 +01001023 patched_code_.assign(quick_code.begin(), quick_code.end());
1024 quick_code = ArrayRef<const uint8_t>(patched_code_);
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001025 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001026 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001027 switch (patch.GetType()) {
1028 case LinkerPatch::Type::kCallRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001029 // NOTE: Relative calls across oat files are not supported.
1030 uint32_t target_offset = GetTargetOffset(patch);
1031 writer_->relative_patcher_->PatchCall(&patched_code_,
1032 literal_offset,
1033 offset_ + literal_offset,
1034 target_offset);
1035 break;
1036 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001037 case LinkerPatch::Type::kDexCacheArray: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001038 uint32_t target_offset = GetDexCacheOffset(patch);
1039 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1040 patch,
1041 offset_ + literal_offset,
1042 target_offset);
1043 break;
1044 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001045 case LinkerPatch::Type::kStringRelative: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001046 uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1047 writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1048 patch,
1049 offset_ + literal_offset,
1050 target_offset);
1051 break;
1052 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001053 case LinkerPatch::Type::kCall: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001054 uint32_t target_offset = GetTargetOffset(patch);
1055 PatchCodeAddress(&patched_code_, literal_offset, target_offset);
1056 break;
1057 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001058 case LinkerPatch::Type::kMethod: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001059 ArtMethod* method = GetTargetMethod(patch);
1060 PatchMethodAddress(&patched_code_, literal_offset, method);
1061 break;
1062 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001063 case LinkerPatch::Type::kString: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001064 mirror::String* string = GetTargetString(patch);
1065 PatchObjectAddress(&patched_code_, literal_offset, string);
1066 break;
1067 }
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001068 case LinkerPatch::Type::kType: {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001069 mirror::Class* type = GetTargetType(patch);
1070 PatchObjectAddress(&patched_code_, literal_offset, type);
1071 break;
1072 }
1073 default: {
Vladimir Markodb8e62d2016-03-30 16:30:21 +01001074 DCHECK_EQ(patch.GetType(), LinkerPatch::Type::kRecordPosition);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001075 break;
1076 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001077 }
1078 }
1079 }
1080
Vladimir Marko49b0f452015-12-10 13:49:19 +00001081 if (!writer_->WriteData(out, quick_code.data(), code_size)) {
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001082 ReportWriteFailure("method code", it);
1083 return false;
1084 }
1085 writer_->size_code_ += code_size;
1086 offset_ += code_size;
Nicolas Geoffrayf0758792015-07-13 11:56:00 +00001087 }
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +01001088 DCHECK_OFFSET_();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001089 ++method_offsets_index_;
1090 }
1091
1092 return true;
1093 }
1094
1095 private:
1096 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001097 const size_t file_offset_;
1098 const ScopedObjectAccess soa_;
1099 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001100 ClassLinker* const class_linker_;
1101 mirror::DexCache* dex_cache_;
1102 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001103
1104 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1105 PLOG(ERROR) << "Failed to write " << what << " for "
1106 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1107 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001108
Mathieu Chartiere401d142015-04-22 13:56:20 -07001109 ArtMethod* GetTargetMethod(const LinkerPatch& patch)
Mathieu Chartier90443472015-07-16 20:32:27 -07001110 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001111 MethodReference ref = patch.TargetMethod();
1112 mirror::DexCache* dex_cache =
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001113 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1114 Thread::Current(), *ref.dex_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001115 ArtMethod* method = dex_cache->GetResolvedMethod(
1116 ref.dex_method_index, class_linker_->GetImagePointerSize());
Vladimir Markof4da6752014-08-01 19:04:18 +01001117 CHECK(method != nullptr);
1118 return method;
1119 }
1120
Mathieu Chartier90443472015-07-16 20:32:27 -07001121 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko944da602016-02-19 12:27:55 +00001122 uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1123 // If there's no new compiled code, either we're compiling an app and the target method
1124 // is in the boot image, or we need to point to the correct trampoline.
Vladimir Markof4da6752014-08-01 19:04:18 +01001125 if (UNLIKELY(target_offset == 0)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001126 ArtMethod* target = GetTargetMethod(patch);
Vladimir Markof4da6752014-08-01 19:04:18 +01001127 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001128 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1129 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1130 if (oat_code_offset != 0) {
Vladimir Marko944da602016-02-19 12:27:55 +00001131 DCHECK(!writer_->HasBootImage());
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001132 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1133 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1134 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1135 target_offset = PointerToLowMemUInt32(oat_code_offset);
1136 } else {
1137 target_offset = target->IsNative()
1138 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1139 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1140 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001141 }
1142 return target_offset;
1143 }
1144
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001145 mirror::Class* GetTargetType(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001146 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001147 ? dex_cache_
1148 : class_linker_->FindDexCache(Thread::Current(), *patch.TargetTypeDexFile());
Vladimir Markof4da6752014-08-01 19:04:18 +01001149 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1150 CHECK(type != nullptr);
1151 return type;
1152 }
1153
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001154 mirror::String* GetTargetString(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
1155 mirror::String* string = dex_cache_->GetResolvedString(patch.TargetStringIndex());
1156 DCHECK(string != nullptr);
1157 DCHECK(writer_->HasBootImage() ||
1158 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(string));
1159 return string;
1160 }
1161
Mathieu Chartier90443472015-07-16 20:32:27 -07001162 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001163 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001164 uintptr_t element = writer_->image_writer_->GetDexCacheArrayElementImageAddress<uintptr_t>(
1165 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1166 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1167 uintptr_t oat_data = writer_->image_writer_->GetOatDataBegin(oat_index);
Vladimir Marko05792b92015-08-03 11:56:49 +01001168 return element - oat_data;
Vladimir Marko20f85592015-03-19 10:07:02 +00001169 } else {
Vladimir Marko09d09432015-09-08 13:47:48 +01001170 size_t start = writer_->dex_cache_arrays_offsets_.Get(patch.TargetDexCacheDexFile());
1171 return start + patch.TargetDexCacheElementOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001172 }
1173 }
1174
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001175 uint32_t GetTargetObjectOffset(mirror::Object* object) SHARED_REQUIRES(Locks::mutator_lock_) {
1176 DCHECK(writer_->HasBootImage());
1177 object = writer_->image_writer_->GetImageAddress(object);
1178 size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1179 uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1180 // TODO: Clean up offset types. The target offset must be treated as signed.
1181 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object) - oat_data_begin);
1182 }
1183
Vladimir Markof4da6752014-08-01 19:04:18 +01001184 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
Mathieu Chartier90443472015-07-16 20:32:27 -07001185 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001186 if (writer_->HasBootImage()) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001187 object = writer_->image_writer_->GetImageAddress(object);
Vladimir Marko09d09432015-09-08 13:47:48 +01001188 } else {
1189 // NOTE: We're using linker patches for app->boot references when the image can
1190 // be relocated and therefore we need to emit .oat_patches. We're not using this
1191 // for app->app references, so check that the object is in the image space.
1192 DCHECK(Runtime::Current()->GetHeap()->FindSpaceFromObject(object, false)->IsImageSpace());
Vladimir Markof4da6752014-08-01 19:04:18 +01001193 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001194 // Note: We only patch targeting Objects in image which is in the low 4gb.
Vladimir Markof4da6752014-08-01 19:04:18 +01001195 uint32_t address = PointerToLowMemUInt32(object);
1196 DCHECK_LE(offset + 4, code->size());
1197 uint8_t* data = &(*code)[offset];
1198 data[0] = address & 0xffu;
1199 data[1] = (address >> 8) & 0xffu;
1200 data[2] = (address >> 16) & 0xffu;
1201 data[3] = (address >> 24) & 0xffu;
1202 }
1203
Mathieu Chartiere401d142015-04-22 13:56:20 -07001204 void PatchMethodAddress(std::vector<uint8_t>* code, uint32_t offset, ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -07001205 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001206 if (writer_->HasBootImage()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001207 method = writer_->image_writer_->GetImageMethodAddress(method);
Vladimir Marko09d09432015-09-08 13:47:48 +01001208 } else if (kIsDebugBuild) {
1209 // NOTE: We're using linker patches for app->boot references when the image can
1210 // be relocated and therefore we need to emit .oat_patches. We're not using this
1211 // for app->app references, so check that the method is an image method.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001212 std::vector<gc::space::ImageSpace*> image_spaces =
1213 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1214 bool contains_method = false;
1215 for (gc::space::ImageSpace* image_space : image_spaces) {
1216 size_t method_offset = reinterpret_cast<const uint8_t*>(method) - image_space->Begin();
1217 contains_method |=
1218 image_space->GetImageHeader().GetMethodsSection().Contains(method_offset);
1219 }
1220 CHECK(contains_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001221 }
Vladimir Marko09d09432015-09-08 13:47:48 +01001222 // Note: We only patch targeting ArtMethods in image which is in the low 4gb.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001223 uint32_t address = PointerToLowMemUInt32(method);
1224 DCHECK_LE(offset + 4, code->size());
1225 uint8_t* data = &(*code)[offset];
1226 data[0] = address & 0xffu;
1227 data[1] = (address >> 8) & 0xffu;
1228 data[2] = (address >> 16) & 0xffu;
1229 data[3] = (address >> 24) & 0xffu;
1230 }
1231
Vladimir Markof4da6752014-08-01 19:04:18 +01001232 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
Mathieu Chartier90443472015-07-16 20:32:27 -07001233 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Marko09d09432015-09-08 13:47:48 +01001234 uint32_t address = target_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001235 if (writer_->HasBootImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00001236 size_t oat_index = writer_->image_writer_->GetOatIndexForDexCache(dex_cache_);
1237 // TODO: Clean up offset types.
1238 // The target_offset must be treated as signed for cross-oat patching.
1239 const void* target = reinterpret_cast<const void*>(
1240 writer_->image_writer_->GetOatDataBegin(oat_index) +
1241 static_cast<int32_t>(target_offset));
1242 address = PointerToLowMemUInt32(target);
Vladimir Marko09d09432015-09-08 13:47:48 +01001243 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001244 DCHECK_LE(offset + 4, code->size());
1245 uint8_t* data = &(*code)[offset];
1246 data[0] = address & 0xffu;
1247 data[1] = (address >> 8) & 0xffu;
1248 data[2] = (address >> 16) & 0xffu;
1249 data[3] = (address >> 24) & 0xffu;
1250 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001251};
1252
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001253class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1254 public:
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001255 WriteMapMethodVisitor(OatWriter* writer,
1256 OutputStream* out,
1257 const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001258 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001259 : OatDexMethodVisitor(writer, relative_offset),
1260 out_(out),
1261 file_offset_(file_offset) {
1262 }
1263
1264 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001265 OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001266 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1267
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001268 if (compiled_method != nullptr) { // ie. not an abstract method
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001269 size_t file_offset = file_offset_;
1270 OutputStream* out = out_;
1271
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001272 uint32_t map_offset = oat_class->method_headers_[method_offsets_index_].vmap_table_offset_;
1273 uint32_t code_offset = oat_class->method_offsets_[method_offsets_index_].code_offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001274 ++method_offsets_index_;
1275
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001276 DCHECK((compiled_method->GetVmapTable().size() == 0u && map_offset == 0u) ||
1277 (compiled_method->GetVmapTable().size() != 0u && map_offset != 0u))
1278 << compiled_method->GetVmapTable().size() << " " << map_offset << " "
1279 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1280
1281 if (map_offset != 0u) {
1282 // Transform map_offset to actual oat data offset.
1283 map_offset = (code_offset - compiled_method->CodeDelta()) - map_offset;
1284 DCHECK_NE(map_offset, 0u);
1285 DCHECK_LE(map_offset, offset_) << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1286
1287 ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1288 size_t map_size = map.size() * sizeof(map[0]);
1289 if (map_offset == offset_) {
1290 // Write deduplicated map (code info for Optimizing or transformation info for dex2dex).
1291 if (UNLIKELY(!writer_->WriteData(out, map.data(), map_size))) {
1292 ReportWriteFailure(it);
1293 return false;
1294 }
1295 offset_ += map_size;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001296 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001297 }
1298 DCHECK_OFFSET_();
1299 }
1300
1301 return true;
1302 }
1303
1304 private:
1305 OutputStream* const out_;
1306 size_t const file_offset_;
1307
1308 void ReportWriteFailure(const ClassDataItemIterator& it) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001309 PLOG(ERROR) << "Failed to write map for "
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001310 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1311 }
1312};
1313
1314// Visit all methods from all classes in all dex files with the specified visitor.
1315bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1316 for (const DexFile* dex_file : *dex_files_) {
1317 const size_t class_def_count = dex_file->NumClassDefs();
1318 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1319 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1320 return false;
1321 }
1322 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001323 const uint8_t* class_data = dex_file->GetClassData(class_def);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001324 if (class_data != nullptr) { // ie not an empty class, such as a marker interface
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001325 ClassDataItemIterator it(*dex_file, class_data);
1326 while (it.HasNextStaticField()) {
1327 it.Next();
1328 }
1329 while (it.HasNextInstanceField()) {
1330 it.Next();
1331 }
1332 size_t class_def_method_index = 0u;
1333 while (it.HasNextDirectMethod()) {
1334 if (!visitor->VisitMethod(class_def_method_index, it)) {
1335 return false;
1336 }
1337 ++class_def_method_index;
1338 it.Next();
1339 }
1340 while (it.HasNextVirtualMethod()) {
1341 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1342 return false;
1343 }
1344 ++class_def_method_index;
1345 it.Next();
1346 }
1347 }
1348 if (UNLIKELY(!visitor->EndClass())) {
1349 return false;
1350 }
1351 }
1352 }
1353 return true;
1354}
1355
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001356size_t OatWriter::InitOatHeader(InstructionSet instruction_set,
1357 const InstructionSetFeatures* instruction_set_features,
1358 uint32_t num_dex_files,
1359 SafeMap<std::string, std::string>* key_value_store) {
1360 TimingLogger::ScopedTiming split("InitOatHeader", timings_);
1361 oat_header_.reset(OatHeader::Create(instruction_set,
1362 instruction_set_features,
1363 num_dex_files,
1364 key_value_store));
1365 size_oat_header_ += sizeof(OatHeader);
1366 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001367 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001368}
1369
1370size_t OatWriter::InitOatDexFiles(size_t offset) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001371 TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
1372 // Initialize offsets of dex files.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001373 for (OatDexFile& oat_dex_file : oat_dex_files_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001374 oat_dex_file.offset_ = offset;
1375 offset += oat_dex_file.SizeOf();
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001376 }
1377 return offset;
1378}
1379
Brian Carlstrom389efb02012-01-11 12:06:26 -08001380size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001381 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001382 InitOatClassesMethodVisitor visitor(this, offset);
1383 bool success = VisitDexMethods(&visitor);
1384 CHECK(success);
1385 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001386
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001387 // Update oat_dex_files_.
1388 auto oat_class_it = oat_classes_.begin();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001389 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1390 for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001391 DCHECK(oat_class_it != oat_classes_.end());
Vladimir Marko49b0f452015-12-10 13:49:19 +00001392 class_offset = oat_class_it->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001393 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001394 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001395 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001396 CHECK(oat_class_it == oat_classes_.end());
1397
1398 return offset;
1399}
1400
1401size_t OatWriter::InitOatMaps(size_t offset) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001402 InitMapMethodVisitor visitor(this, offset);
1403 bool success = VisitDexMethods(&visitor);
1404 DCHECK(success);
1405 offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001406
Brian Carlstrome24fa612011-09-29 00:53:55 -07001407 return offset;
1408}
1409
1410size_t OatWriter::InitOatCode(size_t offset) {
1411 // calculate the offsets within OatHeader to executable code
1412 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001413 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001414 // required to be on a new page boundary
1415 offset = RoundUp(offset, kPageSize);
1416 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001417 size_executable_offset_alignment_ = offset - old_offset;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001418 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001419 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001420
Ian Rogers848871b2013-08-05 10:56:33 -07001421 #define DO_TRAMPOLINE(field, fn_name) \
1422 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001423 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1424 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001425 field.reset(compiler_driver_->Create ## fn_name()); \
1426 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001427
Ian Rogers848871b2013-08-05 10:56:33 -07001428 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001429 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001430 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001431 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1432 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001433
Ian Rogers848871b2013-08-05 10:56:33 -07001434 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001435 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001436 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1437 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1438 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001439 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001440 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001441 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001442 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001443 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001444 return offset;
1445}
1446
1447size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001448 #define VISIT(VisitorType) \
1449 do { \
1450 VisitorType visitor(this, offset); \
1451 bool success = VisitDexMethods(&visitor); \
1452 DCHECK(success); \
1453 offset = visitor.GetOffset(); \
1454 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001455
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001456 VISIT(InitCodeMethodVisitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001457 if (HasImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001458 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001459 }
Logan Chien8b977d32012-02-21 19:14:55 +08001460
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001461 #undef VISIT
1462
Brian Carlstrome24fa612011-09-29 00:53:55 -07001463 return offset;
1464}
1465
David Srbeckybc90fd02015-04-22 19:40:27 +01001466bool OatWriter::WriteRodata(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001467 CHECK(write_state_ == WriteState::kWriteRoData);
1468
1469 if (!WriteClassOffsets(out)) {
1470 LOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001471 return false;
1472 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001473
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001474 if (!WriteClasses(out)) {
1475 LOG(ERROR) << "Failed to write classes to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001476 return false;
1477 }
1478
Vladimir Markof4da6752014-08-01 19:04:18 +01001479 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001480 if (tables_end_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001481 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1482 return false;
1483 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001484 size_t file_offset = oat_data_offset_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001485 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001486 relative_offset = WriteMaps(out, file_offset, relative_offset);
1487 if (relative_offset == 0) {
1488 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1489 return false;
1490 }
1491
David Srbeckybc90fd02015-04-22 19:40:27 +01001492 // Write padding.
1493 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
1494 relative_offset += size_executable_offset_alignment_;
1495 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
1496 size_t expected_file_offset = file_offset + relative_offset;
1497 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
1498 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
1499 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
1500 return 0;
1501 }
1502 DCHECK_OFFSET();
1503
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001504 write_state_ = WriteState::kWriteText;
David Srbeckybc90fd02015-04-22 19:40:27 +01001505 return true;
1506}
1507
1508bool OatWriter::WriteCode(OutputStream* out) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001509 CHECK(write_state_ == WriteState::kWriteText);
1510
Vladimir Marko944da602016-02-19 12:27:55 +00001511 SetMultiOatRelativePatcherAdjustment();
1512
David Srbeckybc90fd02015-04-22 19:40:27 +01001513 const size_t file_offset = oat_data_offset_;
1514 size_t relative_offset = oat_header_->GetExecutableOffset();
1515 DCHECK_OFFSET();
1516
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001517 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001518 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001519 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001520 return false;
1521 }
1522
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001523 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1524 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001525 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001526 return false;
1527 }
1528
Vladimir Markof4da6752014-08-01 19:04:18 +01001529 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001530 if (oat_end_file_offset == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001531 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1532 return false;
1533 }
1534
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001535 if (kIsDebugBuild) {
1536 uint32_t size_total = 0;
1537 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001538 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001539 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001540
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001541 DO_STAT(size_dex_file_alignment_);
1542 DO_STAT(size_executable_offset_alignment_);
1543 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001544 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001545 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001546 DO_STAT(size_interpreter_to_interpreter_bridge_);
1547 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1548 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001549 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001550 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001551 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001552 DO_STAT(size_quick_to_interpreter_bridge_);
1553 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001554 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001555 DO_STAT(size_code_);
1556 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001557 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001558 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001559 DO_STAT(size_vmap_table_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001560 DO_STAT(size_oat_dex_file_location_size_);
1561 DO_STAT(size_oat_dex_file_location_data_);
1562 DO_STAT(size_oat_dex_file_location_checksum_);
1563 DO_STAT(size_oat_dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001564 DO_STAT(size_oat_dex_file_class_offsets_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001565 DO_STAT(size_oat_dex_file_lookup_table_offset_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001566 DO_STAT(size_oat_lookup_table_alignment_);
1567 DO_STAT(size_oat_lookup_table_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001568 DO_STAT(size_oat_class_offsets_alignment_);
1569 DO_STAT(size_oat_class_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001570 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001571 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001572 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001573 DO_STAT(size_oat_class_method_offsets_);
1574 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001575
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001576 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001577 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001578 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001579 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001580
Vladimir Markof4da6752014-08-01 19:04:18 +01001581 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001582 CHECK_EQ(size_, relative_offset);
1583
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001584 write_state_ = WriteState::kWriteHeader;
1585 return true;
1586}
1587
1588bool OatWriter::WriteHeader(OutputStream* out,
1589 uint32_t image_file_location_oat_checksum,
1590 uintptr_t image_file_location_oat_begin,
1591 int32_t image_patch_delta) {
1592 CHECK(write_state_ == WriteState::kWriteHeader);
1593
1594 oat_header_->SetImageFileLocationOatChecksum(image_file_location_oat_checksum);
1595 oat_header_->SetImageFileLocationOatDataBegin(image_file_location_oat_begin);
1596 if (compiler_driver_->IsBootImage()) {
1597 CHECK_EQ(image_patch_delta, 0);
1598 CHECK_EQ(oat_header_->GetImagePatchDelta(), 0);
1599 } else {
1600 CHECK_ALIGNED(image_patch_delta, kPageSize);
1601 oat_header_->SetImagePatchDelta(image_patch_delta);
1602 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001603 oat_header_->UpdateChecksumWithHeaderData();
1604
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001605 const size_t file_offset = oat_data_offset_;
1606
1607 off_t current_offset = out->Seek(0, kSeekCurrent);
1608 if (current_offset == static_cast<off_t>(-1)) {
1609 PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
1610 return false;
1611 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00001612 if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001613 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1614 return false;
1615 }
David Srbeckybc90fd02015-04-22 19:40:27 +01001616 DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001617
1618 // Flush all other data before writing the header.
1619 if (!out->Flush()) {
1620 PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
1621 return false;
1622 }
1623 // Write the header.
1624 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001625 if (!out->WriteFully(oat_header_.get(), header_size)) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001626 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1627 return false;
1628 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001629 // Flush the header data.
1630 if (!out->Flush()) {
1631 PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
Vladimir Markof4da6752014-08-01 19:04:18 +01001632 return false;
1633 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001634
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001635 if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
1636 PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
1637 return false;
1638 }
1639 DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
1640
1641 write_state_ = WriteState::kDone;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001642 return true;
1643}
1644
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001645bool OatWriter::WriteClassOffsets(OutputStream* out) {
1646 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1647 if (oat_dex_file.class_offsets_offset_ != 0u) {
1648 uint32_t expected_offset = oat_data_offset_ + oat_dex_file.class_offsets_offset_;
1649 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
1650 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1651 PLOG(ERROR) << "Failed to seek to oat class offsets section. Actual: " << actual_offset
1652 << " Expected: " << expected_offset << " File: " << oat_dex_file.GetLocation();
Vladimir Marko919f5532016-01-20 19:13:01 +00001653 return false;
1654 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001655 if (!oat_dex_file.WriteClassOffsets(this, out)) {
1656 return false;
1657 }
1658 }
1659 }
1660 return true;
1661}
1662
1663bool OatWriter::WriteClasses(OutputStream* out) {
1664 for (OatClass& oat_class : oat_classes_) {
1665 if (!oat_class.Write(this, out, oat_data_offset_)) {
1666 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
1667 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001668 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001669 }
1670 return true;
1671}
1672
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001673size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001674 size_t vmap_tables_offset = relative_offset;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01001675 WriteMapMethodVisitor visitor(this, out, file_offset, relative_offset);
1676 if (UNLIKELY(!VisitDexMethods(&visitor))) {
1677 return 0;
1678 }
1679 relative_offset = visitor.GetOffset();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001680 size_vmap_table_ = relative_offset - vmap_tables_offset;
1681
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001682 return relative_offset;
1683}
1684
1685size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001686 if (compiler_driver_->IsBootImage()) {
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001687 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001688
Ian Rogers848871b2013-08-05 10:56:33 -07001689 #define DO_TRAMPOLINE(field) \
1690 do { \
1691 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1692 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001693 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001694 size_trampoline_alignment_ += alignment_padding; \
Vladimir Marko49b0f452015-12-10 13:49:19 +00001695 if (!WriteData(out, field->data(), field->size())) { \
Ian Rogers3d504072014-03-01 09:16:49 -08001696 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001697 return false; \
1698 } \
1699 size_ ## field += field->size(); \
1700 relative_offset += alignment_padding + field->size(); \
1701 DCHECK_OFFSET(); \
1702 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001703
Ian Rogers848871b2013-08-05 10:56:33 -07001704 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001705 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001706 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001707 DO_TRAMPOLINE(quick_resolution_trampoline_);
1708 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1709 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001710 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001711 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001712}
1713
Ian Rogers3d504072014-03-01 09:16:49 -08001714size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001715 const size_t file_offset,
1716 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001717 #define VISIT(VisitorType) \
1718 do { \
1719 VisitorType visitor(this, out, file_offset, relative_offset); \
1720 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1721 return 0; \
1722 } \
1723 relative_offset = visitor.GetOffset(); \
1724 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001725
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001726 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001727
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001728 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001729
Vladimir Markob163bb72015-03-31 21:49:49 +01001730 size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
1731 size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
1732 size_misc_thunks_ += relative_patcher_->MiscThunksSize();
1733
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001734 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001735}
1736
Vladimir Marko944da602016-02-19 12:27:55 +00001737bool OatWriter::RecordOatDataOffset(OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001738 // Get the elf file offset of the oat file.
1739 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1740 if (raw_file_offset == static_cast<off_t>(-1)) {
1741 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1742 return false;
1743 }
1744 oat_data_offset_ = static_cast<size_t>(raw_file_offset);
1745 return true;
1746}
1747
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001748bool OatWriter::ReadDexFileHeader(File* file, OatDexFile* oat_dex_file) {
1749 // Read the dex file header and perform minimal verification.
1750 uint8_t raw_header[sizeof(DexFile::Header)];
1751 if (!file->ReadFully(&raw_header, sizeof(DexFile::Header))) {
1752 PLOG(ERROR) << "Failed to read dex file header. Actual: "
1753 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1754 return false;
1755 }
1756 if (!ValidateDexFileHeader(raw_header, oat_dex_file->GetLocation())) {
1757 return false;
1758 }
1759
1760 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1761 oat_dex_file->dex_file_size_ = header->file_size_;
1762 oat_dex_file->dex_file_location_checksum_ = header->checksum_;
1763 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
1764 return true;
1765}
1766
1767bool OatWriter::ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
1768 if (!DexFile::IsMagicValid(raw_header)) {
1769 LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
1770 return false;
1771 }
1772 if (!DexFile::IsVersionValid(raw_header)) {
1773 LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
1774 return false;
1775 }
1776 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
1777 if (header->file_size_ < sizeof(DexFile::Header)) {
1778 LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
1779 << " File: " << location;
1780 return false;
1781 }
1782 return true;
1783}
1784
1785bool OatWriter::WriteDexFiles(OutputStream* rodata, File* file) {
1786 TimingLogger::ScopedTiming split("WriteDexFiles", timings_);
1787
1788 // Get the elf file offset of the oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001789 if (!RecordOatDataOffset(rodata)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001790 return false;
1791 }
1792
1793 // Write dex files.
1794 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1795 if (!WriteDexFile(rodata, file, &oat_dex_file)) {
1796 return false;
1797 }
1798 }
1799
1800 // Close sources.
1801 for (OatDexFile& oat_dex_file : oat_dex_files_) {
1802 oat_dex_file.source_.Clear(); // Get rid of the reference, it's about to be invalidated.
1803 }
1804 zipped_dex_files_.clear();
1805 zip_archives_.clear();
1806 raw_dex_files_.clear();
1807 return true;
1808}
1809
1810bool OatWriter::WriteDexFile(OutputStream* rodata, File* file, OatDexFile* oat_dex_file) {
1811 if (!SeekToDexFile(rodata, file, oat_dex_file)) {
1812 return false;
1813 }
1814 if (oat_dex_file->source_.IsZipEntry()) {
1815 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
1816 return false;
1817 }
1818 } else if (oat_dex_file->source_.IsRawFile()) {
1819 if (!WriteDexFile(rodata, file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
1820 return false;
1821 }
1822 } else {
1823 DCHECK(oat_dex_file->source_.IsRawData());
1824 if (!WriteDexFile(rodata, oat_dex_file, oat_dex_file->source_.GetRawData())) {
1825 return false;
1826 }
1827 }
1828
1829 // Update current size and account for the written data.
1830 DCHECK_EQ(size_, oat_dex_file->dex_file_offset_);
1831 size_ += oat_dex_file->dex_file_size_;
1832 size_dex_file_ += oat_dex_file->dex_file_size_;
1833 return true;
1834}
1835
1836bool OatWriter::SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file) {
1837 // Dex files are required to be 4 byte aligned.
1838 size_t original_offset = size_;
1839 size_t offset = RoundUp(original_offset, 4);
1840 size_dex_file_alignment_ += offset - original_offset;
1841
1842 // Seek to the start of the dex file and flush any pending operations in the stream.
1843 // Verify that, after flushing the stream, the file is at the same offset as the stream.
1844 uint32_t start_offset = oat_data_offset_ + offset;
1845 off_t actual_offset = out->Seek(start_offset, kSeekSet);
1846 if (actual_offset != static_cast<off_t>(start_offset)) {
1847 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1848 << " Expected: " << start_offset
1849 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1850 return false;
1851 }
1852 if (!out->Flush()) {
1853 PLOG(ERROR) << "Failed to flush before writing dex file."
1854 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1855 return false;
1856 }
1857 actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1858 if (actual_offset != static_cast<off_t>(start_offset)) {
1859 PLOG(ERROR) << "Stream/file position mismatch! Actual: " << actual_offset
1860 << " Expected: " << start_offset
1861 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1862 return false;
1863 }
1864
1865 size_ = offset;
1866 oat_dex_file->dex_file_offset_ = offset;
1867 return true;
1868}
1869
1870bool OatWriter::WriteDexFile(OutputStream* rodata,
1871 File* file,
1872 OatDexFile* oat_dex_file,
1873 ZipEntry* dex_file) {
1874 size_t start_offset = oat_data_offset_ + size_;
1875 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1876
1877 // Extract the dex file and get the extracted size.
1878 std::string error_msg;
1879 if (!dex_file->ExtractToFile(*file, &error_msg)) {
1880 LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
1881 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1882 return false;
1883 }
1884 if (file->Flush() != 0) {
1885 PLOG(ERROR) << "Failed to flush dex file from ZIP entry."
1886 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1887 return false;
1888 }
1889 off_t extracted_end = lseek(file->Fd(), 0, SEEK_CUR);
1890 if (extracted_end == static_cast<off_t>(-1)) {
1891 PLOG(ERROR) << "Failed get end offset after writing dex file from ZIP entry."
1892 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1893 return false;
1894 }
1895 if (extracted_end < static_cast<off_t>(start_offset)) {
1896 LOG(ERROR) << "Dex file end position is before start position! End: " << extracted_end
1897 << " Start: " << start_offset
1898 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1899 return false;
1900 }
1901 uint64_t extracted_size = static_cast<uint64_t>(extracted_end - start_offset);
1902 if (extracted_size < sizeof(DexFile::Header)) {
1903 LOG(ERROR) << "Extracted dex file is shorter than dex file header. size: "
1904 << extracted_size << " File: " << oat_dex_file->GetLocation();
1905 return false;
1906 }
1907
1908 // Read the dex file header and extract required data to OatDexFile.
1909 off_t actual_offset = lseek(file->Fd(), start_offset, SEEK_SET);
1910 if (actual_offset != static_cast<off_t>(start_offset)) {
1911 PLOG(ERROR) << "Failed to seek back to dex file header. Actual: " << actual_offset
1912 << " Expected: " << start_offset
1913 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1914 return false;
1915 }
1916 if (!ReadDexFileHeader(file, oat_dex_file)) {
1917 return false;
1918 }
1919 if (extracted_size < oat_dex_file->dex_file_size_) {
1920 LOG(ERROR) << "Extracted truncated dex file. Extracted size: " << extracted_size
1921 << " file size from header: " << oat_dex_file->dex_file_size_
1922 << " File: " << oat_dex_file->GetLocation();
1923 return false;
1924 }
1925
1926 // Override the checksum from header with the CRC from ZIP entry.
1927 oat_dex_file->dex_file_location_checksum_ = dex_file->GetCrc32();
1928
1929 // Seek both file and stream to the end offset.
1930 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1931 actual_offset = lseek(file->Fd(), end_offset, SEEK_SET);
1932 if (actual_offset != static_cast<off_t>(end_offset)) {
1933 PLOG(ERROR) << "Failed to seek to end of dex file. Actual: " << actual_offset
1934 << " Expected: " << end_offset
1935 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1936 return false;
1937 }
1938 actual_offset = rodata->Seek(end_offset, kSeekSet);
1939 if (actual_offset != static_cast<off_t>(end_offset)) {
1940 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
1941 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
1942 return false;
1943 }
1944 if (!rodata->Flush()) {
1945 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
1946 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1947 return false;
1948 }
1949
1950 // If we extracted more than the size specified in the header, truncate the file.
1951 if (extracted_size > oat_dex_file->dex_file_size_) {
1952 if (file->SetLength(end_offset) != 0) {
1953 PLOG(ERROR) << "Failed to truncate excessive dex file length."
1954 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1955 return false;
1956 }
1957 }
1958
1959 return true;
1960}
1961
1962bool OatWriter::WriteDexFile(OutputStream* rodata,
1963 File* file,
1964 OatDexFile* oat_dex_file,
1965 File* dex_file) {
1966 size_t start_offset = oat_data_offset_ + size_;
1967 DCHECK_EQ(static_cast<off_t>(start_offset), rodata->Seek(0, kSeekCurrent));
1968
1969 off_t input_offset = lseek(dex_file->Fd(), 0, SEEK_SET);
1970 if (input_offset != static_cast<off_t>(0)) {
1971 PLOG(ERROR) << "Failed to seek to dex file header. Actual: " << input_offset
1972 << " Expected: 0"
1973 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1974 return false;
1975 }
1976 if (!ReadDexFileHeader(dex_file, oat_dex_file)) {
1977 return false;
1978 }
1979
1980 // Copy the input dex file using sendfile().
1981 if (!file->Copy(dex_file, 0, oat_dex_file->dex_file_size_)) {
1982 PLOG(ERROR) << "Failed to copy dex file to oat file."
1983 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1984 return false;
1985 }
1986 if (file->Flush() != 0) {
1987 PLOG(ERROR) << "Failed to flush dex file."
1988 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1989 return false;
1990 }
1991
1992 // Check file position and seek the stream to the end offset.
1993 size_t end_offset = start_offset + oat_dex_file->dex_file_size_;
1994 off_t actual_offset = lseek(file->Fd(), 0, SEEK_CUR);
1995 if (actual_offset != static_cast<off_t>(end_offset)) {
1996 PLOG(ERROR) << "Unexpected file position after copying dex file. Actual: " << actual_offset
1997 << " Expected: " << end_offset
1998 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
1999 return false;
2000 }
2001 actual_offset = rodata->Seek(end_offset, kSeekSet);
2002 if (actual_offset != static_cast<off_t>(end_offset)) {
2003 PLOG(ERROR) << "Failed to seek stream to end of dex file. Actual: " << actual_offset
2004 << " Expected: " << end_offset << " File: " << oat_dex_file->GetLocation();
2005 return false;
2006 }
2007 if (!rodata->Flush()) {
2008 PLOG(ERROR) << "Failed to flush stream after seeking over dex file."
2009 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
2010 return false;
2011 }
2012
2013 return true;
2014}
2015
2016bool OatWriter::WriteDexFile(OutputStream* rodata,
2017 OatDexFile* oat_dex_file,
2018 const uint8_t* dex_file) {
2019 // Note: The raw data has already been checked to contain the header
2020 // and all the data that the header specifies as the file size.
2021 DCHECK(dex_file != nullptr);
2022 DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
2023 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(dex_file);
2024
2025 if (!rodata->WriteFully(dex_file, header->file_size_)) {
2026 PLOG(ERROR) << "Failed to write dex file " << oat_dex_file->GetLocation()
2027 << " to " << rodata->GetLocation();
2028 return false;
2029 }
2030 if (!rodata->Flush()) {
2031 PLOG(ERROR) << "Failed to flush stream after writing dex file."
2032 << " File: " << oat_dex_file->GetLocation();
2033 return false;
2034 }
2035
2036 // Update dex file size and resize class offsets in the OatDexFile.
2037 // Note: For raw data, the checksum is passed directly to AddRawDexFileSource().
2038 oat_dex_file->dex_file_size_ = header->file_size_;
2039 oat_dex_file->class_offsets_.resize(header->class_defs_size_);
2040 return true;
2041}
2042
2043bool OatWriter::WriteOatDexFiles(OutputStream* rodata) {
2044 TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
2045
2046 // Seek to the start of OatDexFiles, i.e. to the end of the OatHeader. If there are
2047 // no OatDexFiles, no data is actually written to .rodata before WriteHeader() and
2048 // this Seek() ensures that we reserve the space for OatHeader in .rodata.
2049 DCHECK(oat_dex_files_.empty() || oat_dex_files_[0u].offset_ == oat_header_->GetHeaderSize());
2050 uint32_t expected_offset = oat_data_offset_ + oat_header_->GetHeaderSize();
2051 off_t actual_offset = rodata->Seek(expected_offset, kSeekSet);
2052 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
2053 PLOG(ERROR) << "Failed to seek to OatDexFile table section. Actual: " << actual_offset
2054 << " Expected: " << expected_offset << " File: " << rodata->GetLocation();
2055 return false;
2056 }
2057
2058 for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
2059 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2060
2061 DCHECK_EQ(oat_data_offset_ + oat_dex_file->offset_,
2062 static_cast<size_t>(rodata->Seek(0, kSeekCurrent)));
2063
2064 // Write OatDexFile.
2065 if (!oat_dex_file->Write(this, rodata)) {
2066 PLOG(ERROR) << "Failed to write oat dex information to " << rodata->GetLocation();
2067 return false;
2068 }
2069 }
2070
2071 return true;
2072}
2073
2074bool OatWriter::ExtendForTypeLookupTables(OutputStream* rodata, File* file, size_t offset) {
2075 TimingLogger::ScopedTiming split("ExtendForTypeLookupTables", timings_);
2076
2077 int64_t new_length = oat_data_offset_ + dchecked_integral_cast<int64_t>(offset);
2078 if (file->SetLength(new_length) != 0) {
2079 PLOG(ERROR) << "Failed to extend file for type lookup tables. new_length: " << new_length
2080 << "File: " << file->GetPath();
2081 return false;
2082 }
2083 off_t actual_offset = rodata->Seek(new_length, kSeekSet);
2084 if (actual_offset != static_cast<off_t>(new_length)) {
2085 PLOG(ERROR) << "Failed to seek stream after extending file for type lookup tables."
2086 << " Actual: " << actual_offset << " Expected: " << new_length
2087 << " File: " << rodata->GetLocation();
2088 return false;
2089 }
2090 if (!rodata->Flush()) {
2091 PLOG(ERROR) << "Failed to flush stream after extending for type lookup tables."
2092 << " File: " << rodata->GetLocation();
2093 return false;
2094 }
2095 return true;
2096}
2097
2098bool OatWriter::OpenDexFiles(
2099 File* file,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002100 bool verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002101 /*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
2102 /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
2103 TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
2104
2105 if (oat_dex_files_.empty()) {
2106 // Nothing to do.
2107 return true;
2108 }
2109
2110 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2111 size_t length = size_ - map_offset;
2112 std::string error_msg;
2113 std::unique_ptr<MemMap> dex_files_map(MemMap::MapFile(length,
2114 PROT_READ | PROT_WRITE,
2115 MAP_SHARED,
2116 file->Fd(),
2117 oat_data_offset_ + map_offset,
2118 /* low_4gb */ false,
2119 file->GetPath().c_str(),
2120 &error_msg));
2121 if (dex_files_map == nullptr) {
2122 LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
2123 << " error: " << error_msg;
2124 return false;
2125 }
2126 std::vector<std::unique_ptr<const DexFile>> dex_files;
2127 for (OatDexFile& oat_dex_file : oat_dex_files_) {
2128 // Make sure no one messed with input files while we were copying data.
2129 // At the very least we need consistent file size and number of class definitions.
2130 const uint8_t* raw_dex_file =
2131 dex_files_map->Begin() + oat_dex_file.dex_file_offset_ - map_offset;
2132 if (!ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation())) {
2133 // Note: ValidateDexFileHeader() already logged an error message.
2134 LOG(ERROR) << "Failed to verify written dex file header!"
2135 << " Output: " << file->GetPath() << " ~ " << std::hex << map_offset
2136 << " ~ " << static_cast<const void*>(raw_dex_file);
2137 return false;
2138 }
2139 const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
2140 if (header->file_size_ != oat_dex_file.dex_file_size_) {
2141 LOG(ERROR) << "File size mismatch in written dex file header! Expected: "
2142 << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
2143 << " Output: " << file->GetPath();
2144 return false;
2145 }
2146 if (header->class_defs_size_ != oat_dex_file.class_offsets_.size()) {
2147 LOG(ERROR) << "Class defs size mismatch in written dex file header! Expected: "
2148 << oat_dex_file.class_offsets_.size() << " Actual: " << header->class_defs_size_
2149 << " Output: " << file->GetPath();
2150 return false;
2151 }
2152
2153 // Now, open the dex file.
2154 dex_files.emplace_back(DexFile::Open(raw_dex_file,
2155 oat_dex_file.dex_file_size_,
2156 oat_dex_file.GetLocation(),
2157 oat_dex_file.dex_file_location_checksum_,
2158 /* oat_dex_file */ nullptr,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002159 verify,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002160 &error_msg));
2161 if (dex_files.back() == nullptr) {
Andreas Gampe3a2bd292016-01-26 17:23:47 -08002162 LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
2163 << " Error: " << error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002164 return false;
2165 }
2166 }
2167
2168 *opened_dex_files_map = std::move(dex_files_map);
2169 *opened_dex_files = std::move(dex_files);
2170 return true;
2171}
2172
2173bool OatWriter::WriteTypeLookupTables(
2174 MemMap* opened_dex_files_map,
2175 const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files) {
2176 TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
2177
2178 DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
2179 for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
2180 OatDexFile* oat_dex_file = &oat_dex_files_[i];
2181 if (oat_dex_file->lookup_table_offset_ != 0u) {
2182 DCHECK(oat_dex_file->create_type_lookup_table_ == CreateTypeLookupTable::kCreate);
2183 DCHECK_NE(oat_dex_file->class_offsets_.size(), 0u);
2184 size_t map_offset = oat_dex_files_[0].dex_file_offset_;
2185 size_t lookup_table_offset = oat_dex_file->lookup_table_offset_;
2186 uint8_t* lookup_table = opened_dex_files_map->Begin() + (lookup_table_offset - map_offset);
2187 opened_dex_files[i]->CreateTypeLookupTable(lookup_table);
2188 }
2189 }
2190
2191 DCHECK_EQ(opened_dex_files_map == nullptr, opened_dex_files.empty());
2192 if (opened_dex_files_map != nullptr && !opened_dex_files_map->Sync()) {
2193 PLOG(ERROR) << "Failed to Sync() type lookup tables. Map: " << opened_dex_files_map->GetName();
2194 return false;
2195 }
2196
2197 return true;
2198}
2199
Vladimir Markof4da6752014-08-01 19:04:18 +01002200bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
2201 static const uint8_t kPadding[] = {
2202 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
2203 };
2204 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
2205 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
2206 return false;
2207 }
2208 size_code_alignment_ += aligned_code_delta;
2209 return true;
2210}
2211
Vladimir Marko49b0f452015-12-10 13:49:19 +00002212bool OatWriter::WriteData(OutputStream* out, const void* data, size_t size) {
2213 oat_header_->UpdateChecksum(data, size);
2214 return out->WriteFully(data, size);
2215}
2216
Vladimir Marko944da602016-02-19 12:27:55 +00002217void OatWriter::SetMultiOatRelativePatcherAdjustment() {
2218 DCHECK(dex_files_ != nullptr);
2219 DCHECK(relative_patcher_ != nullptr);
2220 DCHECK_NE(oat_data_offset_, 0u);
2221 if (image_writer_ != nullptr && !dex_files_->empty()) {
2222 // The oat data begin may not be initialized yet but the oat file offset is ready.
2223 size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
2224 size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
2225 relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
Vladimir Markob163bb72015-03-31 21:49:49 +01002226 }
2227}
2228
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002229OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
2230 DexFileSource source,
2231 CreateTypeLookupTable create_type_lookup_table)
2232 : source_(source),
2233 create_type_lookup_table_(create_type_lookup_table),
2234 dex_file_size_(0),
2235 offset_(0),
2236 dex_file_location_size_(strlen(dex_file_location)),
2237 dex_file_location_data_(dex_file_location),
2238 dex_file_location_checksum_(0u),
2239 dex_file_offset_(0u),
2240 class_offsets_offset_(0u),
2241 lookup_table_offset_(0u),
2242 class_offsets_() {
Brian Carlstrome24fa612011-09-29 00:53:55 -07002243}
2244
2245size_t OatWriter::OatDexFile::SizeOf() const {
2246 return sizeof(dex_file_location_size_)
2247 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002248 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08002249 + sizeof(dex_file_offset_)
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002250 + sizeof(class_offsets_offset_)
2251 + sizeof(lookup_table_offset_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07002252}
2253
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002254void OatWriter::OatDexFile::ReserveTypeLookupTable(OatWriter* oat_writer) {
2255 DCHECK_EQ(lookup_table_offset_, 0u);
2256 if (create_type_lookup_table_ == CreateTypeLookupTable::kCreate && !class_offsets_.empty()) {
2257 size_t table_size = TypeLookupTable::RawDataLength(class_offsets_.size());
2258 if (table_size != 0u) {
2259 // Type tables are required to be 4 byte aligned.
2260 size_t original_offset = oat_writer->size_;
2261 size_t offset = RoundUp(original_offset, 4);
2262 oat_writer->size_oat_lookup_table_alignment_ += offset - original_offset;
2263 lookup_table_offset_ = offset;
2264 oat_writer->size_ = offset + table_size;
2265 oat_writer->size_oat_lookup_table_ += table_size;
2266 }
2267 }
2268}
2269
2270void OatWriter::OatDexFile::ReserveClassOffsets(OatWriter* oat_writer) {
2271 DCHECK_EQ(class_offsets_offset_, 0u);
2272 if (!class_offsets_.empty()) {
2273 // Class offsets are required to be 4 byte aligned.
2274 size_t original_offset = oat_writer->size_;
2275 size_t offset = RoundUp(original_offset, 4);
2276 oat_writer->size_oat_class_offsets_alignment_ += offset - original_offset;
2277 class_offsets_offset_ = offset;
2278 oat_writer->size_ = offset + GetClassOffsetsRawSize();
2279 }
2280}
2281
2282bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
2283 const size_t file_offset = oat_writer->oat_data_offset_;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002284 DCHECK_OFFSET_();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002285
Vladimir Marko49b0f452015-12-10 13:49:19 +00002286 if (!oat_writer->WriteData(out, &dex_file_location_size_, sizeof(dex_file_location_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002287 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002288 return false;
2289 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002290 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002291
Vladimir Marko49b0f452015-12-10 13:49:19 +00002292 if (!oat_writer->WriteData(out, dex_file_location_data_, dex_file_location_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002293 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002294 return false;
2295 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002296 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002297
Vladimir Marko49b0f452015-12-10 13:49:19 +00002298 if (!oat_writer->WriteData(out,
2299 &dex_file_location_checksum_,
2300 sizeof(dex_file_location_checksum_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002301 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002302 return false;
2303 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002304 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002305
Vladimir Marko49b0f452015-12-10 13:49:19 +00002306 if (!oat_writer->WriteData(out, &dex_file_offset_, sizeof(dex_file_offset_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002307 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002308 return false;
2309 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002310 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002311
2312 if (!oat_writer->WriteData(out, &class_offsets_offset_, sizeof(class_offsets_offset_))) {
2313 PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
2314 return false;
2315 }
2316 oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
2317
Vladimir Marko49b0f452015-12-10 13:49:19 +00002318 if (!oat_writer->WriteData(out, &lookup_table_offset_, sizeof(lookup_table_offset_))) {
Artem Udovichenkod9786b02015-10-14 16:36:55 +03002319 PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
2320 return false;
2321 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002322 oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002323
2324 return true;
2325}
2326
2327bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002328 if (!oat_writer->WriteData(out, class_offsets_.data(), GetClassOffsetsRawSize())) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002329 PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
2330 << " to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002331 return false;
2332 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002333 oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002334 return true;
2335}
2336
Brian Carlstromba150c32013-08-27 17:31:03 -07002337OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko49b0f452015-12-10 13:49:19 +00002338 const dchecked_vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002339 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002340 mirror::Class::Status status)
2341 : compiled_methods_(compiled_methods) {
2342 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002343 CHECK_LE(num_non_null_compiled_methods, num_methods);
2344
Brian Carlstrom265091e2013-01-30 14:08:26 -08002345 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002346 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2347
2348 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2349 // apply when there are 0 methods, we just arbitrarily say that 0
2350 // methods means kOatClassNoneCompiled and that we won't use
2351 // kOatClassAllCompiled unless there is at least one compiled
2352 // method. This means in an interpretter only system, we can assert
2353 // that all classes are kOatClassNoneCompiled.
2354 if (num_non_null_compiled_methods == 0) {
2355 type_ = kOatClassNoneCompiled;
2356 } else if (num_non_null_compiled_methods == num_methods) {
2357 type_ = kOatClassAllCompiled;
2358 } else {
2359 type_ = kOatClassSomeCompiled;
2360 }
2361
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002362 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002363 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002364 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002365
2366 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2367 if (type_ == kOatClassSomeCompiled) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002368 method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
Brian Carlstromba150c32013-08-27 17:31:03 -07002369 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2370 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2371 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2372 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002373 method_bitmap_ = nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002374 method_bitmap_size_ = 0;
2375 }
2376
2377 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002378 CompiledMethod* compiled_method = compiled_methods_[i];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002379 if (compiled_method == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002380 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2381 } else {
2382 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2383 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2384 if (type_ == kOatClassSomeCompiled) {
2385 method_bitmap_->SetBit(i);
2386 }
2387 }
2388 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002389}
2390
Brian Carlstrom265091e2013-01-30 14:08:26 -08002391size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2392 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002393 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2394 if (method_offset == 0) {
2395 return 0;
2396 }
2397 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002398}
2399
2400size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2401 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002402 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002403}
2404
2405size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002406 return sizeof(status_)
2407 + sizeof(type_)
2408 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2409 + method_bitmap_size_
2410 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002411}
2412
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002413bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002414 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002415 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002416 DCHECK_OFFSET_();
Vladimir Marko49b0f452015-12-10 13:49:19 +00002417 if (!oat_writer->WriteData(out, &status_, sizeof(status_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002418 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002419 return false;
2420 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002421 oat_writer->size_oat_class_status_ += sizeof(status_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002422
2423 if (!oat_writer->WriteData(out, &type_, sizeof(type_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002424 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002425 return false;
2426 }
2427 oat_writer->size_oat_class_type_ += sizeof(type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002428
Brian Carlstromba150c32013-08-27 17:31:03 -07002429 if (method_bitmap_size_ != 0) {
2430 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002431 if (!oat_writer->WriteData(out, &method_bitmap_size_, sizeof(method_bitmap_size_))) {
Ian Rogers3d504072014-03-01 09:16:49 -08002432 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002433 return false;
2434 }
2435 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002436
2437 if (!oat_writer->WriteData(out, method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
Ian Rogers3d504072014-03-01 09:16:49 -08002438 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002439 return false;
2440 }
2441 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2442 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002443
2444 if (!oat_writer->WriteData(out, method_offsets_.data(), GetMethodOffsetsRawSize())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002445 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002446 return false;
2447 }
Vladimir Marko49b0f452015-12-10 13:49:19 +00002448 oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002449 return true;
2450}
2451
Brian Carlstrome24fa612011-09-29 00:53:55 -07002452} // namespace art