1 /*
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  */
16 
17 #include "oat_writer.h"
18 
19 #include <algorithm>
20 #include <unistd.h>
21 #include <zlib.h>
22 
23 #include "arch/arm64/instruction_set_features_arm64.h"
24 #include "art_method-inl.h"
25 #include "base/allocator.h"
26 #include "base/bit_vector-inl.h"
27 #include "base/enums.h"
28 #include "base/file_magic.h"
29 #include "base/file_utils.h"
30 #include "base/indenter.h"
31 #include "base/logging.h"  // For VLOG
32 #include "base/os.h"
33 #include "base/safe_map.h"
34 #include "base/stl_util.h"
35 #include "base/unix_file/fd_file.h"
36 #include "base/zip_archive.h"
37 #include "class_linker.h"
38 #include "class_table-inl.h"
39 #include "compiled_method-inl.h"
40 #include "debug/method_debug_info.h"
41 #include "dex/art_dex_file_loader.h"
42 #include "dex/class_accessor-inl.h"
43 #include "dex/dex_file-inl.h"
44 #include "dex/dex_file_loader.h"
45 #include "dex/dex_file_types.h"
46 #include "dex/standard_dex_file.h"
47 #include "dex/type_lookup_table.h"
48 #include "dex/verification_results.h"
49 #include "dex_container.h"
50 #include "dexlayout.h"
51 #include "driver/compiler_driver-inl.h"
52 #include "driver/compiler_options.h"
53 #include "gc/space/image_space.h"
54 #include "gc/space/space.h"
55 #include "handle_scope-inl.h"
56 #include "image_writer.h"
57 #include "linker/index_bss_mapping_encoder.h"
58 #include "linker/linker_patch.h"
59 #include "linker/multi_oat_relative_patcher.h"
60 #include "mirror/array.h"
61 #include "mirror/class_loader.h"
62 #include "mirror/dex_cache-inl.h"
63 #include "mirror/object-inl.h"
64 #include "oat.h"
65 #include "oat_quick_method_header.h"
66 #include "profile/profile_compilation_info.h"
67 #include "quicken_info.h"
68 #include "scoped_thread_state_change-inl.h"
69 #include "stack_map.h"
70 #include "stream/buffered_output_stream.h"
71 #include "stream/file_output_stream.h"
72 #include "stream/output_stream.h"
73 #include "utils/dex_cache_arrays_layout-inl.h"
74 #include "vdex_file.h"
75 #include "verifier/verifier_deps.h"
76 
77 namespace art {
78 namespace linker {
79 
80 namespace {  // anonymous namespace
81 
82 // If we write dex layout info in the oat file.
83 static constexpr bool kWriteDexLayoutInfo = true;
84 
85 // Force the OAT method layout to be sorted-by-name instead of
86 // the default (class_def_idx, method_idx).
87 //
88 // Otherwise if profiles are used, that will act as
89 // the primary sort order.
90 //
91 // A bit easier to use for development since oatdump can easily
92 // show that things are being re-ordered when two methods aren't adjacent.
93 static constexpr bool kOatWriterForceOatCodeLayout = false;
94 
95 static constexpr bool kOatWriterDebugOatCodeLayout = false;
96 
97 using UnalignedDexFileHeader __attribute__((__aligned__(1))) = DexFile::Header;
98 
AsUnalignedDexFileHeader(const uint8_t * raw_data)99 const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
100   return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
101 }
102 
CodeAlignmentSize(uint32_t header_offset,const CompiledMethod & compiled_method)103 inline uint32_t CodeAlignmentSize(uint32_t header_offset, const CompiledMethod& compiled_method) {
104   // We want to align the code rather than the preheader.
105   uint32_t unaligned_code_offset = header_offset + sizeof(OatQuickMethodHeader);
106   uint32_t aligned_code_offset =  compiled_method.AlignCode(unaligned_code_offset);
107   return aligned_code_offset - unaligned_code_offset;
108 }
109 
110 }  // anonymous namespace
111 
112 class OatWriter::ChecksumUpdatingOutputStream : public OutputStream {
113  public:
ChecksumUpdatingOutputStream(OutputStream * out,OatWriter * writer)114   ChecksumUpdatingOutputStream(OutputStream* out, OatWriter* writer)
115       : OutputStream(out->GetLocation()), out_(out), writer_(writer) { }
116 
WriteFully(const void * buffer,size_t byte_count)117   bool WriteFully(const void* buffer, size_t byte_count) override {
118     if (buffer != nullptr) {
119       const uint8_t* bytes = reinterpret_cast<const uint8_t*>(buffer);
120       uint32_t old_checksum = writer_->oat_checksum_;
121       writer_->oat_checksum_ = adler32(old_checksum, bytes, byte_count);
122     } else {
123       DCHECK_EQ(0U, byte_count);
124     }
125     return out_->WriteFully(buffer, byte_count);
126   }
127 
Seek(off_t offset,Whence whence)128   off_t Seek(off_t offset, Whence whence) override {
129     return out_->Seek(offset, whence);
130   }
131 
Flush()132   bool Flush() override {
133     return out_->Flush();
134   }
135 
136  private:
137   OutputStream* const out_;
138   OatWriter* const writer_;
139 };
140 
141 // Defines the location of the raw dex file to write.
142 class OatWriter::DexFileSource {
143  public:
144   enum Type {
145     kNone,
146     kZipEntry,
147     kRawFile,
148     kRawData,
149   };
150 
DexFileSource(ZipEntry * zip_entry)151   explicit DexFileSource(ZipEntry* zip_entry)
152       : type_(kZipEntry), source_(zip_entry) {
153     DCHECK(source_ != nullptr);
154   }
155 
DexFileSource(File * raw_file)156   explicit DexFileSource(File* raw_file)
157       : type_(kRawFile), source_(raw_file) {
158     DCHECK(source_ != nullptr);
159   }
160 
DexFileSource(const uint8_t * dex_file)161   explicit DexFileSource(const uint8_t* dex_file)
162       : type_(kRawData), source_(dex_file) {
163     DCHECK(source_ != nullptr);
164   }
165 
GetType() const166   Type GetType() const { return type_; }
IsZipEntry() const167   bool IsZipEntry() const { return type_ == kZipEntry; }
IsRawFile() const168   bool IsRawFile() const { return type_ == kRawFile; }
IsRawData() const169   bool IsRawData() const { return type_ == kRawData; }
170 
GetZipEntry() const171   ZipEntry* GetZipEntry() const {
172     DCHECK(IsZipEntry());
173     DCHECK(source_ != nullptr);
174     return static_cast<ZipEntry*>(const_cast<void*>(source_));
175   }
176 
GetRawFile() const177   File* GetRawFile() const {
178     DCHECK(IsRawFile());
179     DCHECK(source_ != nullptr);
180     return static_cast<File*>(const_cast<void*>(source_));
181   }
182 
GetRawData() const183   const uint8_t* GetRawData() const {
184     DCHECK(IsRawData());
185     DCHECK(source_ != nullptr);
186     return static_cast<const uint8_t*>(source_);
187   }
188 
SetDexLayoutData(std::vector<uint8_t> && dexlayout_data)189   void SetDexLayoutData(std::vector<uint8_t>&& dexlayout_data) {
190     DCHECK_GE(dexlayout_data.size(), sizeof(DexFile::Header));
191     dexlayout_data_ = std::move(dexlayout_data);
192     type_ = kRawData;
193     source_ = dexlayout_data_.data();
194   }
195 
Clear()196   void Clear() {
197     type_ = kNone;
198     source_ = nullptr;
199     // Release the memory held by `dexlayout_data_`.
200     std::vector<uint8_t> temp;
201     temp.swap(dexlayout_data_);
202   }
203 
204  private:
205   Type type_;
206   const void* source_;
207   std::vector<uint8_t> dexlayout_data_;
208 };
209 
210 // OatClassHeader is the header only part of the oat class that is required even when compilation
211 // is not enabled.
212 class OatWriter::OatClassHeader {
213  public:
OatClassHeader(uint32_t offset,uint32_t num_non_null_compiled_methods,uint32_t num_methods,ClassStatus status)214   OatClassHeader(uint32_t offset,
215                  uint32_t num_non_null_compiled_methods,
216                  uint32_t num_methods,
217                  ClassStatus status)
218       : status_(enum_cast<uint16_t>(status)),
219         offset_(offset) {
220     // We just arbitrarily say that 0 methods means kOatClassNoneCompiled and that we won't use
221     // kOatClassAllCompiled unless there is at least one compiled method. This means in an
222     // interpreter only system, we can assert that all classes are kOatClassNoneCompiled.
223     if (num_non_null_compiled_methods == 0) {
224       type_ = kOatClassNoneCompiled;
225     } else if (num_non_null_compiled_methods == num_methods) {
226       type_ = kOatClassAllCompiled;
227     } else {
228       type_ = kOatClassSomeCompiled;
229     }
230   }
231 
232   bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
233 
SizeOf()234   static size_t SizeOf() {
235     return sizeof(status_) + sizeof(type_);
236   }
237 
238   // Data to write.
239   static_assert(enum_cast<>(ClassStatus::kLast) < (1 << 16), "class status won't fit in 16bits");
240   uint16_t status_;
241 
242   static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
243   uint16_t type_;
244 
245   // Offset of start of OatClass from beginning of OatHeader. It is
246   // used to validate file position when writing.
247   uint32_t offset_;
248 };
249 
250 // The actual oat class body contains the information about compiled methods. It is only required
251 // for compiler filters that have any compilation.
252 class OatWriter::OatClass {
253  public:
254   OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
255            uint32_t compiled_methods_with_code,
256            uint16_t oat_class_type);
257   OatClass(OatClass&& src) = default;
258   size_t SizeOf() const;
259   bool Write(OatWriter* oat_writer, OutputStream* out) const;
260 
GetCompiledMethod(size_t class_def_method_index) const261   CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
262     return compiled_methods_[class_def_method_index];
263   }
264 
265   // CompiledMethods for each class_def_method_index, or null if no method is available.
266   dchecked_vector<CompiledMethod*> compiled_methods_;
267 
268   // Offset from OatClass::offset_ to the OatMethodOffsets for the
269   // class_def_method_index. If 0, it means the corresponding
270   // CompiledMethod entry in OatClass::compiled_methods_ should be
271   // null and that the OatClass::type_ should be kOatClassBitmap.
272   dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
273 
274   // Data to write.
275   uint32_t method_bitmap_size_;
276 
277   // bit vector indexed by ClassDef method index. When
278   // OatClassType::type_ is kOatClassBitmap, a set bit indicates the
279   // method has an OatMethodOffsets in methods_offsets_, otherwise
280   // the entry was ommited to save space. If OatClassType::type_ is
281   // not is kOatClassBitmap, the bitmap will be null.
282   std::unique_ptr<BitVector> method_bitmap_;
283 
284   // OatMethodOffsets and OatMethodHeaders for each CompiledMethod
285   // present in the OatClass. Note that some may be missing if
286   // OatClass::compiled_methods_ contains null values (and
287   // oat_method_offsets_offsets_from_oat_class_ should contain 0
288   // values in this case).
289   dchecked_vector<OatMethodOffsets> method_offsets_;
290   dchecked_vector<OatQuickMethodHeader> method_headers_;
291 
292  private:
GetMethodOffsetsRawSize() const293   size_t GetMethodOffsetsRawSize() const {
294     return method_offsets_.size() * sizeof(method_offsets_[0]);
295   }
296 
297   DISALLOW_COPY_AND_ASSIGN(OatClass);
298 };
299 
300 class OatWriter::OatDexFile {
301  public:
302   OatDexFile(const char* dex_file_location,
303              DexFileSource source,
304              CreateTypeLookupTable create_type_lookup_table,
305              uint32_t dex_file_location_checksun,
306              size_t dex_file_size);
307   OatDexFile(OatDexFile&& src) = default;
308 
GetLocation() const309   const char* GetLocation() const {
310     return dex_file_location_data_;
311   }
312 
313   size_t SizeOf() const;
314   bool Write(OatWriter* oat_writer, OutputStream* out) const;
315   bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
316 
GetClassOffsetsRawSize() const317   size_t GetClassOffsetsRawSize() const {
318     return class_offsets_.size() * sizeof(class_offsets_[0]);
319   }
320 
321   // The source of the dex file.
322   DexFileSource source_;
323 
324   // Whether to create the type lookup table.
325   CreateTypeLookupTable create_type_lookup_table_;
326 
327   // Dex file size. Passed in the constructor, but could be
328   // overwritten by LayoutDexFile.
329   size_t dex_file_size_;
330 
331   // Offset of start of OatDexFile from beginning of OatHeader. It is
332   // used to validate file position when writing.
333   size_t offset_;
334 
335   ///// Start of data to write to vdex/oat file.
336 
337   const uint32_t dex_file_location_size_;
338   const char* const dex_file_location_data_;
339 
340   // The checksum of the dex file.
341   const uint32_t dex_file_location_checksum_;
342 
343   // Offset of the dex file in the vdex file. Set when writing dex files in
344   // SeekToDexFile.
345   uint32_t dex_file_offset_;
346 
347   // The lookup table offset in the oat file. Set in WriteTypeLookupTables.
348   uint32_t lookup_table_offset_;
349 
350   // Class and BSS offsets set in PrepareLayout.
351   uint32_t class_offsets_offset_;
352   uint32_t method_bss_mapping_offset_;
353   uint32_t type_bss_mapping_offset_;
354   uint32_t string_bss_mapping_offset_;
355 
356   // Offset of dex sections that will have different runtime madvise states.
357   // Set in WriteDexLayoutSections.
358   uint32_t dex_sections_layout_offset_;
359 
360   // Data to write to a separate section. We set the length
361   // of the vector in OpenDexFiles.
362   dchecked_vector<uint32_t> class_offsets_;
363 
364   // Dex section layout info to serialize.
365   DexLayoutSections dex_sections_layout_;
366 
367   ///// End of data to write to vdex/oat file.
368  private:
369   DISALLOW_COPY_AND_ASSIGN(OatDexFile);
370 };
371 
372 #define DCHECK_OFFSET() \
373   DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
374     << "file_offset=" << file_offset << " relative_offset=" << relative_offset
375 
376 #define DCHECK_OFFSET_() \
377   DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
378     << "file_offset=" << file_offset << " offset_=" << offset_
379 
OatWriter(const CompilerOptions & compiler_options,TimingLogger * timings,ProfileCompilationInfo * info,CompactDexLevel compact_dex_level)380 OatWriter::OatWriter(const CompilerOptions& compiler_options,
381                      TimingLogger* timings,
382                      ProfileCompilationInfo* info,
383                      CompactDexLevel compact_dex_level)
384   : write_state_(WriteState::kAddingDexFileSources),
385     timings_(timings),
386     raw_dex_files_(),
387     zip_archives_(),
388     zipped_dex_files_(),
389     zipped_dex_file_locations_(),
390     compiler_driver_(nullptr),
391     compiler_options_(compiler_options),
392     image_writer_(nullptr),
393     extract_dex_files_into_vdex_(true),
394     vdex_begin_(nullptr),
395     dex_files_(nullptr),
396     primary_oat_file_(false),
397     vdex_size_(0u),
398     vdex_dex_files_offset_(0u),
399     vdex_dex_shared_data_offset_(0u),
400     vdex_verifier_deps_offset_(0u),
401     vdex_quickening_info_offset_(0u),
402     oat_checksum_(adler32(0L, Z_NULL, 0)),
403     code_size_(0u),
404     oat_size_(0u),
405     data_bimg_rel_ro_start_(0u),
406     data_bimg_rel_ro_size_(0u),
407     bss_start_(0u),
408     bss_size_(0u),
409     bss_methods_offset_(0u),
410     bss_roots_offset_(0u),
411     data_bimg_rel_ro_entries_(),
412     bss_method_entry_references_(),
413     bss_method_entries_(),
414     bss_type_entries_(),
415     bss_string_entries_(),
416     oat_data_offset_(0u),
417     oat_header_(nullptr),
418     size_vdex_header_(0),
419     size_vdex_checksums_(0),
420     size_dex_file_alignment_(0),
421     size_quickening_table_offset_(0),
422     size_executable_offset_alignment_(0),
423     size_oat_header_(0),
424     size_oat_header_key_value_store_(0),
425     size_dex_file_(0),
426     size_verifier_deps_(0),
427     size_verifier_deps_alignment_(0),
428     size_quickening_info_(0),
429     size_quickening_info_alignment_(0),
430     size_interpreter_to_interpreter_bridge_(0),
431     size_interpreter_to_compiled_code_bridge_(0),
432     size_jni_dlsym_lookup_trampoline_(0),
433     size_jni_dlsym_lookup_critical_trampoline_(0),
434     size_quick_generic_jni_trampoline_(0),
435     size_quick_imt_conflict_trampoline_(0),
436     size_quick_resolution_trampoline_(0),
437     size_quick_to_interpreter_bridge_(0),
438     size_trampoline_alignment_(0),
439     size_method_header_(0),
440     size_code_(0),
441     size_code_alignment_(0),
442     size_data_bimg_rel_ro_(0),
443     size_data_bimg_rel_ro_alignment_(0),
444     size_relative_call_thunks_(0),
445     size_misc_thunks_(0),
446     size_vmap_table_(0),
447     size_method_info_(0),
448     size_oat_dex_file_location_size_(0),
449     size_oat_dex_file_location_data_(0),
450     size_oat_dex_file_location_checksum_(0),
451     size_oat_dex_file_offset_(0),
452     size_oat_dex_file_class_offsets_offset_(0),
453     size_oat_dex_file_lookup_table_offset_(0),
454     size_oat_dex_file_dex_layout_sections_offset_(0),
455     size_oat_dex_file_dex_layout_sections_(0),
456     size_oat_dex_file_dex_layout_sections_alignment_(0),
457     size_oat_dex_file_method_bss_mapping_offset_(0),
458     size_oat_dex_file_type_bss_mapping_offset_(0),
459     size_oat_dex_file_string_bss_mapping_offset_(0),
460     size_oat_lookup_table_alignment_(0),
461     size_oat_lookup_table_(0),
462     size_oat_class_offsets_alignment_(0),
463     size_oat_class_offsets_(0),
464     size_oat_class_type_(0),
465     size_oat_class_status_(0),
466     size_oat_class_method_bitmaps_(0),
467     size_oat_class_method_offsets_(0),
468     size_method_bss_mappings_(0u),
469     size_type_bss_mappings_(0u),
470     size_string_bss_mappings_(0u),
471     relative_patcher_(nullptr),
472     profile_compilation_info_(info),
473     compact_dex_level_(compact_dex_level) {
474   // If we have a profile, always use at least the default compact dex level. The reason behind
475   // this is that CompactDex conversion is not more expensive than normal dexlayout.
476   if (info != nullptr && compact_dex_level_ == CompactDexLevel::kCompactDexLevelNone) {
477     compact_dex_level_ = kDefaultCompactDexLevel;
478   }
479 }
480 
ValidateDexFileHeader(const uint8_t * raw_header,const char * location)481 static bool ValidateDexFileHeader(const uint8_t* raw_header, const char* location) {
482   const bool valid_standard_dex_magic = DexFileLoader::IsMagicValid(raw_header);
483   if (!valid_standard_dex_magic) {
484     LOG(ERROR) << "Invalid magic number in dex file header. " << " File: " << location;
485     return false;
486   }
487   if (!DexFileLoader::IsVersionAndMagicValid(raw_header)) {
488     LOG(ERROR) << "Invalid version number in dex file header. " << " File: " << location;
489     return false;
490   }
491   const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_header);
492   if (header->file_size_ < sizeof(DexFile::Header)) {
493     LOG(ERROR) << "Dex file header specifies file size insufficient to contain the header."
494                << " File: " << location;
495     return false;
496   }
497   return true;
498 }
499 
GetDexFileHeader(File * file,uint8_t * raw_header,const char * location)500 static const UnalignedDexFileHeader* GetDexFileHeader(File* file,
501                                                       uint8_t* raw_header,
502                                                       const char* location) {
503   // Read the dex file header and perform minimal verification.
504   if (!file->ReadFully(raw_header, sizeof(DexFile::Header))) {
505     PLOG(ERROR) << "Failed to read dex file header. Actual: "
506                 << " File: " << location << " Output: " << file->GetPath();
507     return nullptr;
508   }
509   if (!ValidateDexFileHeader(raw_header, location)) {
510     return nullptr;
511   }
512 
513   return AsUnalignedDexFileHeader(raw_header);
514 }
515 
AddDexFileSource(const char * filename,const char * location,CreateTypeLookupTable create_type_lookup_table)516 bool OatWriter::AddDexFileSource(const char* filename,
517                                  const char* location,
518                                  CreateTypeLookupTable create_type_lookup_table) {
519   DCHECK(write_state_ == WriteState::kAddingDexFileSources);
520   File fd(filename, O_RDONLY, /* check_usage= */ false);
521   if (fd.Fd() == -1) {
522     PLOG(ERROR) << "Failed to open dex file: '" << filename << "'";
523     return false;
524   }
525 
526   return AddDexFileSource(std::move(fd), location, create_type_lookup_table);
527 }
528 
529 // Add dex file source(s) from a file specified by a file handle.
530 // Note: The `dex_file_fd` specifies a plain dex file or a zip file.
AddDexFileSource(File && dex_file_fd,const char * location,CreateTypeLookupTable create_type_lookup_table)531 bool OatWriter::AddDexFileSource(File&& dex_file_fd,
532                                  const char* location,
533                                  CreateTypeLookupTable create_type_lookup_table) {
534   DCHECK(write_state_ == WriteState::kAddingDexFileSources);
535   std::string error_msg;
536   uint32_t magic;
537   if (!ReadMagicAndReset(dex_file_fd.Fd(), &magic, &error_msg)) {
538     LOG(ERROR) << "Failed to read magic number from dex file '" << location << "': " << error_msg;
539     return false;
540   }
541   if (DexFileLoader::IsMagicValid(magic)) {
542     uint8_t raw_header[sizeof(DexFile::Header)];
543     const UnalignedDexFileHeader* header = GetDexFileHeader(&dex_file_fd, raw_header, location);
544     if (header == nullptr) {
545       LOG(ERROR) << "Failed to get DexFileHeader from file descriptor for '"
546           << location << "': " << error_msg;
547       return false;
548     }
549     // The file is open for reading, not writing, so it's OK to let the File destructor
550     // close it without checking for explicit Close(), so pass checkUsage = false.
551     raw_dex_files_.emplace_back(new File(dex_file_fd.Release(), location, /* checkUsage */ false));
552     oat_dex_files_.emplace_back(/* OatDexFile */
553         location,
554         DexFileSource(raw_dex_files_.back().get()),
555         create_type_lookup_table,
556         header->checksum_,
557         header->file_size_);
558   } else if (IsZipMagic(magic)) {
559     zip_archives_.emplace_back(ZipArchive::OpenFromFd(dex_file_fd.Release(), location, &error_msg));
560     ZipArchive* zip_archive = zip_archives_.back().get();
561     if (zip_archive == nullptr) {
562       LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
563           << error_msg;
564       return false;
565     }
566     for (size_t i = 0; ; ++i) {
567       std::string entry_name = DexFileLoader::GetMultiDexClassesDexName(i);
568       std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
569       if (entry == nullptr) {
570         break;
571       }
572       zipped_dex_files_.push_back(std::move(entry));
573       zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
574       const char* full_location = zipped_dex_file_locations_.back().c_str();
575       // We override the checksum from header with the CRC from ZIP entry.
576       oat_dex_files_.emplace_back(/* OatDexFile */
577           full_location,
578           DexFileSource(zipped_dex_files_.back().get()),
579           create_type_lookup_table,
580           zipped_dex_files_.back()->GetCrc32(),
581           zipped_dex_files_.back()->GetUncompressedLength());
582     }
583     if (zipped_dex_file_locations_.empty()) {
584       LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
585       return false;
586     }
587   } else {
588     LOG(ERROR) << "Expected valid zip or dex file: '" << location << "'";
589     return false;
590   }
591   return true;
592 }
593 
594 // Add dex file source(s) from a vdex file specified by a file handle.
AddVdexDexFilesSource(const VdexFile & vdex_file,const char * location,CreateTypeLookupTable create_type_lookup_table)595 bool OatWriter::AddVdexDexFilesSource(const VdexFile& vdex_file,
596                                       const char* location,
597                                       CreateTypeLookupTable create_type_lookup_table) {
598   DCHECK(write_state_ == WriteState::kAddingDexFileSources);
599   DCHECK(vdex_file.HasDexSection());
600   const uint8_t* current_dex_data = nullptr;
601   for (size_t i = 0; i < vdex_file.GetVerifierDepsHeader().GetNumberOfDexFiles(); ++i) {
602     current_dex_data = vdex_file.GetNextDexFileData(current_dex_data);
603     if (current_dex_data == nullptr) {
604       LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
605       return false;
606     }
607 
608     if (!DexFileLoader::IsMagicValid(current_dex_data)) {
609       LOG(ERROR) << "Invalid magic in vdex file created from " << location;
610       return false;
611     }
612     // We used `zipped_dex_file_locations_` to keep the strings in memory.
613     zipped_dex_file_locations_.push_back(DexFileLoader::GetMultiDexLocation(i, location));
614     const char* full_location = zipped_dex_file_locations_.back().c_str();
615     const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(current_dex_data);
616     oat_dex_files_.emplace_back(/* OatDexFile */
617         full_location,
618         DexFileSource(current_dex_data),
619         create_type_lookup_table,
620         vdex_file.GetLocationChecksum(i),
621         header->file_size_);
622   }
623 
624   if (vdex_file.GetNextDexFileData(current_dex_data) != nullptr) {
625     LOG(ERROR) << "Unexpected number of dex files in vdex " << location;
626     return false;
627   }
628 
629   if (oat_dex_files_.empty()) {
630     LOG(ERROR) << "No dex files in vdex file created from " << location;
631     return false;
632   }
633   return true;
634 }
635 
636 // Add dex file source from raw memory.
AddRawDexFileSource(const ArrayRef<const uint8_t> & data,const char * location,uint32_t location_checksum,CreateTypeLookupTable create_type_lookup_table)637 bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
638                                     const char* location,
639                                     uint32_t location_checksum,
640                                     CreateTypeLookupTable create_type_lookup_table) {
641   DCHECK(write_state_ == WriteState::kAddingDexFileSources);
642   if (data.size() < sizeof(DexFile::Header)) {
643     LOG(ERROR) << "Provided data is shorter than dex file header. size: "
644                << data.size() << " File: " << location;
645     return false;
646   }
647   if (!ValidateDexFileHeader(data.data(), location)) {
648     return false;
649   }
650   const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
651   if (data.size() < header->file_size_) {
652     LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
653                << " file size from header: " << header->file_size_ << " File: " << location;
654     return false;
655   }
656 
657   oat_dex_files_.emplace_back(/* OatDexFile */
658       location,
659       DexFileSource(data.data()),
660       create_type_lookup_table,
661       location_checksum,
662       header->file_size_);
663   return true;
664 }
665 
GetSourceLocations() const666 dchecked_vector<std::string> OatWriter::GetSourceLocations() const {
667   dchecked_vector<std::string> locations;
668   locations.reserve(oat_dex_files_.size());
669   for (const OatDexFile& oat_dex_file : oat_dex_files_) {
670     locations.push_back(oat_dex_file.GetLocation());
671   }
672   return locations;
673 }
674 
MayHaveCompiledMethods() const675 bool OatWriter::MayHaveCompiledMethods() const {
676   return GetCompilerOptions().IsAnyCompilationEnabled();
677 }
678 
WriteAndOpenDexFiles(File * vdex_file,bool verify,bool update_input_vdex,CopyOption copy_dex_files,std::vector<MemMap> * opened_dex_files_map,std::vector<std::unique_ptr<const DexFile>> * opened_dex_files)679 bool OatWriter::WriteAndOpenDexFiles(
680     File* vdex_file,
681     bool verify,
682     bool update_input_vdex,
683     CopyOption copy_dex_files,
684     /*out*/ std::vector<MemMap>* opened_dex_files_map,
685     /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
686   CHECK(write_state_ == WriteState::kAddingDexFileSources);
687 
688   // Reserve space for Vdex header and checksums.
689   vdex_size_ = sizeof(VdexFile::VerifierDepsHeader) +
690       oat_dex_files_.size() * sizeof(VdexFile::VdexChecksum);
691 
692   // Write DEX files into VDEX, mmap and open them.
693   std::vector<MemMap> dex_files_map;
694   std::vector<std::unique_ptr<const DexFile>> dex_files;
695   if (!WriteDexFiles(vdex_file, update_input_vdex, copy_dex_files, &dex_files_map) ||
696       !OpenDexFiles(vdex_file, verify, &dex_files_map, &dex_files)) {
697     return false;
698   }
699 
700   *opened_dex_files_map = std::move(dex_files_map);
701   *opened_dex_files = std::move(dex_files);
702   write_state_ = WriteState::kStartRoData;
703   return true;
704 }
705 
StartRoData(const std::vector<const DexFile * > & dex_files,OutputStream * oat_rodata,SafeMap<std::string,std::string> * key_value_store)706 bool OatWriter::StartRoData(const std::vector<const DexFile*>& dex_files,
707                             OutputStream* oat_rodata,
708                             SafeMap<std::string, std::string>* key_value_store) {
709   CHECK(write_state_ == WriteState::kStartRoData);
710 
711   // Record the ELF rodata section offset, i.e. the beginning of the OAT data.
712   if (!RecordOatDataOffset(oat_rodata)) {
713      return false;
714   }
715 
716   // Record whether this is the primary oat file.
717   primary_oat_file_ = (key_value_store != nullptr);
718 
719   // Initialize OAT header.
720   oat_size_ = InitOatHeader(dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
721                             key_value_store);
722 
723   ChecksumUpdatingOutputStream checksum_updating_rodata(oat_rodata, this);
724 
725   // Write type lookup tables into the oat file.
726   if (!WriteTypeLookupTables(&checksum_updating_rodata, dex_files)) {
727     return false;
728   }
729 
730   // Write dex layout sections into the oat file.
731   if (!WriteDexLayoutSections(&checksum_updating_rodata, dex_files)) {
732     return false;
733   }
734 
735   write_state_ = WriteState::kInitialize;
736   return true;
737 }
738 
739 // Initialize the writer with the given parameters.
Initialize(const CompilerDriver * compiler_driver,ImageWriter * image_writer,const std::vector<const DexFile * > & dex_files)740 void OatWriter::Initialize(const CompilerDriver* compiler_driver,
741                            ImageWriter* image_writer,
742                            const std::vector<const DexFile*>& dex_files) {
743   CHECK(write_state_ == WriteState::kInitialize);
744   compiler_driver_ = compiler_driver;
745   image_writer_ = image_writer;
746   dex_files_ = &dex_files;
747   write_state_ = WriteState::kPrepareLayout;
748 }
749 
PrepareLayout(MultiOatRelativePatcher * relative_patcher)750 void OatWriter::PrepareLayout(MultiOatRelativePatcher* relative_patcher) {
751   CHECK(write_state_ == WriteState::kPrepareLayout);
752 
753   relative_patcher_ = relative_patcher;
754   SetMultiOatRelativePatcherAdjustment();
755 
756   if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsBootImageExtension()) {
757     CHECK(image_writer_ != nullptr);
758   }
759   InstructionSet instruction_set = compiler_options_.GetInstructionSet();
760   CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
761 
762   {
763     TimingLogger::ScopedTiming split("InitBssLayout", timings_);
764     InitBssLayout(instruction_set);
765   }
766 
767   uint32_t offset = oat_size_;
768   {
769     TimingLogger::ScopedTiming split("InitClassOffsets", timings_);
770     offset = InitClassOffsets(offset);
771   }
772   {
773     TimingLogger::ScopedTiming split("InitOatClasses", timings_);
774     offset = InitOatClasses(offset);
775   }
776   {
777     TimingLogger::ScopedTiming split("InitIndexBssMappings", timings_);
778     offset = InitIndexBssMappings(offset);
779   }
780   {
781     TimingLogger::ScopedTiming split("InitOatMaps", timings_);
782     offset = InitOatMaps(offset);
783   }
784   {
785     TimingLogger::ScopedTiming split("InitOatDexFiles", timings_);
786     oat_header_->SetOatDexFilesOffset(offset);
787     offset = InitOatDexFiles(offset);
788   }
789   {
790     TimingLogger::ScopedTiming split("InitOatCode", timings_);
791     offset = InitOatCode(offset);
792   }
793   {
794     TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
795     offset = InitOatCodeDexFiles(offset);
796     code_size_ = offset - GetOatHeader().GetExecutableOffset();
797   }
798   {
799     TimingLogger::ScopedTiming split("InitDataBimgRelRoLayout", timings_);
800     offset = InitDataBimgRelRoLayout(offset);
801   }
802   oat_size_ = offset;  // .bss does not count towards oat_size_.
803   bss_start_ = (bss_size_ != 0u) ? RoundUp(oat_size_, kPageSize) : 0u;
804 
805   CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
806 
807   write_state_ = WriteState::kWriteRoData;
808 }
809 
~OatWriter()810 OatWriter::~OatWriter() {
811 }
812 
813 class OatWriter::DexMethodVisitor {
814  public:
DexMethodVisitor(OatWriter * writer,size_t offset)815   DexMethodVisitor(OatWriter* writer, size_t offset)
816       : writer_(writer),
817         offset_(offset),
818         dex_file_(nullptr),
819         class_def_index_(dex::kDexNoIndex) {}
820 
StartClass(const DexFile * dex_file,size_t class_def_index)821   virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
822     DCHECK(dex_file_ == nullptr);
823     DCHECK_EQ(class_def_index_, dex::kDexNoIndex);
824     dex_file_ = dex_file;
825     class_def_index_ = class_def_index;
826     return true;
827   }
828 
829   virtual bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) = 0;
830 
EndClass()831   virtual bool EndClass() {
832     if (kIsDebugBuild) {
833       dex_file_ = nullptr;
834       class_def_index_ = dex::kDexNoIndex;
835     }
836     return true;
837   }
838 
GetOffset() const839   size_t GetOffset() const {
840     return offset_;
841   }
842 
843  protected:
~DexMethodVisitor()844   virtual ~DexMethodVisitor() { }
845 
846   OatWriter* const writer_;
847 
848   // The offset is usually advanced for each visited method by the derived class.
849   size_t offset_;
850 
851   // The dex file and class def index are set in StartClass().
852   const DexFile* dex_file_;
853   size_t class_def_index_;
854 };
855 
856 class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
857  public:
OatDexMethodVisitor(OatWriter * writer,size_t offset)858   OatDexMethodVisitor(OatWriter* writer, size_t offset)
859       : DexMethodVisitor(writer, offset),
860         oat_class_index_(0u),
861         method_offsets_index_(0u) {}
862 
StartClass(const DexFile * dex_file,size_t class_def_index)863   bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
864     DexMethodVisitor::StartClass(dex_file, class_def_index);
865     if (kIsDebugBuild && writer_->MayHaveCompiledMethods()) {
866       // There are no oat classes if there aren't any compiled methods.
867       CHECK_LT(oat_class_index_, writer_->oat_classes_.size());
868     }
869     method_offsets_index_ = 0u;
870     return true;
871   }
872 
EndClass()873   bool EndClass() override {
874     ++oat_class_index_;
875     return DexMethodVisitor::EndClass();
876   }
877 
878  protected:
879   size_t oat_class_index_;
880   size_t method_offsets_index_;
881 };
882 
HasCompiledCode(const CompiledMethod * method)883 static bool HasCompiledCode(const CompiledMethod* method) {
884   return method != nullptr && !method->GetQuickCode().empty();
885 }
886 
HasQuickeningInfo(const CompiledMethod * method)887 static bool HasQuickeningInfo(const CompiledMethod* method) {
888   // The dextodexcompiler puts the quickening info table into the CompiledMethod
889   // for simplicity.
890   return method != nullptr && method->GetQuickCode().empty() && !method->GetVmapTable().empty();
891 }
892 
893 class OatWriter::InitBssLayoutMethodVisitor : public DexMethodVisitor {
894  public:
InitBssLayoutMethodVisitor(OatWriter * writer)895   explicit InitBssLayoutMethodVisitor(OatWriter* writer)
896       : DexMethodVisitor(writer, /* offset */ 0u) {}
897 
VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,const ClassAccessor::Method & method)898   bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
899                    const ClassAccessor::Method& method) override {
900     // Look for patches with .bss references and prepare maps with placeholders for their offsets.
901     CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(
902         MethodReference(dex_file_, method.GetIndex()));
903     if (HasCompiledCode(compiled_method)) {
904       for (const LinkerPatch& patch : compiled_method->GetPatches()) {
905         if (patch.GetType() == LinkerPatch::Type::kDataBimgRelRo) {
906           writer_->data_bimg_rel_ro_entries_.Overwrite(patch.BootImageOffset(),
907                                                        /* placeholder */ 0u);
908         } else if (patch.GetType() == LinkerPatch::Type::kMethodBssEntry) {
909           MethodReference target_method = patch.TargetMethod();
910           AddBssReference(target_method,
911                           target_method.dex_file->NumMethodIds(),
912                           &writer_->bss_method_entry_references_);
913           writer_->bss_method_entries_.Overwrite(target_method, /* placeholder */ 0u);
914         } else if (patch.GetType() == LinkerPatch::Type::kTypeBssEntry) {
915           TypeReference target_type(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
916           AddBssReference(target_type,
917                           target_type.dex_file->NumTypeIds(),
918                           &writer_->bss_type_entry_references_);
919           writer_->bss_type_entries_.Overwrite(target_type, /* placeholder */ 0u);
920         } else if (patch.GetType() == LinkerPatch::Type::kStringBssEntry) {
921           StringReference target_string(patch.TargetStringDexFile(), patch.TargetStringIndex());
922           AddBssReference(target_string,
923                           target_string.dex_file->NumStringIds(),
924                           &writer_->bss_string_entry_references_);
925           writer_->bss_string_entries_.Overwrite(target_string, /* placeholder */ 0u);
926         }
927       }
928     } else {
929       DCHECK(compiled_method == nullptr || compiled_method->GetPatches().empty());
930     }
931     return true;
932   }
933 
934  private:
AddBssReference(const DexFileReference & ref,size_t number_of_indexes,SafeMap<const DexFile *,BitVector> * references)935   void AddBssReference(const DexFileReference& ref,
936                        size_t number_of_indexes,
937                        /*inout*/ SafeMap<const DexFile*, BitVector>* references) {
938     // We currently support inlining of throwing instructions only when they originate in the
939     // same dex file as the outer method. All .bss references are used by throwing instructions.
940     DCHECK_EQ(dex_file_, ref.dex_file);
941 
942     auto refs_it = references->find(ref.dex_file);
943     if (refs_it == references->end()) {
944       refs_it = references->Put(
945           ref.dex_file,
946           BitVector(number_of_indexes, /* expandable */ false, Allocator::GetMallocAllocator()));
947       refs_it->second.ClearAllBits();
948     }
949     refs_it->second.SetBit(ref.index);
950   }
951 };
952 
953 class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
954  public:
InitOatClassesMethodVisitor(OatWriter * writer,size_t offset)955   InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
956       : DexMethodVisitor(writer, offset),
957         compiled_methods_(),
958         compiled_methods_with_code_(0u) {
959     size_t num_classes = 0u;
960     for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
961       num_classes += oat_dex_file.class_offsets_.size();
962     }
963     // If we aren't compiling only reserve headers.
964     writer_->oat_class_headers_.reserve(num_classes);
965     if (writer->MayHaveCompiledMethods()) {
966       writer->oat_classes_.reserve(num_classes);
967     }
968     compiled_methods_.reserve(256u);
969     // If there are any classes, the class offsets allocation aligns the offset.
970     DCHECK(num_classes == 0u || IsAligned<4u>(offset));
971   }
972 
StartClass(const DexFile * dex_file,size_t class_def_index)973   bool StartClass(const DexFile* dex_file, size_t class_def_index) override {
974     DexMethodVisitor::StartClass(dex_file, class_def_index);
975     compiled_methods_.clear();
976     compiled_methods_with_code_ = 0u;
977     return true;
978   }
979 
VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,const ClassAccessor::Method & method)980   bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
981                    const ClassAccessor::Method& method) override {
982     // Fill in the compiled_methods_ array for methods that have a
983     // CompiledMethod. We track the number of non-null entries in
984     // compiled_methods_with_code_ since we only want to allocate
985     // OatMethodOffsets for the compiled methods.
986     uint32_t method_idx = method.GetIndex();
987     CompiledMethod* compiled_method =
988         writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
989     compiled_methods_.push_back(compiled_method);
990     if (HasCompiledCode(compiled_method)) {
991       ++compiled_methods_with_code_;
992     }
993     return true;
994   }
995 
EndClass()996   bool EndClass() override {
997     ClassReference class_ref(dex_file_, class_def_index_);
998     ClassStatus status;
999     bool found = writer_->compiler_driver_->GetCompiledClass(class_ref, &status);
1000     if (!found) {
1001       const VerificationResults* results = writer_->compiler_options_.GetVerificationResults();
1002       if (results != nullptr && results->IsClassRejected(class_ref)) {
1003         // The oat class status is used only for verification of resolved classes,
1004         // so use ClassStatus::kErrorResolved whether the class was resolved or unresolved
1005         // during compile-time verification.
1006         status = ClassStatus::kErrorResolved;
1007       } else {
1008         status = ClassStatus::kNotReady;
1009       }
1010     }
1011     // We never emit kRetryVerificationAtRuntime, instead we mark the class as
1012     // resolved and the class will therefore be re-verified at runtime.
1013     if (status == ClassStatus::kRetryVerificationAtRuntime) {
1014       status = ClassStatus::kResolved;
1015     }
1016 
1017     writer_->oat_class_headers_.emplace_back(offset_,
1018                                              compiled_methods_with_code_,
1019                                              compiled_methods_.size(),
1020                                              status);
1021     OatClassHeader& header = writer_->oat_class_headers_.back();
1022     offset_ += header.SizeOf();
1023     if (writer_->MayHaveCompiledMethods()) {
1024       writer_->oat_classes_.emplace_back(compiled_methods_,
1025                                          compiled_methods_with_code_,
1026                                          header.type_);
1027       offset_ += writer_->oat_classes_.back().SizeOf();
1028     }
1029     return DexMethodVisitor::EndClass();
1030   }
1031 
1032  private:
1033   dchecked_vector<CompiledMethod*> compiled_methods_;
1034   size_t compiled_methods_with_code_;
1035 };
1036 
1037 // CompiledMethod + metadata required to do ordered method layout.
1038 //
1039 // See also OrderedMethodVisitor.
1040 struct OatWriter::OrderedMethodData {
1041   ProfileCompilationInfo::MethodHotness method_hotness;
1042   OatClass* oat_class;
1043   CompiledMethod* compiled_method;
1044   MethodReference method_reference;
1045   size_t method_offsets_index;
1046 
1047   size_t class_def_index;
1048   uint32_t access_flags;
1049   const dex::CodeItem* code_item;
1050 
1051   // A value of -1 denotes missing debug info
1052   static constexpr size_t kDebugInfoIdxInvalid = static_cast<size_t>(-1);
1053   // Index into writer_->method_info_
1054   size_t debug_info_idx;
1055 
HasDebugInfoart::linker::OatWriter::OrderedMethodData1056   bool HasDebugInfo() const {
1057     return debug_info_idx != kDebugInfoIdxInvalid;
1058   }
1059 
1060   // Bin each method according to the profile flags.
1061   //
1062   // Groups by e.g.
1063   //  -- not hot at all
1064   //  -- hot
1065   //  -- hot and startup
1066   //  -- hot and post-startup
1067   //  -- hot and startup and poststartup
1068   //  -- startup
1069   //  -- startup and post-startup
1070   //  -- post-startup
1071   //
1072   // (See MethodHotness enum definition for up-to-date binning order.)
operator <art::linker::OatWriter::OrderedMethodData1073   bool operator<(const OrderedMethodData& other) const {
1074     if (kOatWriterForceOatCodeLayout) {
1075       // Development flag: Override default behavior by sorting by name.
1076 
1077       std::string name = method_reference.PrettyMethod();
1078       std::string other_name = other.method_reference.PrettyMethod();
1079       return name < other_name;
1080     }
1081 
1082     // Use the profile's method hotness to determine sort order.
1083     if (GetMethodHotnessOrder() < other.GetMethodHotnessOrder()) {
1084       return true;
1085     }
1086 
1087     // Default: retain the original order.
1088     return false;
1089   }
1090 
1091  private:
1092   // Used to determine relative order for OAT code layout when determining
1093   // binning.
GetMethodHotnessOrderart::linker::OatWriter::OrderedMethodData1094   size_t GetMethodHotnessOrder() const {
1095     bool hotness[] = {
1096       method_hotness.IsHot(),
1097       method_hotness.IsStartup(),
1098       method_hotness.IsPostStartup()
1099     };
1100 
1101 
1102     // Note: Bin-to-bin order does not matter. If the kernel does or does not read-ahead
1103     // any memory, it only goes into the buffer cache and does not grow the PSS until the first
1104     // time that memory is referenced in the process.
1105 
1106     size_t hotness_bits = 0;
1107     for (size_t i = 0; i < arraysize(hotness); ++i) {
1108       if (hotness[i]) {
1109         hotness_bits |= (1 << i);
1110       }
1111     }
1112 
1113     if (kIsDebugBuild) {
1114       // Check for bins that are always-empty given a real profile.
1115       if (method_hotness.IsHot() &&
1116               !method_hotness.IsStartup() && !method_hotness.IsPostStartup()) {
1117         std::string name = method_reference.PrettyMethod();
1118         LOG(FATAL) << "Method " << name << " had a Hot method that wasn't marked "
1119                    << "either start-up or post-startup. Possible corrupted profile?";
1120         // This is not fatal, so only warn.
1121       }
1122     }
1123 
1124     return hotness_bits;
1125   }
1126 };
1127 
1128 // Given a queue of CompiledMethod in some total order,
1129 // visit each one in that order.
1130 class OatWriter::OrderedMethodVisitor {
1131  public:
OrderedMethodVisitor(OrderedMethodList ordered_methods)1132   explicit OrderedMethodVisitor(OrderedMethodList ordered_methods)
1133       : ordered_methods_(std::move(ordered_methods)) {
1134   }
1135 
~OrderedMethodVisitor()1136   virtual ~OrderedMethodVisitor() {}
1137 
1138   // Invoke VisitMethod in the order of `ordered_methods`, then invoke VisitComplete.
Visit()1139   bool Visit() REQUIRES_SHARED(Locks::mutator_lock_) {
1140     if (!VisitStart()) {
1141       return false;
1142     }
1143 
1144     for (const OrderedMethodData& method_data : ordered_methods_)  {
1145       if (!VisitMethod(method_data)) {
1146         return false;
1147       }
1148     }
1149 
1150     return VisitComplete();
1151   }
1152 
1153   // Invoked once at the beginning, prior to visiting anything else.
1154   //
1155   // Return false to abort further visiting.
VisitStart()1156   virtual bool VisitStart() { return true; }
1157 
1158   // Invoked repeatedly in the order specified by `ordered_methods`.
1159   //
1160   // Return false to short-circuit and to stop visiting further methods.
1161   virtual bool VisitMethod(const OrderedMethodData& method_data)
1162       REQUIRES_SHARED(Locks::mutator_lock_)  = 0;
1163 
1164   // Invoked once at the end, after every other method has been successfully visited.
1165   //
1166   // Return false to indicate the overall `Visit` has failed.
1167   virtual bool VisitComplete() = 0;
1168 
ReleaseOrderedMethods()1169   OrderedMethodList ReleaseOrderedMethods() {
1170     return std::move(ordered_methods_);
1171   }
1172 
1173  private:
1174   // List of compiled methods, sorted by the order defined in OrderedMethodData.
1175   // Methods can be inserted more than once in case of duplicated methods.
1176   OrderedMethodList ordered_methods_;
1177 };
1178 
1179 // Visit every compiled method in order to determine its order within the OAT file.
1180 // Methods from the same class do not need to be adjacent in the OAT code.
1181 class OatWriter::LayoutCodeMethodVisitor : public OatDexMethodVisitor {
1182  public:
LayoutCodeMethodVisitor(OatWriter * writer,size_t offset)1183   LayoutCodeMethodVisitor(OatWriter* writer, size_t offset)
1184       : OatDexMethodVisitor(writer, offset) {
1185   }
1186 
EndClass()1187   bool EndClass() override {
1188     OatDexMethodVisitor::EndClass();
1189     return true;
1190   }
1191 
VisitMethod(size_t class_def_method_index,const ClassAccessor::Method & method)1192   bool VisitMethod(size_t class_def_method_index,
1193                    const ClassAccessor::Method& method)
1194       override
1195       REQUIRES_SHARED(Locks::mutator_lock_)  {
1196     Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1197 
1198     OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1199     CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1200 
1201     if (HasCompiledCode(compiled_method)) {
1202       size_t debug_info_idx = OrderedMethodData::kDebugInfoIdxInvalid;
1203 
1204       {
1205         const CompilerOptions& compiler_options = writer_->GetCompilerOptions();
1206         ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1207         uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1208 
1209         // Debug method info must be pushed in the original order
1210         // (i.e. all methods from the same class must be adjacent in the debug info sections)
1211         // ElfCompilationUnitWriter::Write requires this.
1212         if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
1213           debug::MethodDebugInfo info = debug::MethodDebugInfo();
1214           writer_->method_info_.push_back(info);
1215 
1216           // The debug info is filled in LayoutReserveOffsetCodeMethodVisitor
1217           // once we know the offsets.
1218           //
1219           // Store the index into writer_->method_info_ since future push-backs
1220           // could reallocate and change the underlying data address.
1221           debug_info_idx = writer_->method_info_.size() - 1;
1222         }
1223       }
1224 
1225       MethodReference method_ref(dex_file_, method.GetIndex());
1226 
1227       // Lookup method hotness from profile, if available.
1228       // Otherwise assume a default of none-hotness.
1229       ProfileCompilationInfo::MethodHotness method_hotness =
1230           writer_->profile_compilation_info_ != nullptr
1231               ? writer_->profile_compilation_info_->GetMethodHotness(method_ref)
1232               : ProfileCompilationInfo::MethodHotness();
1233 
1234       // Handle duplicate methods by pushing them repeatedly.
1235       OrderedMethodData method_data = {
1236           method_hotness,
1237           oat_class,
1238           compiled_method,
1239           method_ref,
1240           method_offsets_index_,
1241           class_def_index_,
1242           method.GetAccessFlags(),
1243           method.GetCodeItem(),
1244           debug_info_idx
1245       };
1246       ordered_methods_.push_back(method_data);
1247 
1248       method_offsets_index_++;
1249     }
1250 
1251     return true;
1252   }
1253 
ReleaseOrderedMethods()1254   OrderedMethodList ReleaseOrderedMethods() {
1255     if (kOatWriterForceOatCodeLayout || writer_->profile_compilation_info_ != nullptr) {
1256       // Sort by the method ordering criteria (in OrderedMethodData).
1257       // Since most methods will have the same ordering criteria,
1258       // we preserve the original insertion order within the same sort order.
1259       std::stable_sort(ordered_methods_.begin(), ordered_methods_.end());
1260     } else {
1261       // The profile-less behavior is as if every method had 0 hotness
1262       // associated with it.
1263       //
1264       // Since sorting all methods with hotness=0 should give back the same
1265       // order as before, don't do anything.
1266       DCHECK(std::is_sorted(ordered_methods_.begin(), ordered_methods_.end()));
1267     }
1268 
1269     return std::move(ordered_methods_);
1270   }
1271 
1272  private:
1273   // List of compiled methods, later to be sorted by order defined in OrderedMethodData.
1274   // Methods can be inserted more than once in case of duplicated methods.
1275   OrderedMethodList ordered_methods_;
1276 };
1277 
1278 // Given a method order, reserve the offsets for each CompiledMethod in the OAT file.
1279 class OatWriter::LayoutReserveOffsetCodeMethodVisitor : public OrderedMethodVisitor {
1280  public:
LayoutReserveOffsetCodeMethodVisitor(OatWriter * writer,size_t offset,OrderedMethodList ordered_methods)1281   LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1282                                        size_t offset,
1283                                        OrderedMethodList ordered_methods)
1284       : LayoutReserveOffsetCodeMethodVisitor(writer,
1285                                              offset,
1286                                              writer->GetCompilerOptions(),
1287                                              std::move(ordered_methods)) {
1288   }
1289 
VisitComplete()1290   bool VisitComplete() override {
1291     offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
1292     if (generate_debug_info_) {
1293       std::vector<debug::MethodDebugInfo> thunk_infos =
1294           relative_patcher_->GenerateThunkDebugInfo(executable_offset_);
1295       writer_->method_info_.insert(writer_->method_info_.end(),
1296                                    std::make_move_iterator(thunk_infos.begin()),
1297                                    std::make_move_iterator(thunk_infos.end()));
1298     }
1299     return true;
1300   }
1301 
VisitMethod(const OrderedMethodData & method_data)1302   bool VisitMethod(const OrderedMethodData& method_data) override
1303       REQUIRES_SHARED(Locks::mutator_lock_) {
1304     OatClass* oat_class = method_data.oat_class;
1305     CompiledMethod* compiled_method = method_data.compiled_method;
1306     const MethodReference& method_ref = method_data.method_reference;
1307     uint16_t method_offsets_index_ = method_data.method_offsets_index;
1308     size_t class_def_index = method_data.class_def_index;
1309     uint32_t access_flags = method_data.access_flags;
1310     bool has_debug_info = method_data.HasDebugInfo();
1311     size_t debug_info_idx = method_data.debug_info_idx;
1312 
1313     DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1314 
1315     // Derived from CompiledMethod.
1316     uint32_t quick_code_offset = 0;
1317 
1318     ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1319     uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1320     uint32_t thumb_offset = compiled_method->CodeDelta();
1321 
1322     // Deduplicate code arrays if we are not producing debuggable code.
1323     bool deduped = true;
1324     if (debuggable_) {
1325       quick_code_offset = relative_patcher_->GetOffset(method_ref);
1326       if (quick_code_offset != 0u) {
1327         // Duplicate methods, we want the same code for both of them so that the oat writer puts
1328         // the same code in both ArtMethods so that we do not get different oat code at runtime.
1329       } else {
1330         quick_code_offset = NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1331         deduped = false;
1332       }
1333     } else {
1334       quick_code_offset = dedupe_map_.GetOrCreate(
1335           compiled_method,
1336           [this, &deduped, compiled_method, &method_ref, thumb_offset]() {
1337             deduped = false;
1338             return NewQuickCodeOffset(compiled_method, method_ref, thumb_offset);
1339           });
1340     }
1341 
1342     if (code_size != 0) {
1343       if (relative_patcher_->GetOffset(method_ref) != 0u) {
1344         // TODO: Should this be a hard failure?
1345         LOG(WARNING) << "Multiple definitions of "
1346             << method_ref.dex_file->PrettyMethod(method_ref.index)
1347             << " offsets " << relative_patcher_->GetOffset(method_ref)
1348             << " " << quick_code_offset;
1349       } else {
1350         relative_patcher_->SetOffset(method_ref, quick_code_offset);
1351       }
1352     }
1353 
1354     // Update quick method header.
1355     DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1356     OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1357     uint32_t vmap_table_offset = method_header->GetVmapTableOffset();
1358     // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1359     // to 0-offset and we need to adjust it by code_offset.
1360     uint32_t code_offset = quick_code_offset - thumb_offset;
1361     CHECK(!compiled_method->GetQuickCode().empty());
1362     // If the code is compiled, we write the offset of the stack map relative
1363     // to the code.
1364     if (vmap_table_offset != 0u) {
1365       vmap_table_offset += code_offset;
1366       DCHECK_LT(vmap_table_offset, code_offset);
1367     }
1368     *method_header = OatQuickMethodHeader(vmap_table_offset, code_size);
1369 
1370     if (!deduped) {
1371       // Update offsets. (Checksum is updated when writing.)
1372       offset_ += sizeof(*method_header);  // Method header is prepended before code.
1373       offset_ += code_size;
1374     }
1375 
1376     // Exclude quickened dex methods (code_size == 0) since they have no native code.
1377     if (generate_debug_info_ && code_size != 0) {
1378       DCHECK(has_debug_info);
1379       const uint8_t* code_info = compiled_method->GetVmapTable().data();
1380       DCHECK(code_info != nullptr);
1381 
1382       // Record debug information for this function if we are doing that.
1383       debug::MethodDebugInfo& info = writer_->method_info_[debug_info_idx];
1384       info.custom_name = (access_flags & kAccNative) ? "art_jni_trampoline" : "";
1385       info.dex_file = method_ref.dex_file;
1386       info.class_def_index = class_def_index;
1387       info.dex_method_index = method_ref.index;
1388       info.access_flags = access_flags;
1389       // For intrinsics emitted by codegen, the code has no relation to the original code item.
1390       info.code_item = compiled_method->IsIntrinsic() ? nullptr : method_data.code_item;
1391       info.isa = compiled_method->GetInstructionSet();
1392       info.deduped = deduped;
1393       info.is_native_debuggable = native_debuggable_;
1394       info.is_optimized = method_header->IsOptimized();
1395       info.is_code_address_text_relative = true;
1396       info.code_address = code_offset - executable_offset_;
1397       info.code_size = code_size;
1398       info.frame_size_in_bytes = CodeInfo::DecodeFrameInfo(code_info).FrameSizeInBytes();
1399       info.code_info = code_info;
1400       info.cfi = compiled_method->GetCFIInfo();
1401     } else {
1402       DCHECK(!has_debug_info);
1403     }
1404 
1405     DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1406     OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1407     offsets->code_offset_ = quick_code_offset;
1408 
1409     return true;
1410   }
1411 
GetOffset() const1412   size_t GetOffset() const {
1413     return offset_;
1414   }
1415 
1416  private:
LayoutReserveOffsetCodeMethodVisitor(OatWriter * writer,size_t offset,const CompilerOptions & compiler_options,OrderedMethodList ordered_methods)1417   LayoutReserveOffsetCodeMethodVisitor(OatWriter* writer,
1418                                        size_t offset,
1419                                        const CompilerOptions& compiler_options,
1420                                        OrderedMethodList ordered_methods)
1421       : OrderedMethodVisitor(std::move(ordered_methods)),
1422         writer_(writer),
1423         offset_(offset),
1424         relative_patcher_(writer->relative_patcher_),
1425         executable_offset_(writer->oat_header_->GetExecutableOffset()),
1426         debuggable_(compiler_options.GetDebuggable()),
1427         native_debuggable_(compiler_options.GetNativeDebuggable()),
1428         generate_debug_info_(compiler_options.GenerateAnyDebugInfo()) {}
1429 
1430   struct CodeOffsetsKeyComparator {
operator ()art::linker::OatWriter::LayoutReserveOffsetCodeMethodVisitor::CodeOffsetsKeyComparator1431     bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
1432       // Code is deduplicated by CompilerDriver, compare only data pointers.
1433       if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
1434         return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
1435       }
1436       // If the code is the same, all other fields are likely to be the same as well.
1437       if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
1438         return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
1439       }
1440       if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
1441         return lhs->GetPatches().data() < rhs->GetPatches().data();
1442       }
1443       if (UNLIKELY(lhs->IsIntrinsic() != rhs->IsIntrinsic())) {
1444         return rhs->IsIntrinsic();
1445       }
1446       return false;
1447     }
1448   };
1449 
NewQuickCodeOffset(CompiledMethod * compiled_method,const MethodReference & method_ref,uint32_t thumb_offset)1450   uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
1451                               const MethodReference& method_ref,
1452                               uint32_t thumb_offset) {
1453     offset_ = relative_patcher_->ReserveSpace(offset_, compiled_method, method_ref);
1454     offset_ += CodeAlignmentSize(offset_, *compiled_method);
1455     DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1456                          GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1457     return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
1458   }
1459 
1460   OatWriter* writer_;
1461 
1462   // Offset of the code of the compiled methods.
1463   size_t offset_;
1464 
1465   // Deduplication is already done on a pointer basis by the compiler driver,
1466   // so we can simply compare the pointers to find out if things are duplicated.
1467   SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
1468 
1469   // Cache writer_'s members and compiler options.
1470   MultiOatRelativePatcher* relative_patcher_;
1471   uint32_t executable_offset_;
1472   const bool debuggable_;
1473   const bool native_debuggable_;
1474   const bool generate_debug_info_;
1475 };
1476 
1477 class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1478  public:
InitMapMethodVisitor(OatWriter * writer,size_t offset)1479   InitMapMethodVisitor(OatWriter* writer, size_t offset)
1480       : OatDexMethodVisitor(writer, offset),
1481         dedupe_bit_table_(&writer_->code_info_data_) {
1482   }
1483 
VisitMethod(size_t class_def_method_index,const ClassAccessor::Method & method ATTRIBUTE_UNUSED)1484   bool VisitMethod(size_t class_def_method_index,
1485                    const ClassAccessor::Method& method ATTRIBUTE_UNUSED)
1486       override REQUIRES_SHARED(Locks::mutator_lock_) {
1487     OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1488     CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1489 
1490     if (HasCompiledCode(compiled_method)) {
1491       DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1492       DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].GetVmapTableOffset(), 0u);
1493 
1494       ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
1495       if (map.size() != 0u) {
1496         size_t offset = dedupe_code_info_.GetOrCreate(map.data(), [=]() {
1497           // Deduplicate the inner BitTable<>s within the CodeInfo.
1498           return offset_ + dedupe_bit_table_.Dedupe(map.data());
1499         });
1500         // Code offset is not initialized yet, so set the map offset to 0u-offset.
1501         DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
1502         oat_class->method_headers_[method_offsets_index_].SetVmapTableOffset(0u - offset);
1503       }
1504       ++method_offsets_index_;
1505     }
1506 
1507     return true;
1508   }
1509 
1510  private:
1511   // Deduplicate at CodeInfo level. The value is byte offset within code_info_data_.
1512   // This deduplicates the whole CodeInfo object without going into the inner tables.
1513   // The compiler already deduplicated the pointers but it did not dedupe the tables.
1514   SafeMap<const uint8_t*, size_t> dedupe_code_info_;
1515 
1516   // Deduplicate at BitTable level.
1517   CodeInfo::Deduper dedupe_bit_table_;
1518 };
1519 
1520 class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1521  public:
InitImageMethodVisitor(OatWriter * writer,size_t offset,const std::vector<const DexFile * > * dex_files)1522   InitImageMethodVisitor(OatWriter* writer,
1523                          size_t offset,
1524                          const std::vector<const DexFile*>* dex_files)
1525       : OatDexMethodVisitor(writer, offset),
1526         pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
1527         class_loader_(writer->HasImage() ? writer->image_writer_->GetAppClassLoader() : nullptr),
1528         dex_files_(dex_files),
1529         class_linker_(Runtime::Current()->GetClassLinker()) {}
1530 
1531   // Handle copied methods here. Copy pointer to quick code from
1532   // an origin method to a copied method only if they are
1533   // in the same oat file. If the origin and the copied methods are
1534   // in different oat files don't touch the copied method.
1535   // References to other oat files are not supported yet.
StartClass(const DexFile * dex_file,size_t class_def_index)1536   bool StartClass(const DexFile* dex_file, size_t class_def_index) override
1537       REQUIRES_SHARED(Locks::mutator_lock_) {
1538     OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1539     // Skip classes that are not in the image.
1540     if (!IsImageClass()) {
1541       return true;
1542     }
1543     ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1544     const dex::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
1545     ObjPtr<mirror::Class> klass =
1546         class_linker_->LookupResolvedType(class_def.class_idx_, dex_cache, class_loader_);
1547     if (klass != nullptr) {
1548       for (ArtMethod& method : klass->GetCopiedMethods(pointer_size_)) {
1549         // Find origin method. Declaring class and dex_method_idx
1550         // in the copied method should be the same as in the origin
1551         // method.
1552         ObjPtr<mirror::Class> declaring_class = method.GetDeclaringClass();
1553         ArtMethod* origin = declaring_class->FindClassMethod(
1554             declaring_class->GetDexCache(),
1555             method.GetDexMethodIndex(),
1556             pointer_size_);
1557         CHECK(origin != nullptr);
1558         CHECK(!origin->IsDirect());
1559         CHECK(origin->GetDeclaringClass() == declaring_class);
1560         if (IsInOatFile(&declaring_class->GetDexFile())) {
1561           const void* code_ptr =
1562               origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1563           if (code_ptr == nullptr) {
1564             methods_to_process_.push_back(std::make_pair(&method, origin));
1565           } else {
1566             method.SetEntryPointFromQuickCompiledCodePtrSize(
1567                 code_ptr, pointer_size_);
1568           }
1569         }
1570       }
1571     }
1572     return true;
1573   }
1574 
VisitMethod(size_t class_def_method_index,const ClassAccessor::Method & method)1575   bool VisitMethod(size_t class_def_method_index, const ClassAccessor::Method& method) override
1576       REQUIRES_SHARED(Locks::mutator_lock_) {
1577     // Skip methods that are not in the image.
1578     if (!IsImageClass()) {
1579       return true;
1580     }
1581 
1582     OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
1583     CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1584 
1585     OatMethodOffsets offsets(0u);
1586     if (HasCompiledCode(compiled_method)) {
1587       DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1588       offsets = oat_class->method_offsets_[method_offsets_index_];
1589       ++method_offsets_index_;
1590     }
1591 
1592     Thread* self = Thread::Current();
1593     ObjPtr<mirror::DexCache> dex_cache = class_linker_->FindDexCache(self, *dex_file_);
1594     ArtMethod* resolved_method;
1595     if (writer_->GetCompilerOptions().IsBootImage() ||
1596         writer_->GetCompilerOptions().IsBootImageExtension()) {
1597       resolved_method = class_linker_->LookupResolvedMethod(
1598           method.GetIndex(), dex_cache, /*class_loader=*/ nullptr);
1599       if (resolved_method == nullptr) {
1600         LOG(FATAL) << "Unexpected failure to look up a method: "
1601             << dex_file_->PrettyMethod(method.GetIndex(), true);
1602         UNREACHABLE();
1603       }
1604     } else {
1605       // Should already have been resolved by the compiler.
1606       // It may not be resolved if the class failed to verify, in this case, don't set the
1607       // entrypoint. This is not fatal since we shall use a resolution method.
1608       resolved_method = class_linker_->LookupResolvedMethod(method.GetIndex(),
1609                                                             dex_cache,
1610                                                             class_loader_);
1611     }
1612     if (resolved_method != nullptr &&
1613         compiled_method != nullptr &&
1614         compiled_method->GetQuickCode().size() != 0) {
1615       resolved_method->SetEntryPointFromQuickCompiledCodePtrSize(
1616           reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
1617     }
1618 
1619     return true;
1620   }
1621 
1622   // Check whether current class is image class
IsImageClass()1623   bool IsImageClass() {
1624     const dex::TypeId& type_id =
1625         dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
1626     const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
1627     return writer_->GetCompilerOptions().IsImageClass(class_descriptor);
1628   }
1629 
1630   // Check whether specified dex file is in the compiled oat file.
IsInOatFile(const DexFile * dex_file)1631   bool IsInOatFile(const DexFile* dex_file) {
1632     return ContainsElement(*dex_files_, dex_file);
1633   }
1634 
1635   // Assign a pointer to quick code for copied methods
1636   // not handled in the method StartClass
Postprocess()1637   void Postprocess() REQUIRES_SHARED(Locks::mutator_lock_) {
1638     for (std::pair<ArtMethod*, ArtMethod*>& p : methods_to_process_) {
1639       ArtMethod* method = p.first;
1640       ArtMethod* origin = p.second;
1641       const void* code_ptr =
1642           origin->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1643       if (code_ptr != nullptr) {
1644         method->SetEntryPointFromQuickCompiledCodePtrSize(code_ptr, pointer_size_);
1645       }
1646     }
1647   }
1648 
1649  private:
1650   const PointerSize pointer_size_;
1651   ObjPtr<mirror::ClassLoader> class_loader_;
1652   const std::vector<const DexFile*>* dex_files_;
1653   ClassLinker* const class_linker_;
1654   std::vector<std::pair<ArtMethod*, ArtMethod*>> methods_to_process_;
1655 };
1656 
1657 class OatWriter::WriteCodeMethodVisitor : public OrderedMethodVisitor {
1658  public:
WriteCodeMethodVisitor(OatWriter * writer,OutputStream * out,const size_t file_offset,size_t relative_offset,OrderedMethodList ordered_methods)1659   WriteCodeMethodVisitor(OatWriter* writer,
1660                          OutputStream* out,
1661                          const size_t file_offset,
1662                          size_t relative_offset,
1663                          OrderedMethodList ordered_methods)
1664       : OrderedMethodVisitor(std::move(ordered_methods)),
1665         writer_(writer),
1666         offset_(relative_offset),
1667         dex_file_(nullptr),
1668         pointer_size_(GetInstructionSetPointerSize(writer_->compiler_options_.GetInstructionSet())),
1669         class_loader_(writer->HasImage() ? writer->image_writer_->GetAppClassLoader() : nullptr),
1670         out_(out),
1671         file_offset_(file_offset),
1672         class_linker_(Runtime::Current()->GetClassLinker()),
1673         dex_cache_(nullptr),
1674         no_thread_suspension_("OatWriter patching") {
1675     patched_code_.reserve(16 * KB);
1676     if (writer_->GetCompilerOptions().IsBootImage() ||
1677         writer_->GetCompilerOptions().IsBootImageExtension()) {
1678       // If we're creating the image, the address space must be ready so that we can apply patches.
1679       CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
1680     }
1681   }
1682 
VisitStart()1683   bool VisitStart() override {
1684     return true;
1685   }
1686 
UpdateDexFileAndDexCache(const DexFile * dex_file)1687   void UpdateDexFileAndDexCache(const DexFile* dex_file)
1688       REQUIRES_SHARED(Locks::mutator_lock_) {
1689     dex_file_ = dex_file;
1690 
1691     // Ordered method visiting is only for compiled methods.
1692     DCHECK(writer_->MayHaveCompiledMethods());
1693 
1694     if (writer_->GetCompilerOptions().IsAotCompilationEnabled()) {
1695       // Only need to set the dex cache if we have compilation. Other modes might have unloaded it.
1696       if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1697         dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
1698         DCHECK(dex_cache_ != nullptr);
1699       }
1700     }
1701   }
1702 
VisitComplete()1703   bool VisitComplete() override {
1704     offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
1705     if (UNLIKELY(offset_ == 0u)) {
1706       PLOG(ERROR) << "Failed to write final relative call thunks";
1707       return false;
1708     }
1709     return true;
1710   }
1711 
VisitMethod(const OrderedMethodData & method_data)1712   bool VisitMethod(const OrderedMethodData& method_data) override
1713       REQUIRES_SHARED(Locks::mutator_lock_) {
1714     const MethodReference& method_ref = method_data.method_reference;
1715     UpdateDexFileAndDexCache(method_ref.dex_file);
1716 
1717     OatClass* oat_class = method_data.oat_class;
1718     CompiledMethod* compiled_method = method_data.compiled_method;
1719     uint16_t method_offsets_index = method_data.method_offsets_index;
1720 
1721     // No thread suspension since dex_cache_ that may get invalidated if that occurs.
1722     ScopedAssertNoThreadSuspension tsc(__FUNCTION__);
1723     DCHECK(HasCompiledCode(compiled_method)) << method_ref.PrettyMethod();
1724 
1725     // TODO: cleanup DCHECK_OFFSET_ to accept file_offset as parameter.
1726     size_t file_offset = file_offset_;  // Used by DCHECK_OFFSET_ macro.
1727     OutputStream* out = out_;
1728 
1729     ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
1730     uint32_t code_size = quick_code.size() * sizeof(uint8_t);
1731 
1732     // Deduplicate code arrays.
1733     const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index];
1734     if (method_offsets.code_offset_ > offset_) {
1735       offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1736       if (offset_ == 0u) {
1737         ReportWriteFailure("relative call thunk", method_ref);
1738         return false;
1739       }
1740       uint32_t alignment_size = CodeAlignmentSize(offset_, *compiled_method);
1741       if (alignment_size != 0) {
1742         if (!writer_->WriteCodeAlignment(out, alignment_size)) {
1743           ReportWriteFailure("code alignment padding", method_ref);
1744           return false;
1745         }
1746         offset_ += alignment_size;
1747         DCHECK_OFFSET_();
1748       }
1749       DCHECK_ALIGNED_PARAM(offset_ + sizeof(OatQuickMethodHeader),
1750                            GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1751       DCHECK_EQ(method_offsets.code_offset_,
1752                 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1753           << dex_file_->PrettyMethod(method_ref.index);
1754       const OatQuickMethodHeader& method_header =
1755           oat_class->method_headers_[method_offsets_index];
1756       if (!out->WriteFully(&method_header, sizeof(method_header))) {
1757         ReportWriteFailure("method header", method_ref);
1758         return false;
1759       }
1760       writer_->size_method_header_ += sizeof(method_header);
1761       offset_ += sizeof(method_header);
1762       DCHECK_OFFSET_();
1763 
1764       if (!compiled_method->GetPatches().empty()) {
1765         patched_code_.assign(quick_code.begin(), quick_code.end());
1766         quick_code = ArrayRef<const uint8_t>(patched_code_);
1767         for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1768           uint32_t literal_offset = patch.LiteralOffset();
1769           switch (patch.GetType()) {
1770             case LinkerPatch::Type::kIntrinsicReference: {
1771               uint32_t target_offset = GetTargetIntrinsicReferenceOffset(patch);
1772               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1773                                                                    patch,
1774                                                                    offset_ + literal_offset,
1775                                                                    target_offset);
1776               break;
1777             }
1778             case LinkerPatch::Type::kDataBimgRelRo: {
1779               uint32_t target_offset =
1780                   writer_->data_bimg_rel_ro_start_ +
1781                   writer_->data_bimg_rel_ro_entries_.Get(patch.BootImageOffset());
1782               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1783                                                                    patch,
1784                                                                    offset_ + literal_offset,
1785                                                                    target_offset);
1786               break;
1787             }
1788             case LinkerPatch::Type::kMethodBssEntry: {
1789               uint32_t target_offset =
1790                   writer_->bss_start_ + writer_->bss_method_entries_.Get(patch.TargetMethod());
1791               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1792                                                                    patch,
1793                                                                    offset_ + literal_offset,
1794                                                                    target_offset);
1795               break;
1796             }
1797             case LinkerPatch::Type::kCallRelative: {
1798               // NOTE: Relative calls across oat files are not supported.
1799               uint32_t target_offset = GetTargetOffset(patch);
1800               writer_->relative_patcher_->PatchCall(&patched_code_,
1801                                                     literal_offset,
1802                                                     offset_ + literal_offset,
1803                                                     target_offset);
1804               break;
1805             }
1806             case LinkerPatch::Type::kStringRelative: {
1807               uint32_t target_offset = GetTargetObjectOffset(GetTargetString(patch));
1808               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1809                                                                    patch,
1810                                                                    offset_ + literal_offset,
1811                                                                    target_offset);
1812               break;
1813             }
1814             case LinkerPatch::Type::kStringBssEntry: {
1815               StringReference ref(patch.TargetStringDexFile(), patch.TargetStringIndex());
1816               uint32_t target_offset =
1817                   writer_->bss_start_ + writer_->bss_string_entries_.Get(ref);
1818               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1819                                                                    patch,
1820                                                                    offset_ + literal_offset,
1821                                                                    target_offset);
1822               break;
1823             }
1824             case LinkerPatch::Type::kTypeRelative: {
1825               uint32_t target_offset = GetTargetObjectOffset(GetTargetType(patch));
1826               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1827                                                                    patch,
1828                                                                    offset_ + literal_offset,
1829                                                                    target_offset);
1830               break;
1831             }
1832             case LinkerPatch::Type::kTypeBssEntry: {
1833               TypeReference ref(patch.TargetTypeDexFile(), patch.TargetTypeIndex());
1834               uint32_t target_offset = writer_->bss_start_ + writer_->bss_type_entries_.Get(ref);
1835               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1836                                                                    patch,
1837                                                                    offset_ + literal_offset,
1838                                                                    target_offset);
1839               break;
1840             }
1841             case LinkerPatch::Type::kMethodRelative: {
1842               uint32_t target_offset = GetTargetMethodOffset(GetTargetMethod(patch));
1843               writer_->relative_patcher_->PatchPcRelativeReference(&patched_code_,
1844                                                                    patch,
1845                                                                    offset_ + literal_offset,
1846                                                                    target_offset);
1847               break;
1848             }
1849             case LinkerPatch::Type::kCallEntrypoint: {
1850               writer_->relative_patcher_->PatchEntrypointCall(&patched_code_,
1851                                                               patch,
1852                                                               offset_ + literal_offset);
1853               break;
1854             }
1855             case LinkerPatch::Type::kBakerReadBarrierBranch: {
1856               writer_->relative_patcher_->PatchBakerReadBarrierBranch(&patched_code_,
1857                                                                       patch,
1858                                                                       offset_ + literal_offset);
1859               break;
1860             }
1861             default: {
1862               DCHECK(false) << "Unexpected linker patch type: " << patch.GetType();
1863               break;
1864             }
1865           }
1866         }
1867       }
1868 
1869       if (!out->WriteFully(quick_code.data(), code_size)) {
1870         ReportWriteFailure("method code", method_ref);
1871         return false;
1872       }
1873       writer_->size_code_ += code_size;
1874       offset_ += code_size;
1875     }
1876     DCHECK_OFFSET_();
1877 
1878     return true;
1879   }
1880 
GetOffset() const1881   size_t GetOffset() const {
1882     return offset_;
1883   }
1884 
1885  private:
1886   OatWriter* const writer_;
1887 
1888   // Updated in VisitMethod as methods are written out.
1889   size_t offset_;
1890 
1891   // Potentially varies with every different VisitMethod.
1892   // Used to determine which DexCache to use when finding ArtMethods.
1893   const DexFile* dex_file_;
1894 
1895   // Pointer size we are compiling to.
1896   const PointerSize pointer_size_;
1897   // The image writer's classloader, if there is one, else null.
1898   ObjPtr<mirror::ClassLoader> class_loader_;
1899   // Stream to output file, where the OAT code will be written to.
1900   OutputStream* const out_;
1901   const size_t file_offset_;
1902   ClassLinker* const class_linker_;
1903   ObjPtr<mirror::DexCache> dex_cache_;
1904   std::vector<uint8_t> patched_code_;
1905   const ScopedAssertNoThreadSuspension no_thread_suspension_;
1906 
ReportWriteFailure(const char * what,const MethodReference & method_ref)1907   void ReportWriteFailure(const char* what, const MethodReference& method_ref) {
1908     PLOG(ERROR) << "Failed to write " << what << " for "
1909         << method_ref.PrettyMethod() << " to " << out_->GetLocation();
1910   }
1911 
GetTargetMethod(const LinkerPatch & patch)1912   ArtMethod* GetTargetMethod(const LinkerPatch& patch)
1913       REQUIRES_SHARED(Locks::mutator_lock_) {
1914     MethodReference ref = patch.TargetMethod();
1915     ObjPtr<mirror::DexCache> dex_cache =
1916         (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(
1917             Thread::Current(), *ref.dex_file);
1918     ArtMethod* method =
1919         class_linker_->LookupResolvedMethod(ref.index, dex_cache, class_loader_);
1920     CHECK(method != nullptr);
1921     return method;
1922   }
1923 
GetTargetOffset(const LinkerPatch & patch)1924   uint32_t GetTargetOffset(const LinkerPatch& patch) REQUIRES_SHARED(Locks::mutator_lock_) {
1925     uint32_t target_offset = writer_->relative_patcher_->GetOffset(patch.TargetMethod());
1926     // If there's no new compiled code, we need to point to the correct trampoline.
1927     if (UNLIKELY(target_offset == 0)) {
1928       ArtMethod* target = GetTargetMethod(patch);
1929       DCHECK(target != nullptr);
1930       // TODO: Remove kCallRelative? This patch type is currently not in use.
1931       // If we want to use it again, we should make sure that we either use it
1932       // only for target methods that were actually compiled, or call the
1933       // method dispatch thunk. Currently, ARM/ARM64 patchers would emit the
1934       // thunk for far `target_offset` (so we could teach them to use the
1935       // thunk for `target_offset == 0`) but x86/x86-64 patchers do not.
1936       // (When this was originally implemented, every oat file contained
1937       // trampolines, so we could just return their offset here. Now only
1938       // the boot image contains them, so this is not always an option.)
1939       LOG(FATAL) << "The target method was not compiled.";
1940     }
1941     return target_offset;
1942   }
1943 
GetDexCache(const DexFile * target_dex_file)1944   ObjPtr<mirror::DexCache> GetDexCache(const DexFile* target_dex_file)
1945       REQUIRES_SHARED(Locks::mutator_lock_) {
1946     return (target_dex_file == dex_file_)
1947         ? dex_cache_
1948         : class_linker_->FindDexCache(Thread::Current(), *target_dex_file);
1949   }
1950 
GetTargetType(const LinkerPatch & patch)1951   ObjPtr<mirror::Class> GetTargetType(const LinkerPatch& patch)
1952       REQUIRES_SHARED(Locks::mutator_lock_) {
1953     DCHECK(writer_->HasImage());
1954     ObjPtr<mirror::DexCache> dex_cache = GetDexCache(patch.TargetTypeDexFile());
1955     ObjPtr<mirror::Class> type =
1956         class_linker_->LookupResolvedType(patch.TargetTypeIndex(), dex_cache, class_loader_);
1957     CHECK(type != nullptr);
1958     return type;
1959   }
1960 
GetTargetString(const LinkerPatch & patch)1961   ObjPtr<mirror::String> GetTargetString(const LinkerPatch& patch)
1962       REQUIRES_SHARED(Locks::mutator_lock_) {
1963     ClassLinker* linker = Runtime::Current()->GetClassLinker();
1964     ObjPtr<mirror::String> string =
1965         linker->LookupString(patch.TargetStringIndex(), GetDexCache(patch.TargetStringDexFile()));
1966     DCHECK(string != nullptr);
1967     DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
1968            writer_->GetCompilerOptions().IsBootImageExtension());
1969     return string;
1970   }
1971 
GetTargetIntrinsicReferenceOffset(const LinkerPatch & patch)1972   uint32_t GetTargetIntrinsicReferenceOffset(const LinkerPatch& patch)
1973       REQUIRES_SHARED(Locks::mutator_lock_) {
1974     DCHECK(writer_->GetCompilerOptions().IsBootImage());
1975     const void* address =
1976         writer_->image_writer_->GetIntrinsicReferenceAddress(patch.IntrinsicData());
1977     size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1978     uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1979     // TODO: Clean up offset types. The target offset must be treated as signed.
1980     return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(address) - oat_data_begin);
1981   }
1982 
GetTargetMethodOffset(ArtMethod * method)1983   uint32_t GetTargetMethodOffset(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
1984     DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
1985            writer_->GetCompilerOptions().IsBootImageExtension());
1986     method = writer_->image_writer_->GetImageMethodAddress(method);
1987     size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1988     uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
1989     // TODO: Clean up offset types. The target offset must be treated as signed.
1990     return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(method) - oat_data_begin);
1991   }
1992 
GetTargetObjectOffset(ObjPtr<mirror::Object> object)1993   uint32_t GetTargetObjectOffset(ObjPtr<mirror::Object> object)
1994       REQUIRES_SHARED(Locks::mutator_lock_) {
1995     DCHECK(writer_->GetCompilerOptions().IsBootImage() ||
1996            writer_->GetCompilerOptions().IsBootImageExtension());
1997     object = writer_->image_writer_->GetImageAddress(object.Ptr());
1998     size_t oat_index = writer_->image_writer_->GetOatIndexForDexFile(dex_file_);
1999     uintptr_t oat_data_begin = writer_->image_writer_->GetOatDataBegin(oat_index);
2000     // TODO: Clean up offset types. The target offset must be treated as signed.
2001     return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(object.Ptr()) - oat_data_begin);
2002   }
2003 };
2004 
2005 // Visit all methods from all classes in all dex files with the specified visitor.
VisitDexMethods(DexMethodVisitor * visitor)2006 bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
2007   for (const DexFile* dex_file : *dex_files_) {
2008     for (ClassAccessor accessor : dex_file->GetClasses()) {
2009       if (UNLIKELY(!visitor->StartClass(dex_file, accessor.GetClassDefIndex()))) {
2010         return false;
2011       }
2012       if (MayHaveCompiledMethods()) {
2013         size_t class_def_method_index = 0u;
2014         for (const ClassAccessor::Method& method : accessor.GetMethods()) {
2015           if (!visitor->VisitMethod(class_def_method_index, method)) {
2016             return false;
2017           }
2018           ++class_def_method_index;
2019         }
2020       }
2021       if (UNLIKELY(!visitor->EndClass())) {
2022         return false;
2023       }
2024     }
2025   }
2026   return true;
2027 }
2028 
InitOatHeader(uint32_t num_dex_files,SafeMap<std::string,std::string> * key_value_store)2029 size_t OatWriter::InitOatHeader(uint32_t num_dex_files,
2030                                 SafeMap<std::string, std::string>* key_value_store) {
2031   TimingLogger::ScopedTiming split("InitOatHeader", timings_);
2032   // Check that oat version when runtime was compiled matches the oat version
2033   // when dex2oat was compiled. We have seen cases where they got out of sync.
2034   constexpr std::array<uint8_t, 4> dex2oat_oat_version = OatHeader::kOatVersion;
2035   OatHeader::CheckOatVersion(dex2oat_oat_version);
2036   oat_header_.reset(OatHeader::Create(GetCompilerOptions().GetInstructionSet(),
2037                                       GetCompilerOptions().GetInstructionSetFeatures(),
2038                                       num_dex_files,
2039                                       key_value_store));
2040   size_oat_header_ += sizeof(OatHeader);
2041   size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
2042   return oat_header_->GetHeaderSize();
2043 }
2044 
InitClassOffsets(size_t offset)2045 size_t OatWriter::InitClassOffsets(size_t offset) {
2046   // Reserve space for class offsets in OAT and update class_offsets_offset_.
2047   for (OatDexFile& oat_dex_file : oat_dex_files_) {
2048     DCHECK_EQ(oat_dex_file.class_offsets_offset_, 0u);
2049     if (!oat_dex_file.class_offsets_.empty()) {
2050       // Class offsets are required to be 4 byte aligned.
2051       offset = RoundUp(offset, 4u);
2052       oat_dex_file.class_offsets_offset_ = offset;
2053       offset += oat_dex_file.GetClassOffsetsRawSize();
2054       DCHECK_ALIGNED(offset, 4u);
2055     }
2056   }
2057   return offset;
2058 }
2059 
InitOatClasses(size_t offset)2060 size_t OatWriter::InitOatClasses(size_t offset) {
2061   // calculate the offsets within OatDexFiles to OatClasses
2062   InitOatClassesMethodVisitor visitor(this, offset);
2063   bool success = VisitDexMethods(&visitor);
2064   CHECK(success);
2065   offset = visitor.GetOffset();
2066 
2067   // Update oat_dex_files_.
2068   auto oat_class_it = oat_class_headers_.begin();
2069   for (OatDexFile& oat_dex_file : oat_dex_files_) {
2070     for (uint32_t& class_offset : oat_dex_file.class_offsets_) {
2071       DCHECK(oat_class_it != oat_class_headers_.end());
2072       class_offset = oat_class_it->offset_;
2073       ++oat_class_it;
2074     }
2075   }
2076   CHECK(oat_class_it == oat_class_headers_.end());
2077 
2078   return offset;
2079 }
2080 
InitOatMaps(size_t offset)2081 size_t OatWriter::InitOatMaps(size_t offset) {
2082   if (!MayHaveCompiledMethods()) {
2083     return offset;
2084   }
2085   {
2086     InitMapMethodVisitor visitor(this, offset);
2087     bool success = VisitDexMethods(&visitor);
2088     DCHECK(success);
2089     code_info_data_.shrink_to_fit();
2090     offset += code_info_data_.size();
2091   }
2092   return offset;
2093 }
2094 
2095 template <typename GetBssOffset>
CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,size_t slot_size,const BitVector & indexes,GetBssOffset get_bss_offset)2096 static size_t CalculateNumberOfIndexBssMappingEntries(size_t number_of_indexes,
2097                                                       size_t slot_size,
2098                                                       const BitVector& indexes,
2099                                                       GetBssOffset get_bss_offset) {
2100   IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2101   size_t number_of_entries = 0u;
2102   bool first_index = true;
2103   for (uint32_t index : indexes.Indexes()) {
2104     uint32_t bss_offset = get_bss_offset(index);
2105     if (first_index || !encoder.TryMerge(index, bss_offset)) {
2106       encoder.Reset(index, bss_offset);
2107       ++number_of_entries;
2108       first_index = false;
2109     }
2110   }
2111   DCHECK_NE(number_of_entries, 0u);
2112   return number_of_entries;
2113 }
2114 
2115 template <typename GetBssOffset>
CalculateIndexBssMappingSize(size_t number_of_indexes,size_t slot_size,const BitVector & indexes,GetBssOffset get_bss_offset)2116 static size_t CalculateIndexBssMappingSize(size_t number_of_indexes,
2117                                            size_t slot_size,
2118                                            const BitVector& indexes,
2119                                            GetBssOffset get_bss_offset) {
2120   size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(number_of_indexes,
2121                                                                      slot_size,
2122                                                                      indexes,
2123                                                                      get_bss_offset);
2124   return IndexBssMapping::ComputeSize(number_of_entries);
2125 }
2126 
InitIndexBssMappings(size_t offset)2127 size_t OatWriter::InitIndexBssMappings(size_t offset) {
2128   if (bss_method_entry_references_.empty() &&
2129       bss_type_entry_references_.empty() &&
2130       bss_string_entry_references_.empty()) {
2131     return offset;
2132   }
2133   // If there are any classes, the class offsets allocation aligns the offset
2134   // and we cannot have any index bss mappings without class offsets.
2135   static_assert(alignof(IndexBssMapping) == 4u, "IndexBssMapping alignment check.");
2136   DCHECK_ALIGNED(offset, 4u);
2137 
2138   size_t number_of_method_dex_files = 0u;
2139   size_t number_of_type_dex_files = 0u;
2140   size_t number_of_string_dex_files = 0u;
2141   PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2142   for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2143     const DexFile* dex_file = (*dex_files_)[i];
2144     auto method_it = bss_method_entry_references_.find(dex_file);
2145     if (method_it != bss_method_entry_references_.end()) {
2146       const BitVector& method_indexes = method_it->second;
2147       ++number_of_method_dex_files;
2148       oat_dex_files_[i].method_bss_mapping_offset_ = offset;
2149       offset += CalculateIndexBssMappingSize(
2150           dex_file->NumMethodIds(),
2151           static_cast<size_t>(pointer_size),
2152           method_indexes,
2153           [=](uint32_t index) {
2154             return bss_method_entries_.Get({dex_file, index});
2155           });
2156     }
2157 
2158     auto type_it = bss_type_entry_references_.find(dex_file);
2159     if (type_it != bss_type_entry_references_.end()) {
2160       const BitVector& type_indexes = type_it->second;
2161       ++number_of_type_dex_files;
2162       oat_dex_files_[i].type_bss_mapping_offset_ = offset;
2163       offset += CalculateIndexBssMappingSize(
2164           dex_file->NumTypeIds(),
2165           sizeof(GcRoot<mirror::Class>),
2166           type_indexes,
2167           [=](uint32_t index) {
2168             return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2169           });
2170     }
2171 
2172     auto string_it = bss_string_entry_references_.find(dex_file);
2173     if (string_it != bss_string_entry_references_.end()) {
2174       const BitVector& string_indexes = string_it->second;
2175       ++number_of_string_dex_files;
2176       oat_dex_files_[i].string_bss_mapping_offset_ = offset;
2177       offset += CalculateIndexBssMappingSize(
2178           dex_file->NumStringIds(),
2179           sizeof(GcRoot<mirror::String>),
2180           string_indexes,
2181           [=](uint32_t index) {
2182             return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2183           });
2184     }
2185   }
2186   // Check that all dex files targeted by bss entries are in `*dex_files_`.
2187   CHECK_EQ(number_of_method_dex_files, bss_method_entry_references_.size());
2188   CHECK_EQ(number_of_type_dex_files, bss_type_entry_references_.size());
2189   CHECK_EQ(number_of_string_dex_files, bss_string_entry_references_.size());
2190   return offset;
2191 }
2192 
InitOatDexFiles(size_t offset)2193 size_t OatWriter::InitOatDexFiles(size_t offset) {
2194   // Initialize offsets of oat dex files.
2195   for (OatDexFile& oat_dex_file : oat_dex_files_) {
2196     oat_dex_file.offset_ = offset;
2197     offset += oat_dex_file.SizeOf();
2198   }
2199   return offset;
2200 }
2201 
InitOatCode(size_t offset)2202 size_t OatWriter::InitOatCode(size_t offset) {
2203   // calculate the offsets within OatHeader to executable code
2204   size_t old_offset = offset;
2205   // required to be on a new page boundary
2206   offset = RoundUp(offset, kPageSize);
2207   oat_header_->SetExecutableOffset(offset);
2208   size_executable_offset_alignment_ = offset - old_offset;
2209   if (GetCompilerOptions().IsBootImage() && primary_oat_file_) {
2210     InstructionSet instruction_set = compiler_options_.GetInstructionSet();
2211     const bool generate_debug_info = GetCompilerOptions().GenerateAnyDebugInfo();
2212     size_t adjusted_offset = offset;
2213 
2214     #define DO_TRAMPOLINE(field, fn_name)                                   \
2215       /* Pad with at least four 0xFFs so we can do DCHECKs in OatQuickMethodHeader */ \
2216       offset = CompiledCode::AlignCode(offset + 4, instruction_set);        \
2217       adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set);  \
2218       oat_header_->Set ## fn_name ## Offset(adjusted_offset);               \
2219       (field) = compiler_driver_->Create ## fn_name();                      \
2220       if (generate_debug_info) {                                            \
2221         debug::MethodDebugInfo info = {};                                   \
2222         info.custom_name = #fn_name;                                        \
2223         info.isa = instruction_set;                                         \
2224         info.is_code_address_text_relative = true;                          \
2225         /* Use the code offset rather than the `adjusted_offset`. */        \
2226         info.code_address = offset - oat_header_->GetExecutableOffset();    \
2227         info.code_size = (field)->size();                                   \
2228         method_info_.push_back(std::move(info));                            \
2229       }                                                                     \
2230       offset += (field)->size();
2231 
2232     DO_TRAMPOLINE(jni_dlsym_lookup_trampoline_, JniDlsymLookupTrampoline);
2233     DO_TRAMPOLINE(jni_dlsym_lookup_critical_trampoline_, JniDlsymLookupCriticalTrampoline);
2234     DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
2235     DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
2236     DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
2237     DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
2238 
2239     #undef DO_TRAMPOLINE
2240   } else {
2241     oat_header_->SetJniDlsymLookupTrampolineOffset(0);
2242     oat_header_->SetJniDlsymLookupCriticalTrampolineOffset(0);
2243     oat_header_->SetQuickGenericJniTrampolineOffset(0);
2244     oat_header_->SetQuickImtConflictTrampolineOffset(0);
2245     oat_header_->SetQuickResolutionTrampolineOffset(0);
2246     oat_header_->SetQuickToInterpreterBridgeOffset(0);
2247   }
2248   return offset;
2249 }
2250 
InitOatCodeDexFiles(size_t offset)2251 size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
2252   if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
2253     if (kOatWriterDebugOatCodeLayout) {
2254       LOG(INFO) << "InitOatCodeDexFiles: OatWriter("
2255                 << this << "), "
2256                 << "compilation is disabled";
2257     }
2258 
2259     return offset;
2260   }
2261   bool success = false;
2262 
2263   {
2264     ScopedObjectAccess soa(Thread::Current());
2265 
2266     LayoutCodeMethodVisitor layout_code_visitor(this, offset);
2267     success = VisitDexMethods(&layout_code_visitor);
2268     DCHECK(success);
2269 
2270     LayoutReserveOffsetCodeMethodVisitor layout_reserve_code_visitor(
2271         this,
2272         offset,
2273         layout_code_visitor.ReleaseOrderedMethods());
2274     success = layout_reserve_code_visitor.Visit();
2275     DCHECK(success);
2276     offset = layout_reserve_code_visitor.GetOffset();
2277 
2278     // Save the method order because the WriteCodeMethodVisitor will need this
2279     // order again.
2280     DCHECK(ordered_methods_ == nullptr);
2281     ordered_methods_.reset(
2282         new OrderedMethodList(
2283             layout_reserve_code_visitor.ReleaseOrderedMethods()));
2284 
2285     if (kOatWriterDebugOatCodeLayout) {
2286       LOG(INFO) << "IniatOatCodeDexFiles: method order: ";
2287       for (const OrderedMethodData& ordered_method : *ordered_methods_) {
2288         std::string pretty_name = ordered_method.method_reference.PrettyMethod();
2289         LOG(INFO) << pretty_name
2290                   << "@ offset "
2291                   << relative_patcher_->GetOffset(ordered_method.method_reference)
2292                   << " X hotness "
2293                   << reinterpret_cast<void*>(ordered_method.method_hotness.GetFlags());
2294       }
2295     }
2296   }
2297 
2298   if (HasImage()) {
2299     ScopedObjectAccess soa(Thread::Current());
2300     ScopedAssertNoThreadSuspension sants("Init image method visitor", Thread::Current());
2301     InitImageMethodVisitor image_visitor(this, offset, dex_files_);
2302     success = VisitDexMethods(&image_visitor);
2303     image_visitor.Postprocess();
2304     DCHECK(success);
2305     offset = image_visitor.GetOffset();
2306   }
2307 
2308   return offset;
2309 }
2310 
InitDataBimgRelRoLayout(size_t offset)2311 size_t OatWriter::InitDataBimgRelRoLayout(size_t offset) {
2312   DCHECK_EQ(data_bimg_rel_ro_size_, 0u);
2313   if (data_bimg_rel_ro_entries_.empty()) {
2314     // Nothing to put to the .data.bimg.rel.ro section.
2315     return offset;
2316   }
2317 
2318   data_bimg_rel_ro_start_ = RoundUp(offset, kPageSize);
2319 
2320   for (auto& entry : data_bimg_rel_ro_entries_) {
2321     size_t& entry_offset = entry.second;
2322     entry_offset = data_bimg_rel_ro_size_;
2323     data_bimg_rel_ro_size_ += sizeof(uint32_t);
2324   }
2325 
2326   offset = data_bimg_rel_ro_start_ + data_bimg_rel_ro_size_;
2327   return offset;
2328 }
2329 
InitBssLayout(InstructionSet instruction_set)2330 void OatWriter::InitBssLayout(InstructionSet instruction_set) {
2331   {
2332     InitBssLayoutMethodVisitor visitor(this);
2333     bool success = VisitDexMethods(&visitor);
2334     DCHECK(success);
2335   }
2336 
2337   DCHECK_EQ(bss_size_, 0u);
2338   if (bss_method_entries_.empty() &&
2339       bss_type_entries_.empty() &&
2340       bss_string_entries_.empty()) {
2341     // Nothing to put to the .bss section.
2342     return;
2343   }
2344 
2345   PointerSize pointer_size = GetInstructionSetPointerSize(instruction_set);
2346   bss_methods_offset_ = bss_size_;
2347 
2348   // Prepare offsets for .bss ArtMethod entries.
2349   for (auto& entry : bss_method_entries_) {
2350     DCHECK_EQ(entry.second, 0u);
2351     entry.second = bss_size_;
2352     bss_size_ += static_cast<size_t>(pointer_size);
2353   }
2354 
2355   bss_roots_offset_ = bss_size_;
2356 
2357   // Prepare offsets for .bss Class entries.
2358   for (auto& entry : bss_type_entries_) {
2359     DCHECK_EQ(entry.second, 0u);
2360     entry.second = bss_size_;
2361     bss_size_ += sizeof(GcRoot<mirror::Class>);
2362   }
2363   // Prepare offsets for .bss String entries.
2364   for (auto& entry : bss_string_entries_) {
2365     DCHECK_EQ(entry.second, 0u);
2366     entry.second = bss_size_;
2367     bss_size_ += sizeof(GcRoot<mirror::String>);
2368   }
2369 }
2370 
WriteRodata(OutputStream * out)2371 bool OatWriter::WriteRodata(OutputStream* out) {
2372   CHECK(write_state_ == WriteState::kWriteRoData);
2373 
2374   size_t file_offset = oat_data_offset_;
2375   off_t current_offset = out->Seek(0, kSeekCurrent);
2376   if (current_offset == static_cast<off_t>(-1)) {
2377     PLOG(ERROR) << "Failed to retrieve current position in " << out->GetLocation();
2378   }
2379   DCHECK_GE(static_cast<size_t>(current_offset), file_offset + oat_header_->GetHeaderSize());
2380   size_t relative_offset = current_offset - file_offset;
2381 
2382   // Wrap out to update checksum with each write.
2383   ChecksumUpdatingOutputStream checksum_updating_out(out, this);
2384   out = &checksum_updating_out;
2385 
2386   relative_offset = WriteClassOffsets(out, file_offset, relative_offset);
2387   if (relative_offset == 0) {
2388     PLOG(ERROR) << "Failed to write class offsets to " << out->GetLocation();
2389     return false;
2390   }
2391 
2392   relative_offset = WriteClasses(out, file_offset, relative_offset);
2393   if (relative_offset == 0) {
2394     PLOG(ERROR) << "Failed to write classes to " << out->GetLocation();
2395     return false;
2396   }
2397 
2398   relative_offset = WriteIndexBssMappings(out, file_offset, relative_offset);
2399   if (relative_offset == 0) {
2400     PLOG(ERROR) << "Failed to write method bss mappings to " << out->GetLocation();
2401     return false;
2402   }
2403 
2404   relative_offset = WriteMaps(out, file_offset, relative_offset);
2405   if (relative_offset == 0) {
2406     PLOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2407     return false;
2408   }
2409 
2410   relative_offset = WriteOatDexFiles(out, file_offset, relative_offset);
2411   if (relative_offset == 0) {
2412     PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
2413     return false;
2414   }
2415 
2416   // Write padding.
2417   off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
2418   relative_offset += size_executable_offset_alignment_;
2419   DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
2420   size_t expected_file_offset = file_offset + relative_offset;
2421   if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
2422     PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
2423                 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
2424     return false;
2425   }
2426   DCHECK_OFFSET();
2427 
2428   write_state_ = WriteState::kWriteText;
2429   return true;
2430 }
2431 
2432 class OatWriter::WriteQuickeningInfoMethodVisitor {
2433  public:
WriteQuickeningInfoMethodVisitor(OatWriter * writer,std::vector<uint8_t> * buffer)2434   WriteQuickeningInfoMethodVisitor(OatWriter* writer, /*out*/std::vector<uint8_t>* buffer)
2435       : writer_(writer),
2436         buffer_(buffer) {}
2437 
VisitDexMethods(const std::vector<const DexFile * > & dex_files)2438   void VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
2439     // Map of offsets for quicken info related to method indices.
2440     SafeMap<const uint8_t*, uint32_t> offset_map;
2441     // Use method index order to minimize the encoded size of the offset table.
2442     for (const DexFile* dex_file : dex_files) {
2443       std::vector<uint32_t>* const offsets =
2444           &quicken_info_offset_indices_.Put(dex_file, std::vector<uint32_t>())->second;
2445       for (uint32_t method_idx = 0; method_idx < dex_file->NumMethodIds(); ++method_idx) {
2446         uint32_t offset = 0u;
2447         MethodReference method_ref(dex_file, method_idx);
2448         CompiledMethod* compiled_method = writer_->compiler_driver_->GetCompiledMethod(method_ref);
2449         if (compiled_method != nullptr && HasQuickeningInfo(compiled_method)) {
2450           ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
2451 
2452           // Record each index if required. written_bytes_ is the offset from the start of the
2453           // quicken info data.
2454           // May be already inserted for duplicate items.
2455           // Add offset of one to make sure 0 represents unused.
2456           auto pair = offset_map.emplace(map.data(), written_bytes_ + 1);
2457           offset = pair.first->second;
2458           // Write out the map if it's not already written.
2459           if (pair.second) {
2460             static_assert(sizeof(map[0]) == 1u);
2461             buffer_->insert(buffer_->end(), map.begin(), map.end());
2462             written_bytes_ += map.size();
2463           }
2464         }
2465         offsets->push_back(offset);
2466       }
2467     }
2468   }
2469 
GetNumberOfWrittenBytes() const2470   size_t GetNumberOfWrittenBytes() const {
2471     return written_bytes_;
2472   }
2473 
GetQuickenInfoOffsetIndices()2474   SafeMap<const DexFile*, std::vector<uint32_t>>& GetQuickenInfoOffsetIndices() {
2475     return quicken_info_offset_indices_;
2476   }
2477 
2478  private:
2479   OatWriter* const writer_;
2480   std::vector<uint8_t>* const buffer_;
2481   size_t written_bytes_ = 0u;
2482   SafeMap<const DexFile*, std::vector<uint32_t>> quicken_info_offset_indices_;
2483 };
2484 
2485 class OatWriter::WriteQuickeningInfoOffsetsMethodVisitor {
2486  public:
WriteQuickeningInfoOffsetsMethodVisitor(std::vector<uint8_t> * buffer,uint32_t start_offset,SafeMap<const DexFile *,std::vector<uint32_t>> * quicken_info_offset_indices,std::vector<uint32_t> * out_table_offsets)2487   WriteQuickeningInfoOffsetsMethodVisitor(
2488       /*out*/std::vector<uint8_t>* buffer,
2489       uint32_t start_offset,
2490       SafeMap<const DexFile*, std::vector<uint32_t>>* quicken_info_offset_indices,
2491       std::vector<uint32_t>* out_table_offsets)
2492       : buffer_(buffer),
2493         start_offset_(start_offset),
2494         quicken_info_offset_indices_(quicken_info_offset_indices),
2495         out_table_offsets_(out_table_offsets) {}
2496 
VisitDexMethods(const std::vector<const DexFile * > & dex_files)2497   void VisitDexMethods(const std::vector<const DexFile*>& dex_files) {
2498     for (const DexFile* dex_file : dex_files) {
2499       auto it = quicken_info_offset_indices_->find(dex_file);
2500       DCHECK(it != quicken_info_offset_indices_->end()) << "Failed to find dex file "
2501                                                         << dex_file->GetLocation();
2502       const std::vector<uint32_t>* const offsets = &it->second;
2503 
2504       const uint32_t current_offset = start_offset_ + written_bytes_;
2505       CHECK_ALIGNED_PARAM(current_offset, CompactOffsetTable::kAlignment);
2506 
2507       // Generate and write the data.
2508       std::vector<uint8_t> table_data;
2509       CompactOffsetTable::Build(*offsets, &table_data);
2510 
2511       // Store the offset since we need to put those after the dex file. Table offsets are relative
2512       // to the start of the quicken info section.
2513       out_table_offsets_->push_back(current_offset);
2514 
2515       static_assert(sizeof(table_data[0]) == 1u);
2516       buffer_->insert(buffer_->end(), table_data.begin(), table_data.end());
2517       written_bytes_ += table_data.size();
2518     }
2519   }
2520 
GetNumberOfWrittenBytes() const2521   size_t GetNumberOfWrittenBytes() const {
2522     return written_bytes_;
2523   }
2524 
2525  private:
2526   std::vector<uint8_t>* const buffer_;
2527   const uint32_t start_offset_;
2528   size_t written_bytes_ = 0u;
2529   // Maps containing the offsets for the tables.
2530   SafeMap<const DexFile*, std::vector<uint32_t>>* const quicken_info_offset_indices_;
2531   std::vector<uint32_t>* const out_table_offsets_;
2532 };
2533 
WriteQuickeningInfo(std::vector<uint8_t> * buffer)2534 void OatWriter::WriteQuickeningInfo(/*out*/std::vector<uint8_t>* buffer) {
2535   if (!extract_dex_files_into_vdex_ || !GetCompilerOptions().IsQuickeningCompilationEnabled()) {
2536     // Nothing to write. Leave `vdex_size_` untouched and unaligned.
2537     vdex_quickening_info_offset_ = vdex_size_;
2538     size_quickening_info_alignment_ = 0;
2539     return;
2540   }
2541 
2542   TimingLogger::ScopedTiming split("VDEX quickening info", timings_);
2543 
2544   // Make sure the table is properly aligned.
2545   size_t start_offset = RoundUp(vdex_size_, 4u);
2546   const size_t padding_bytes = start_offset - vdex_size_;
2547   buffer->resize(buffer->size() + padding_bytes, 0u);
2548 
2549   WriteQuickeningInfoMethodVisitor write_quicken_info_visitor(this, buffer);
2550   write_quicken_info_visitor.VisitDexMethods(*dex_files_);
2551 
2552   uint32_t quicken_info_offset = write_quicken_info_visitor.GetNumberOfWrittenBytes();
2553   uint32_t extra_bytes_offset = start_offset + quicken_info_offset;
2554   size_t current_offset = RoundUp(extra_bytes_offset, CompactOffsetTable::kAlignment);
2555   const size_t extra_bytes = current_offset - extra_bytes_offset;
2556   buffer->resize(buffer->size() + extra_bytes, 0u);
2557   quicken_info_offset += extra_bytes;
2558 
2559   std::vector<uint32_t> table_offsets;
2560   WriteQuickeningInfoOffsetsMethodVisitor table_visitor(
2561       buffer,
2562       quicken_info_offset,
2563       &write_quicken_info_visitor.GetQuickenInfoOffsetIndices(),
2564       /*out*/ &table_offsets);
2565   table_visitor.VisitDexMethods(*dex_files_);
2566 
2567   CHECK_EQ(table_offsets.size(), dex_files_->size());
2568 
2569   current_offset += table_visitor.GetNumberOfWrittenBytes();
2570 
2571   // Store the offset table offset as a preheader for each dex.
2572   size_t index = 0;
2573   for (const OatDexFile& oat_dex_file : oat_dex_files_) {
2574     auto* quickening_table_offset = reinterpret_cast<VdexFile::QuickeningTableOffsetType*>(
2575         vdex_begin_ + oat_dex_file.dex_file_offset_ - sizeof(VdexFile::QuickeningTableOffsetType));
2576     *quickening_table_offset = table_offsets[index];
2577     ++index;
2578   }
2579   size_quickening_info_ = current_offset - start_offset;
2580 
2581   if (size_quickening_info_ == 0) {
2582     // Nothing was written. Leave `vdex_size_` untouched and unaligned.
2583     buffer->resize(buffer->size() - padding_bytes);  // Drop the padding data.
2584     vdex_quickening_info_offset_ = vdex_size_;
2585     size_quickening_info_alignment_ = 0;
2586   } else {
2587     size_quickening_info_alignment_ = padding_bytes;
2588     vdex_quickening_info_offset_ = start_offset;
2589     vdex_size_ = start_offset + size_quickening_info_;
2590   }
2591 }
2592 
WriteVerifierDeps(verifier::VerifierDeps * verifier_deps,std::vector<uint8_t> * buffer)2593 void OatWriter::WriteVerifierDeps(verifier::VerifierDeps* verifier_deps,
2594                                   /*out*/std::vector<uint8_t>* buffer) {
2595   if (verifier_deps == nullptr) {
2596     // Nothing to write. Record the offset, but no need
2597     // for alignment.
2598     vdex_verifier_deps_offset_ = vdex_size_;
2599     return;
2600   }
2601 
2602   TimingLogger::ScopedTiming split("VDEX verifier deps", timings_);
2603 
2604   size_t initial_offset = vdex_size_;
2605   size_t start_offset = RoundUp(initial_offset, 4u);
2606 
2607   vdex_size_ = start_offset;
2608   vdex_verifier_deps_offset_ = vdex_size_;
2609   size_verifier_deps_alignment_ = start_offset - initial_offset;
2610   buffer->resize(buffer->size() + size_verifier_deps_alignment_, 0u);
2611 
2612   size_t old_buffer_size = buffer->size();
2613   verifier_deps->Encode(*dex_files_, buffer);
2614 
2615   size_verifier_deps_ = buffer->size() - old_buffer_size;
2616   vdex_size_ += size_verifier_deps_;
2617 }
2618 
WriteCode(OutputStream * out)2619 bool OatWriter::WriteCode(OutputStream* out) {
2620   CHECK(write_state_ == WriteState::kWriteText);
2621 
2622   // Wrap out to update checksum with each write.
2623   ChecksumUpdatingOutputStream checksum_updating_out(out, this);
2624   out = &checksum_updating_out;
2625 
2626   SetMultiOatRelativePatcherAdjustment();
2627 
2628   const size_t file_offset = oat_data_offset_;
2629   size_t relative_offset = oat_header_->GetExecutableOffset();
2630   DCHECK_OFFSET();
2631 
2632   relative_offset = WriteCode(out, file_offset, relative_offset);
2633   if (relative_offset == 0) {
2634     LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
2635     return false;
2636   }
2637 
2638   relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
2639   if (relative_offset == 0) {
2640     LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
2641     return false;
2642   }
2643 
2644   if (data_bimg_rel_ro_size_ != 0u) {
2645     write_state_ = WriteState::kWriteDataBimgRelRo;
2646   } else {
2647     if (!CheckOatSize(out, file_offset, relative_offset)) {
2648       return false;
2649     }
2650     write_state_ = WriteState::kWriteHeader;
2651   }
2652   return true;
2653 }
2654 
WriteDataBimgRelRo(OutputStream * out)2655 bool OatWriter::WriteDataBimgRelRo(OutputStream* out) {
2656   CHECK(write_state_ == WriteState::kWriteDataBimgRelRo);
2657 
2658   // Wrap out to update checksum with each write.
2659   ChecksumUpdatingOutputStream checksum_updating_out(out, this);
2660   out = &checksum_updating_out;
2661 
2662   const size_t file_offset = oat_data_offset_;
2663   size_t relative_offset = data_bimg_rel_ro_start_;
2664 
2665   // Record the padding before the .data.bimg.rel.ro section.
2666   // Do not write anything, this zero-filled part was skipped (Seek()) when starting the section.
2667   size_t code_end = GetOatHeader().GetExecutableOffset() + code_size_;
2668   DCHECK_EQ(RoundUp(code_end, kPageSize), relative_offset);
2669   size_t padding_size = relative_offset - code_end;
2670   DCHECK_EQ(size_data_bimg_rel_ro_alignment_, 0u);
2671   size_data_bimg_rel_ro_alignment_ = padding_size;
2672 
2673   relative_offset = WriteDataBimgRelRo(out, file_offset, relative_offset);
2674   if (relative_offset == 0) {
2675     LOG(ERROR) << "Failed to write boot image relocations to " << out->GetLocation();
2676     return false;
2677   }
2678 
2679   if (!CheckOatSize(out, file_offset, relative_offset)) {
2680     return false;
2681   }
2682   write_state_ = WriteState::kWriteHeader;
2683   return true;
2684 }
2685 
CheckOatSize(OutputStream * out,size_t file_offset,size_t relative_offset)2686 bool OatWriter::CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset) {
2687   const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
2688   if (oat_end_file_offset == static_cast<off_t>(-1)) {
2689     LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
2690     return false;
2691   }
2692 
2693   if (kIsDebugBuild) {
2694     uint32_t size_total = 0;
2695     #define DO_STAT(x) \
2696       VLOG(compiler) << #x "=" << PrettySize(x) << " (" << (x) << "B)"; \
2697       size_total += (x);
2698 
2699     DO_STAT(size_vdex_header_);
2700     DO_STAT(size_vdex_checksums_);
2701     DO_STAT(size_dex_file_alignment_);
2702     DO_STAT(size_quickening_table_offset_);
2703     DO_STAT(size_executable_offset_alignment_);
2704     DO_STAT(size_oat_header_);
2705     DO_STAT(size_oat_header_key_value_store_);
2706     DO_STAT(size_dex_file_);
2707     DO_STAT(size_verifier_deps_);
2708     DO_STAT(size_verifier_deps_alignment_);
2709     DO_STAT(size_quickening_info_);
2710     DO_STAT(size_quickening_info_alignment_);
2711     DO_STAT(size_interpreter_to_interpreter_bridge_);
2712     DO_STAT(size_interpreter_to_compiled_code_bridge_);
2713     DO_STAT(size_jni_dlsym_lookup_trampoline_);
2714     DO_STAT(size_jni_dlsym_lookup_critical_trampoline_);
2715     DO_STAT(size_quick_generic_jni_trampoline_);
2716     DO_STAT(size_quick_imt_conflict_trampoline_);
2717     DO_STAT(size_quick_resolution_trampoline_);
2718     DO_STAT(size_quick_to_interpreter_bridge_);
2719     DO_STAT(size_trampoline_alignment_);
2720     DO_STAT(size_method_header_);
2721     DO_STAT(size_code_);
2722     DO_STAT(size_code_alignment_);
2723     DO_STAT(size_data_bimg_rel_ro_);
2724     DO_STAT(size_data_bimg_rel_ro_alignment_);
2725     DO_STAT(size_relative_call_thunks_);
2726     DO_STAT(size_misc_thunks_);
2727     DO_STAT(size_vmap_table_);
2728     DO_STAT(size_method_info_);
2729     DO_STAT(size_oat_dex_file_location_size_);
2730     DO_STAT(size_oat_dex_file_location_data_);
2731     DO_STAT(size_oat_dex_file_location_checksum_);
2732     DO_STAT(size_oat_dex_file_offset_);
2733     DO_STAT(size_oat_dex_file_class_offsets_offset_);
2734     DO_STAT(size_oat_dex_file_lookup_table_offset_);
2735     DO_STAT(size_oat_dex_file_dex_layout_sections_offset_);
2736     DO_STAT(size_oat_dex_file_dex_layout_sections_);
2737     DO_STAT(size_oat_dex_file_dex_layout_sections_alignment_);
2738     DO_STAT(size_oat_dex_file_method_bss_mapping_offset_);
2739     DO_STAT(size_oat_dex_file_type_bss_mapping_offset_);
2740     DO_STAT(size_oat_dex_file_string_bss_mapping_offset_);
2741     DO_STAT(size_oat_lookup_table_alignment_);
2742     DO_STAT(size_oat_lookup_table_);
2743     DO_STAT(size_oat_class_offsets_alignment_);
2744     DO_STAT(size_oat_class_offsets_);
2745     DO_STAT(size_oat_class_type_);
2746     DO_STAT(size_oat_class_status_);
2747     DO_STAT(size_oat_class_method_bitmaps_);
2748     DO_STAT(size_oat_class_method_offsets_);
2749     DO_STAT(size_method_bss_mappings_);
2750     DO_STAT(size_type_bss_mappings_);
2751     DO_STAT(size_string_bss_mappings_);
2752     #undef DO_STAT
2753 
2754     VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)";
2755 
2756     CHECK_EQ(vdex_size_ + oat_size_, size_total);
2757     CHECK_EQ(file_offset + size_total - vdex_size_, static_cast<size_t>(oat_end_file_offset));
2758   }
2759 
2760   CHECK_EQ(file_offset + oat_size_, static_cast<size_t>(oat_end_file_offset));
2761   CHECK_EQ(oat_size_, relative_offset);
2762 
2763   write_state_ = WriteState::kWriteHeader;
2764   return true;
2765 }
2766 
WriteHeader(OutputStream * out)2767 bool OatWriter::WriteHeader(OutputStream* out) {
2768   CHECK(write_state_ == WriteState::kWriteHeader);
2769 
2770   // Update checksum with header data.
2771   DCHECK_EQ(oat_header_->GetChecksum(), 0u);  // For checksum calculation.
2772   const uint8_t* header_begin = reinterpret_cast<const uint8_t*>(oat_header_.get());
2773   const uint8_t* header_end = oat_header_->GetKeyValueStore() + oat_header_->GetKeyValueStoreSize();
2774   uint32_t old_checksum = oat_checksum_;
2775   oat_checksum_ = adler32(old_checksum, header_begin, header_end - header_begin);
2776   oat_header_->SetChecksum(oat_checksum_);
2777 
2778   const size_t file_offset = oat_data_offset_;
2779 
2780   off_t current_offset = out->Seek(0, kSeekCurrent);
2781   if (current_offset == static_cast<off_t>(-1)) {
2782     PLOG(ERROR) << "Failed to get current offset from " << out->GetLocation();
2783     return false;
2784   }
2785   if (out->Seek(file_offset, kSeekSet) == static_cast<off_t>(-1)) {
2786     PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
2787     return false;
2788   }
2789   DCHECK_EQ(file_offset, static_cast<size_t>(out->Seek(0, kSeekCurrent)));
2790 
2791   // Flush all other data before writing the header.
2792   if (!out->Flush()) {
2793     PLOG(ERROR) << "Failed to flush before writing oat header to " << out->GetLocation();
2794     return false;
2795   }
2796   // Write the header.
2797   size_t header_size = oat_header_->GetHeaderSize();
2798   if (!out->WriteFully(oat_header_.get(), header_size)) {
2799     PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
2800     return false;
2801   }
2802   // Flush the header data.
2803   if (!out->Flush()) {
2804     PLOG(ERROR) << "Failed to flush after writing oat header to " << out->GetLocation();
2805     return false;
2806   }
2807 
2808   if (out->Seek(current_offset, kSeekSet) == static_cast<off_t>(-1)) {
2809     PLOG(ERROR) << "Failed to seek back after writing oat header to " << out->GetLocation();
2810     return false;
2811   }
2812   DCHECK_EQ(current_offset, out->Seek(0, kSeekCurrent));
2813 
2814   write_state_ = WriteState::kDone;
2815   return true;
2816 }
2817 
WriteClassOffsets(OutputStream * out,size_t file_offset,size_t relative_offset)2818 size_t OatWriter::WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset) {
2819   for (OatDexFile& oat_dex_file : oat_dex_files_) {
2820     if (oat_dex_file.class_offsets_offset_ != 0u) {
2821       // Class offsets are required to be 4 byte aligned.
2822       if (UNLIKELY(!IsAligned<4u>(relative_offset))) {
2823         size_t padding_size =  RoundUp(relative_offset, 4u) - relative_offset;
2824         if (!WriteUpTo16BytesAlignment(out, padding_size, &size_oat_class_offsets_alignment_)) {
2825           return 0u;
2826         }
2827         relative_offset += padding_size;
2828       }
2829       DCHECK_OFFSET();
2830       if (!oat_dex_file.WriteClassOffsets(this, out)) {
2831         return 0u;
2832       }
2833       relative_offset += oat_dex_file.GetClassOffsetsRawSize();
2834     }
2835   }
2836   return relative_offset;
2837 }
2838 
WriteClasses(OutputStream * out,size_t file_offset,size_t relative_offset)2839 size_t OatWriter::WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset) {
2840   const bool may_have_compiled = MayHaveCompiledMethods();
2841   if (may_have_compiled) {
2842     CHECK_EQ(oat_class_headers_.size(), oat_classes_.size());
2843   }
2844   for (size_t i = 0; i < oat_class_headers_.size(); ++i) {
2845     // If there are any classes, the class offsets allocation aligns the offset.
2846     DCHECK_ALIGNED(relative_offset, 4u);
2847     DCHECK_OFFSET();
2848     if (!oat_class_headers_[i].Write(this, out, oat_data_offset_)) {
2849       return 0u;
2850     }
2851     relative_offset += oat_class_headers_[i].SizeOf();
2852     if (may_have_compiled) {
2853       if (!oat_classes_[i].Write(this, out)) {
2854         return 0u;
2855       }
2856       relative_offset += oat_classes_[i].SizeOf();
2857     }
2858   }
2859   return relative_offset;
2860 }
2861 
WriteMaps(OutputStream * out,size_t file_offset,size_t relative_offset)2862 size_t OatWriter::WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset) {
2863   {
2864     if (UNLIKELY(!out->WriteFully(code_info_data_.data(), code_info_data_.size()))) {
2865       return 0;
2866     }
2867     relative_offset += code_info_data_.size();
2868     size_vmap_table_ = code_info_data_.size();
2869     DCHECK_OFFSET();
2870   }
2871 
2872   return relative_offset;
2873 }
2874 
2875 
2876 template <typename GetBssOffset>
WriteIndexBssMapping(OutputStream * out,size_t number_of_indexes,size_t slot_size,const BitVector & indexes,GetBssOffset get_bss_offset)2877 size_t WriteIndexBssMapping(OutputStream* out,
2878                             size_t number_of_indexes,
2879                             size_t slot_size,
2880                             const BitVector& indexes,
2881                             GetBssOffset get_bss_offset) {
2882   // Allocate the IndexBssMapping.
2883   size_t number_of_entries = CalculateNumberOfIndexBssMappingEntries(
2884       number_of_indexes, slot_size, indexes, get_bss_offset);
2885   size_t mappings_size = IndexBssMapping::ComputeSize(number_of_entries);
2886   DCHECK_ALIGNED(mappings_size, sizeof(uint32_t));
2887   std::unique_ptr<uint32_t[]> storage(new uint32_t[mappings_size / sizeof(uint32_t)]);
2888   IndexBssMapping* mappings = new(storage.get()) IndexBssMapping(number_of_entries);
2889   mappings->ClearPadding();
2890   // Encode the IndexBssMapping.
2891   IndexBssMappingEncoder encoder(number_of_indexes, slot_size);
2892   auto init_it = mappings->begin();
2893   bool first_index = true;
2894   for (uint32_t index : indexes.Indexes()) {
2895     size_t bss_offset = get_bss_offset(index);
2896     if (first_index) {
2897       first_index = false;
2898       encoder.Reset(index, bss_offset);
2899     } else if (!encoder.TryMerge(index, bss_offset)) {
2900       *init_it = encoder.GetEntry();
2901       ++init_it;
2902       encoder.Reset(index, bss_offset);
2903     }
2904   }
2905   // Store the last entry.
2906   *init_it = encoder.GetEntry();
2907   ++init_it;
2908   DCHECK(init_it == mappings->end());
2909 
2910   if (!out->WriteFully(storage.get(), mappings_size)) {
2911     return 0u;
2912   }
2913   return mappings_size;
2914 }
2915 
WriteIndexBssMappings(OutputStream * out,size_t file_offset,size_t relative_offset)2916 size_t OatWriter::WriteIndexBssMappings(OutputStream* out,
2917                                         size_t file_offset,
2918                                         size_t relative_offset) {
2919   TimingLogger::ScopedTiming split("WriteMethodBssMappings", timings_);
2920   if (bss_method_entry_references_.empty() &&
2921       bss_type_entry_references_.empty() &&
2922       bss_string_entry_references_.empty()) {
2923     return relative_offset;
2924   }
2925   // If there are any classes, the class offsets allocation aligns the offset
2926   // and we cannot have method bss mappings without class offsets.
2927   static_assert(alignof(IndexBssMapping) == sizeof(uint32_t),
2928                 "IndexBssMapping alignment check.");
2929   DCHECK_ALIGNED(relative_offset, sizeof(uint32_t));
2930 
2931   PointerSize pointer_size = GetInstructionSetPointerSize(oat_header_->GetInstructionSet());
2932   for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
2933     const DexFile* dex_file = (*dex_files_)[i];
2934     OatDexFile* oat_dex_file = &oat_dex_files_[i];
2935     auto method_it = bss_method_entry_references_.find(dex_file);
2936     if (method_it != bss_method_entry_references_.end()) {
2937       const BitVector& method_indexes = method_it->second;
2938       DCHECK_EQ(relative_offset, oat_dex_file->method_bss_mapping_offset_);
2939       DCHECK_OFFSET();
2940       size_t method_mappings_size = WriteIndexBssMapping(
2941           out,
2942           dex_file->NumMethodIds(),
2943           static_cast<size_t>(pointer_size),
2944           method_indexes,
2945           [=](uint32_t index) {
2946             return bss_method_entries_.Get({dex_file, index});
2947           });
2948       if (method_mappings_size == 0u) {
2949         return 0u;
2950       }
2951       size_method_bss_mappings_ += method_mappings_size;
2952       relative_offset += method_mappings_size;
2953     } else {
2954       DCHECK_EQ(0u, oat_dex_file->method_bss_mapping_offset_);
2955     }
2956 
2957     auto type_it = bss_type_entry_references_.find(dex_file);
2958     if (type_it != bss_type_entry_references_.end()) {
2959       const BitVector& type_indexes = type_it->second;
2960       DCHECK_EQ(relative_offset, oat_dex_file->type_bss_mapping_offset_);
2961       DCHECK_OFFSET();
2962       size_t type_mappings_size = WriteIndexBssMapping(
2963           out,
2964           dex_file->NumTypeIds(),
2965           sizeof(GcRoot<mirror::Class>),
2966           type_indexes,
2967           [=](uint32_t index) {
2968             return bss_type_entries_.Get({dex_file, dex::TypeIndex(index)});
2969           });
2970       if (type_mappings_size == 0u) {
2971         return 0u;
2972       }
2973       size_type_bss_mappings_ += type_mappings_size;
2974       relative_offset += type_mappings_size;
2975     } else {
2976       DCHECK_EQ(0u, oat_dex_file->type_bss_mapping_offset_);
2977     }
2978 
2979     auto string_it = bss_string_entry_references_.find(dex_file);
2980     if (string_it != bss_string_entry_references_.end()) {
2981       const BitVector& string_indexes = string_it->second;
2982       DCHECK_EQ(relative_offset, oat_dex_file->string_bss_mapping_offset_);
2983       DCHECK_OFFSET();
2984       size_t string_mappings_size = WriteIndexBssMapping(
2985           out,
2986           dex_file->NumStringIds(),
2987           sizeof(GcRoot<mirror::String>),
2988           string_indexes,
2989           [=](uint32_t index) {
2990             return bss_string_entries_.Get({dex_file, dex::StringIndex(index)});
2991           });
2992       if (string_mappings_size == 0u) {
2993         return 0u;
2994       }
2995       size_string_bss_mappings_ += string_mappings_size;
2996       relative_offset += string_mappings_size;
2997     } else {
2998       DCHECK_EQ(0u, oat_dex_file->string_bss_mapping_offset_);
2999     }
3000   }
3001   return relative_offset;
3002 }
3003 
WriteOatDexFiles(OutputStream * out,size_t file_offset,size_t relative_offset)3004 size_t OatWriter::WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset) {
3005   TimingLogger::ScopedTiming split("WriteOatDexFiles", timings_);
3006 
3007   for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3008     OatDexFile* oat_dex_file = &oat_dex_files_[i];
3009     DCHECK_EQ(relative_offset, oat_dex_file->offset_);
3010     DCHECK_OFFSET();
3011 
3012     // Write OatDexFile.
3013     if (!oat_dex_file->Write(this, out)) {
3014       return 0u;
3015     }
3016     relative_offset += oat_dex_file->SizeOf();
3017   }
3018 
3019   return relative_offset;
3020 }
3021 
WriteCode(OutputStream * out,size_t file_offset,size_t relative_offset)3022 size_t OatWriter::WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset) {
3023   if (GetCompilerOptions().IsBootImage() && primary_oat_file_) {
3024     InstructionSet instruction_set = compiler_options_.GetInstructionSet();
3025 
3026     #define DO_TRAMPOLINE(field) \
3027       do { \
3028         /* Pad with at least four 0xFFs so we can do DCHECKs in OatQuickMethodHeader */ \
3029         uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset + 4, instruction_set); \
3030         uint32_t alignment_padding = aligned_offset - relative_offset; \
3031         for (size_t i = 0; i < alignment_padding; i++) { \
3032           uint8_t padding = 0xFF; \
3033           out->WriteFully(&padding, 1); \
3034         } \
3035         size_trampoline_alignment_ += alignment_padding; \
3036         if (!out->WriteFully((field)->data(), (field)->size())) { \
3037           PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
3038           return false; \
3039         } \
3040         size_ ## field += (field)->size(); \
3041         relative_offset += alignment_padding + (field)->size(); \
3042         DCHECK_OFFSET(); \
3043       } while (false)
3044 
3045     DO_TRAMPOLINE(jni_dlsym_lookup_trampoline_);
3046     DO_TRAMPOLINE(jni_dlsym_lookup_critical_trampoline_);
3047     DO_TRAMPOLINE(quick_generic_jni_trampoline_);
3048     DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
3049     DO_TRAMPOLINE(quick_resolution_trampoline_);
3050     DO_TRAMPOLINE(quick_to_interpreter_bridge_);
3051     #undef DO_TRAMPOLINE
3052   }
3053   return relative_offset;
3054 }
3055 
WriteCodeDexFiles(OutputStream * out,size_t file_offset,size_t relative_offset)3056 size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
3057                                     size_t file_offset,
3058                                     size_t relative_offset) {
3059   if (!GetCompilerOptions().IsAnyCompilationEnabled()) {
3060     // As with InitOatCodeDexFiles, also skip the writer if
3061     // compilation was disabled.
3062     if (kOatWriterDebugOatCodeLayout) {
3063       LOG(INFO) << "WriteCodeDexFiles: OatWriter("
3064                 << this << "), "
3065                 << "compilation is disabled";
3066     }
3067 
3068     return relative_offset;
3069   }
3070   ScopedObjectAccess soa(Thread::Current());
3071   DCHECK(ordered_methods_ != nullptr);
3072   std::unique_ptr<OrderedMethodList> ordered_methods_ptr =
3073       std::move(ordered_methods_);
3074   WriteCodeMethodVisitor visitor(this,
3075                                  out,
3076                                  file_offset,
3077                                  relative_offset,
3078                                  std::move(*ordered_methods_ptr));
3079   if (UNLIKELY(!visitor.Visit())) {
3080     return 0;
3081   }
3082   relative_offset = visitor.GetOffset();
3083 
3084   size_code_alignment_ += relative_patcher_->CodeAlignmentSize();
3085   size_relative_call_thunks_ += relative_patcher_->RelativeCallThunksSize();
3086   size_misc_thunks_ += relative_patcher_->MiscThunksSize();
3087 
3088   return relative_offset;
3089 }
3090 
WriteDataBimgRelRo(OutputStream * out,size_t file_offset,size_t relative_offset)3091 size_t OatWriter::WriteDataBimgRelRo(OutputStream* out,
3092                                      size_t file_offset,
3093                                      size_t relative_offset) {
3094   if (data_bimg_rel_ro_entries_.empty()) {
3095     return relative_offset;
3096   }
3097 
3098   // Write the entire .data.bimg.rel.ro with a single WriteFully().
3099   std::vector<uint32_t> data;
3100   data.reserve(data_bimg_rel_ro_entries_.size());
3101   for (const auto& entry : data_bimg_rel_ro_entries_) {
3102     uint32_t boot_image_offset = entry.first;
3103     data.push_back(boot_image_offset);
3104   }
3105   DCHECK_EQ(data.size(), data_bimg_rel_ro_entries_.size());
3106   DCHECK_OFFSET();
3107   if (!out->WriteFully(data.data(), data.size() * sizeof(data[0]))) {
3108     PLOG(ERROR) << "Failed to write .data.bimg.rel.ro in " << out->GetLocation();
3109     return 0u;
3110   }
3111   DCHECK_EQ(size_data_bimg_rel_ro_, 0u);
3112   size_data_bimg_rel_ro_ = data.size() * sizeof(data[0]);
3113   relative_offset += size_data_bimg_rel_ro_;
3114   return relative_offset;
3115 }
3116 
RecordOatDataOffset(OutputStream * out)3117 bool OatWriter::RecordOatDataOffset(OutputStream* out) {
3118   // Get the elf file offset of the oat file.
3119   const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
3120   if (raw_file_offset == static_cast<off_t>(-1)) {
3121     LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
3122     return false;
3123   }
3124   oat_data_offset_ = static_cast<size_t>(raw_file_offset);
3125   return true;
3126 }
3127 
WriteDexFiles(File * file,bool update_input_vdex,CopyOption copy_dex_files,std::vector<MemMap> * opened_dex_files_map)3128 bool OatWriter::WriteDexFiles(File* file,
3129                               bool update_input_vdex,
3130                               CopyOption copy_dex_files,
3131                               /*out*/ std::vector<MemMap>* opened_dex_files_map) {
3132   TimingLogger::ScopedTiming split("Write Dex files", timings_);
3133 
3134   // If extraction is enabled, only do it if not all the dex files are aligned and uncompressed.
3135   if (copy_dex_files == CopyOption::kOnlyIfCompressed) {
3136     extract_dex_files_into_vdex_ = false;
3137     for (OatDexFile& oat_dex_file : oat_dex_files_) {
3138       if (!oat_dex_file.source_.IsZipEntry()) {
3139         extract_dex_files_into_vdex_ = true;
3140         break;
3141       }
3142       ZipEntry* entry = oat_dex_file.source_.GetZipEntry();
3143       if (!entry->IsUncompressed() || !entry->IsAlignedTo(alignof(DexFile::Header))) {
3144         extract_dex_files_into_vdex_ = true;
3145         break;
3146       }
3147     }
3148   } else if (copy_dex_files == CopyOption::kAlways) {
3149     extract_dex_files_into_vdex_ = true;
3150   } else {
3151     DCHECK(copy_dex_files == CopyOption::kNever);
3152     extract_dex_files_into_vdex_ = false;
3153   }
3154 
3155   if (extract_dex_files_into_vdex_) {
3156     // Add the dex section header.
3157     vdex_size_ += sizeof(VdexFile::DexSectionHeader);
3158     vdex_dex_files_offset_ = vdex_size_;
3159 
3160     // Perform dexlayout if requested.
3161     if (profile_compilation_info_ != nullptr ||
3162         compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone) {
3163       for (OatDexFile& oat_dex_file : oat_dex_files_) {
3164         // update_input_vdex disables compact dex and layout.
3165         CHECK(!update_input_vdex)
3166             << "We should never update the input vdex when doing dexlayout or compact dex";
3167         if (!LayoutDexFile(&oat_dex_file)) {
3168           return false;
3169         }
3170       }
3171     }
3172 
3173     // Calculate the total size after the dex files.
3174     size_t vdex_size_with_dex_files = vdex_size_;
3175     for (OatDexFile& oat_dex_file : oat_dex_files_) {
3176       // Dex files are required to be 4 byte aligned.
3177       vdex_size_with_dex_files = RoundUp(vdex_size_with_dex_files, 4u);
3178       // Leave extra room for the quicken table offset.
3179       vdex_size_with_dex_files += sizeof(VdexFile::QuickeningTableOffsetType);
3180       // Record offset for the dex file.
3181       oat_dex_file.dex_file_offset_ = vdex_size_with_dex_files;
3182       // Add the size of the dex file.
3183       if (oat_dex_file.dex_file_size_ < sizeof(DexFile::Header)) {
3184         LOG(ERROR) << "Dex file " << oat_dex_file.GetLocation() << " is too short: "
3185             << oat_dex_file.dex_file_size_ << " < " << sizeof(DexFile::Header);
3186         return false;
3187       }
3188       vdex_size_with_dex_files += oat_dex_file.dex_file_size_;
3189     }
3190     // Add the shared data section size.
3191     const uint8_t* raw_dex_file_shared_data_begin = nullptr;
3192     uint32_t shared_data_size = 0u;
3193     if (dex_container_ != nullptr) {
3194       shared_data_size = dex_container_->GetDataSection()->Size();
3195     } else {
3196       // Dex files from input vdex are represented as raw dex files and they can be
3197       // compact dex files. These need to specify the same shared data section if any.
3198       for (const OatDexFile& oat_dex_file : oat_dex_files_) {
3199         if (!oat_dex_file.source_.IsRawData()) {
3200           continue;
3201         }
3202         const uint8_t* raw_data = oat_dex_file.source_.GetRawData();
3203         const UnalignedDexFileHeader& header = *AsUnalignedDexFileHeader(raw_data);
3204         if (!CompactDexFile::IsMagicValid(header.magic_) || header.data_size_ == 0u) {
3205           // Non compact dex does not have shared data section.
3206           continue;
3207         }
3208         const uint8_t* cur_data_begin = raw_data + header.data_off_;
3209         if (raw_dex_file_shared_data_begin == nullptr) {
3210           raw_dex_file_shared_data_begin = cur_data_begin;
3211         } else if (raw_dex_file_shared_data_begin != cur_data_begin) {
3212           LOG(ERROR) << "Mismatched shared data sections in raw dex files: "
3213                      << static_cast<const void*>(raw_dex_file_shared_data_begin)
3214                      << " != " << static_cast<const void*>(cur_data_begin);
3215           return false;
3216         }
3217         // The different dex files currently can have different data sizes since
3218         // the dex writer writes them one at a time into the shared section.:w
3219         shared_data_size = std::max(shared_data_size, header.data_size_);
3220       }
3221     }
3222     if (shared_data_size != 0u) {
3223       // Shared data section is required to be 4 byte aligned.
3224       vdex_size_with_dex_files = RoundUp(vdex_size_with_dex_files, 4u);
3225     }
3226     vdex_dex_shared_data_offset_ = vdex_size_with_dex_files;
3227     vdex_size_with_dex_files += shared_data_size;
3228 
3229     // Extend the file and include the full page at the end as we need to write
3230     // additional data there and do not want to mmap that page twice.
3231     size_t page_aligned_size = RoundUp(vdex_size_with_dex_files, kPageSize);
3232     if (!update_input_vdex) {
3233       if (file->SetLength(page_aligned_size) != 0) {
3234         PLOG(ERROR) << "Failed to resize vdex file " << file->GetPath();
3235         return false;
3236       }
3237     }
3238 
3239     std::string error_msg;
3240     MemMap dex_files_map = MemMap::MapFile(
3241         page_aligned_size,
3242         PROT_READ | PROT_WRITE,
3243         MAP_SHARED,
3244         file->Fd(),
3245         /*start=*/ 0u,
3246         /*low_4gb=*/ false,
3247         file->GetPath().c_str(),
3248         &error_msg);
3249     if (!dex_files_map.IsValid()) {
3250       LOG(ERROR) << "Failed to mmap() dex files from oat file. File: " << file->GetPath()
3251                  << " error: " << error_msg;
3252       return false;
3253     }
3254     vdex_begin_ = dex_files_map.Begin();
3255 
3256     // Write dex files.
3257     for (OatDexFile& oat_dex_file : oat_dex_files_) {
3258       // Dex files are required to be 4 byte aligned.
3259       size_t quickening_table_offset_offset = RoundUp(vdex_size_, 4u);
3260       if (!update_input_vdex) {
3261         // Clear the padding.
3262         memset(vdex_begin_ + vdex_size_, 0, quickening_table_offset_offset - vdex_size_);
3263         // Initialize the quickening table offset to 0.
3264         auto* quickening_table_offset = reinterpret_cast<VdexFile::QuickeningTableOffsetType*>(
3265             vdex_begin_ + quickening_table_offset_offset);
3266         *quickening_table_offset = 0u;
3267       }
3268       size_dex_file_alignment_ += quickening_table_offset_offset - vdex_size_;
3269       size_quickening_table_offset_ += sizeof(VdexFile::QuickeningTableOffsetType);
3270       vdex_size_ = quickening_table_offset_offset + sizeof(VdexFile::QuickeningTableOffsetType);
3271       // Write the actual dex file.
3272       if (!WriteDexFile(file, &oat_dex_file, update_input_vdex)) {
3273         return false;
3274       }
3275     }
3276 
3277     // Write shared dex file data section and fix up the dex file headers.
3278     if (shared_data_size != 0u) {
3279       DCHECK_EQ(RoundUp(vdex_size_, 4u), vdex_dex_shared_data_offset_);
3280       if (!update_input_vdex) {
3281         memset(vdex_begin_ + vdex_size_, 0, vdex_dex_shared_data_offset_ - vdex_size_);
3282       }
3283       size_dex_file_alignment_ += vdex_dex_shared_data_offset_ - vdex_size_;
3284       vdex_size_ = vdex_dex_shared_data_offset_;
3285 
3286       if (dex_container_ != nullptr) {
3287         CHECK(!update_input_vdex) << "Update input vdex should have empty dex container";
3288         CHECK(compact_dex_level_ != CompactDexLevel::kCompactDexLevelNone);
3289         DexContainer::Section* const section = dex_container_->GetDataSection();
3290         DCHECK_EQ(shared_data_size, section->Size());
3291         memcpy(vdex_begin_ + vdex_size_, section->Begin(), shared_data_size);
3292         section->Clear();
3293         dex_container_.reset();
3294       } else if (!update_input_vdex) {
3295         // If we are not updating the input vdex, write out the shared data section.
3296         memcpy(vdex_begin_ + vdex_size_, raw_dex_file_shared_data_begin, shared_data_size);
3297       }
3298       vdex_size_ += shared_data_size;
3299       size_dex_file_ += shared_data_size;
3300       if (!update_input_vdex) {
3301         // Fix up the dex headers to have correct offsets to the data section.
3302         for (OatDexFile& oat_dex_file : oat_dex_files_) {
3303           DexFile::Header* header =
3304               reinterpret_cast<DexFile::Header*>(vdex_begin_ + oat_dex_file.dex_file_offset_);
3305           if (!CompactDexFile::IsMagicValid(header->magic_)) {
3306             // Non-compact dex file, probably failed to convert due to duplicate methods.
3307             continue;
3308           }
3309           CHECK_GT(vdex_dex_shared_data_offset_, oat_dex_file.dex_file_offset_);
3310           // Offset is from the dex file base.
3311           header->data_off_ = vdex_dex_shared_data_offset_ - oat_dex_file.dex_file_offset_;
3312           // The size should already be what part of the data buffer may be used by the dex.
3313           CHECK_LE(header->data_size_, shared_data_size);
3314         }
3315       }
3316     }
3317     opened_dex_files_map->push_back(std::move(dex_files_map));
3318   } else {
3319     vdex_dex_shared_data_offset_ = vdex_size_;
3320   }
3321 
3322   return true;
3323 }
3324 
CloseSources()3325 void OatWriter::CloseSources() {
3326   for (OatDexFile& oat_dex_file : oat_dex_files_) {
3327     oat_dex_file.source_.Clear();  // Get rid of the reference, it's about to be invalidated.
3328   }
3329   zipped_dex_files_.clear();
3330   zip_archives_.clear();
3331   raw_dex_files_.clear();
3332 }
3333 
WriteDexFile(File * file,OatDexFile * oat_dex_file,bool update_input_vdex)3334 bool OatWriter::WriteDexFile(File* file,
3335                              OatDexFile* oat_dex_file,
3336                              bool update_input_vdex) {
3337   DCHECK_EQ(vdex_size_, oat_dex_file->dex_file_offset_);
3338   if (oat_dex_file->source_.IsZipEntry()) {
3339     DCHECK(!update_input_vdex);
3340     if (!WriteDexFile(file, oat_dex_file, oat_dex_file->source_.GetZipEntry())) {
3341       return false;
3342     }
3343   } else if (oat_dex_file->source_.IsRawFile()) {
3344     DCHECK(!update_input_vdex);
3345     if (!WriteDexFile(file, oat_dex_file, oat_dex_file->source_.GetRawFile())) {
3346       return false;
3347     }
3348   } else {
3349     DCHECK(oat_dex_file->source_.IsRawData());
3350     const uint8_t* raw_data = oat_dex_file->source_.GetRawData();
3351     if (!WriteDexFile(oat_dex_file, raw_data, update_input_vdex)) {
3352       return false;
3353     }
3354   }
3355 
3356   // Update current size and account for the written data.
3357   vdex_size_ += oat_dex_file->dex_file_size_;
3358   size_dex_file_ += oat_dex_file->dex_file_size_;
3359   return true;
3360 }
3361 
LayoutDexFile(OatDexFile * oat_dex_file)3362 bool OatWriter::LayoutDexFile(OatDexFile* oat_dex_file) {
3363   TimingLogger::ScopedTiming split("Dex Layout", timings_);
3364   std::string error_msg;
3365   std::string location(oat_dex_file->GetLocation());
3366   std::unique_ptr<const DexFile> dex_file;
3367   const ArtDexFileLoader dex_file_loader;
3368   if (oat_dex_file->source_.IsZipEntry()) {
3369     ZipEntry* zip_entry = oat_dex_file->source_.GetZipEntry();
3370     MemMap mem_map;
3371     {
3372       TimingLogger::ScopedTiming extract("Unzip", timings_);
3373       mem_map = zip_entry->ExtractToMemMap(location.c_str(), "classes.dex", &error_msg);
3374     }
3375     if (!mem_map.IsValid()) {
3376       LOG(ERROR) << "Failed to extract dex file to mem map for layout: " << error_msg;
3377       return false;
3378     }
3379     TimingLogger::ScopedTiming extract("Open", timings_);
3380     dex_file = dex_file_loader.Open(location,
3381                                     zip_entry->GetCrc32(),
3382                                     std::move(mem_map),
3383                                     /*verify=*/ true,
3384                                     /*verify_checksum=*/ true,
3385                                     &error_msg);
3386   } else if (oat_dex_file->source_.IsRawFile()) {
3387     File* raw_file = oat_dex_file->source_.GetRawFile();
3388     int dup_fd = DupCloexec(raw_file->Fd());
3389     if (dup_fd < 0) {
3390       PLOG(ERROR) << "Failed to dup dex file descriptor (" << raw_file->Fd() << ") at " << location;
3391       return false;
3392     }
3393     TimingLogger::ScopedTiming extract("Open", timings_);
3394     dex_file = dex_file_loader.OpenDex(dup_fd, location,
3395                                        /*verify=*/ true,
3396                                        /*verify_checksum=*/ true,
3397                                        /*mmap_shared=*/ false,
3398                                        &error_msg);
3399   } else {
3400     // The source data is a vdex file.
3401     CHECK(oat_dex_file->source_.IsRawData())
3402         << static_cast<size_t>(oat_dex_file->source_.GetType());
3403     const uint8_t* raw_dex_file = oat_dex_file->source_.GetRawData();
3404     // Note: The raw data has already been checked to contain the header
3405     // and all the data that the header specifies as the file size.
3406     DCHECK(raw_dex_file != nullptr);
3407     DCHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file->GetLocation()));
3408     const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3409     // Since the source may have had its layout changed, or may be quickened, don't verify it.
3410     dex_file = dex_file_loader.Open(raw_dex_file,
3411                                     header->file_size_,
3412                                     location,
3413                                     oat_dex_file->dex_file_location_checksum_,
3414                                     nullptr,
3415                                     /*verify=*/ false,
3416                                     /*verify_checksum=*/ false,
3417                                     &error_msg);
3418   }
3419   if (dex_file == nullptr) {
3420     LOG(ERROR) << "Failed to open dex file for layout: " << error_msg;
3421     return false;
3422   }
3423   Options options;
3424   options.compact_dex_level_ = compact_dex_level_;
3425   options.update_checksum_ = true;
3426   DexLayout dex_layout(options, profile_compilation_info_, /*file*/ nullptr, /*header*/ nullptr);
3427   {
3428     TimingLogger::ScopedTiming extract("ProcessDexFile", timings_);
3429     if (dex_layout.ProcessDexFile(location.c_str(),
3430                                   dex_file.get(),
3431                                   0,
3432                                   &dex_container_,
3433                                   &error_msg)) {
3434       oat_dex_file->dex_sections_layout_ = dex_layout.GetSections();
3435       oat_dex_file->source_.SetDexLayoutData(dex_container_->GetMainSection()->ReleaseData());
3436       // Dex layout can affect the size of the dex file, so we update here what we have set
3437       // when adding the dex file as a source.
3438       const UnalignedDexFileHeader* header =
3439           AsUnalignedDexFileHeader(oat_dex_file->source_.GetRawData());
3440       oat_dex_file->dex_file_size_ = header->file_size_;
3441     } else {
3442       LOG(WARNING) << "Failed to run dex layout, reason:" << error_msg;
3443       // Since we failed to convert the dex, just copy the input dex.
3444       if (dex_container_ != nullptr) {
3445         // Clear the main section before processing next dex file in case we have written some data.
3446         dex_container_->GetMainSection()->Clear();
3447       }
3448     }
3449   }
3450   CHECK_EQ(oat_dex_file->dex_file_location_checksum_, dex_file->GetLocationChecksum());
3451   return true;
3452 }
3453 
WriteDexFile(File * file,OatDexFile * oat_dex_file,ZipEntry * dex_file)3454 bool OatWriter::WriteDexFile(File* file,
3455                              OatDexFile* oat_dex_file,
3456                              ZipEntry* dex_file) {
3457   uint8_t* raw_output = vdex_begin_ + oat_dex_file->dex_file_offset_;
3458 
3459   // Extract the dex file.
3460   std::string error_msg;
3461   if (!dex_file->ExtractToMemory(raw_output, &error_msg)) {
3462     LOG(ERROR) << "Failed to extract dex file from ZIP entry: " << error_msg
3463                << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3464     return false;
3465   }
3466 
3467   return true;
3468 }
3469 
WriteDexFile(File * file,OatDexFile * oat_dex_file,File * dex_file)3470 bool OatWriter::WriteDexFile(File* file,
3471                              OatDexFile* oat_dex_file,
3472                              File* dex_file) {
3473   uint8_t* raw_output = vdex_begin_ + oat_dex_file->dex_file_offset_;
3474 
3475   if (!dex_file->PreadFully(raw_output, oat_dex_file->dex_file_size_, /*offset=*/ 0u)) {
3476     PLOG(ERROR) << "Failed to copy dex file to vdex file."
3477                 << " File: " << oat_dex_file->GetLocation() << " Output: " << file->GetPath();
3478     return false;
3479   }
3480 
3481   return true;
3482 }
3483 
WriteDexFile(OatDexFile * oat_dex_file,const uint8_t * dex_file,bool update_input_vdex)3484 bool OatWriter::WriteDexFile(OatDexFile* oat_dex_file,
3485                              const uint8_t* dex_file,
3486                              bool update_input_vdex) {
3487   // Note: The raw data has already been checked to contain the header
3488   // and all the data that the header specifies as the file size.
3489   DCHECK(dex_file != nullptr);
3490   DCHECK(ValidateDexFileHeader(dex_file, oat_dex_file->GetLocation()));
3491   DCHECK_EQ(oat_dex_file->dex_file_size_, AsUnalignedDexFileHeader(dex_file)->file_size_);
3492 
3493   if (update_input_vdex) {
3494     // The vdex already contains the dex code, no need to write it again.
3495   } else {
3496     uint8_t* raw_output = vdex_begin_ + oat_dex_file->dex_file_offset_;
3497     memcpy(raw_output, dex_file, oat_dex_file->dex_file_size_);
3498   }
3499   return true;
3500 }
3501 
OpenDexFiles(File * file,bool verify,std::vector<MemMap> * opened_dex_files_map,std::vector<std::unique_ptr<const DexFile>> * opened_dex_files)3502 bool OatWriter::OpenDexFiles(
3503     File* file,
3504     bool verify,
3505     /*inout*/ std::vector<MemMap>* opened_dex_files_map,
3506     /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
3507   TimingLogger::ScopedTiming split("OpenDexFiles", timings_);
3508 
3509   if (oat_dex_files_.empty()) {
3510     // Nothing to do.
3511     return true;
3512   }
3513 
3514   if (!extract_dex_files_into_vdex_) {
3515     DCHECK_EQ(opened_dex_files_map->size(), 0u);
3516     std::vector<std::unique_ptr<const DexFile>> dex_files;
3517     std::vector<MemMap> maps;
3518     for (OatDexFile& oat_dex_file : oat_dex_files_) {
3519       std::string error_msg;
3520       maps.emplace_back(oat_dex_file.source_.GetZipEntry()->MapDirectlyOrExtract(
3521           oat_dex_file.dex_file_location_data_, "zipped dex", &error_msg, alignof(DexFile)));
3522       MemMap* map = &maps.back();
3523       if (!map->IsValid()) {
3524         LOG(ERROR) << error_msg;
3525         return false;
3526       }
3527       // Now, open the dex file.
3528       const ArtDexFileLoader dex_file_loader;
3529       dex_files.emplace_back(dex_file_loader.Open(map->Begin(),
3530                                                   map->Size(),
3531                                                   oat_dex_file.GetLocation(),
3532                                                   oat_dex_file.dex_file_location_checksum_,
3533                                                   /* oat_dex_file */ nullptr,
3534                                                   verify,
3535                                                   verify,
3536                                                   &error_msg));
3537       if (dex_files.back() == nullptr) {
3538         LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3539                    << " Error: " << error_msg;
3540         return false;
3541       }
3542       oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3543     }
3544     *opened_dex_files_map = std::move(maps);
3545     *opened_dex_files = std::move(dex_files);
3546     CloseSources();
3547     return true;
3548   }
3549   // We could have closed the sources at the point of writing the dex files, but to
3550   // make it consistent with the case we're not writing the dex files, we close them now.
3551   CloseSources();
3552 
3553   DCHECK_EQ(opened_dex_files_map->size(), 1u);
3554   DCHECK(vdex_begin_ == opened_dex_files_map->front().Begin());
3555   const ArtDexFileLoader dex_file_loader;
3556   std::vector<std::unique_ptr<const DexFile>> dex_files;
3557   for (OatDexFile& oat_dex_file : oat_dex_files_) {
3558     const uint8_t* raw_dex_file = vdex_begin_ + oat_dex_file.dex_file_offset_;
3559 
3560     if (kIsDebugBuild) {
3561       // Check the validity of the input files.
3562       // Note that ValidateDexFileHeader() logs error messages.
3563       CHECK(ValidateDexFileHeader(raw_dex_file, oat_dex_file.GetLocation()))
3564           << "Failed to verify written dex file header!"
3565           << " Output: " << file->GetPath()
3566           << " ~ " << std::hex << static_cast<const void*>(raw_dex_file);
3567 
3568       const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(raw_dex_file);
3569       CHECK_EQ(header->file_size_, oat_dex_file.dex_file_size_)
3570           << "File size mismatch in written dex file header! Expected: "
3571           << oat_dex_file.dex_file_size_ << " Actual: " << header->file_size_
3572           << " Output: " << file->GetPath();
3573     }
3574 
3575     // Now, open the dex file.
3576     std::string error_msg;
3577     dex_files.emplace_back(dex_file_loader.Open(raw_dex_file,
3578                                                 oat_dex_file.dex_file_size_,
3579                                                 oat_dex_file.GetLocation(),
3580                                                 oat_dex_file.dex_file_location_checksum_,
3581                                                 /* oat_dex_file */ nullptr,
3582                                                 verify,
3583                                                 verify,
3584                                                 &error_msg));
3585     if (dex_files.back() == nullptr) {
3586       LOG(ERROR) << "Failed to open dex file from oat file. File: " << oat_dex_file.GetLocation()
3587                  << " Error: " << error_msg;
3588       return false;
3589     }
3590 
3591     // Set the class_offsets size now that we have easy access to the DexFile and
3592     // it has been verified in dex_file_loader.Open.
3593     oat_dex_file.class_offsets_.resize(dex_files.back()->GetHeader().class_defs_size_);
3594   }
3595 
3596   *opened_dex_files = std::move(dex_files);
3597   return true;
3598 }
3599 
WriteTypeLookupTables(OutputStream * oat_rodata,const std::vector<const DexFile * > & opened_dex_files)3600 bool OatWriter::WriteTypeLookupTables(OutputStream* oat_rodata,
3601                                       const std::vector<const DexFile*>& opened_dex_files) {
3602   TimingLogger::ScopedTiming split("WriteTypeLookupTables", timings_);
3603 
3604   uint32_t expected_offset = oat_data_offset_ + oat_size_;
3605   off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3606   if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3607     PLOG(ERROR) << "Failed to seek to TypeLookupTable section. Actual: " << actual_offset
3608                 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3609     return false;
3610   }
3611 
3612   DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3613   for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3614     OatDexFile* oat_dex_file = &oat_dex_files_[i];
3615     DCHECK_EQ(oat_dex_file->lookup_table_offset_, 0u);
3616 
3617     if (oat_dex_file->create_type_lookup_table_ != CreateTypeLookupTable::kCreate ||
3618         oat_dex_file->class_offsets_.empty()) {
3619       continue;
3620     }
3621 
3622     size_t table_size = TypeLookupTable::RawDataLength(oat_dex_file->class_offsets_.size());
3623     if (table_size == 0u) {
3624       continue;
3625     }
3626 
3627     // Create the lookup table. When `nullptr` is given as the storage buffer,
3628     // TypeLookupTable allocates its own and OatDexFile takes ownership.
3629     // TODO: Create the table in an mmap()ed region of the output file to reduce dirty memory.
3630     // (We used to do that when dex files were still copied into the oat file.)
3631     const DexFile& dex_file = *opened_dex_files[i];
3632     {
3633       TypeLookupTable type_lookup_table = TypeLookupTable::Create(dex_file);
3634       type_lookup_table_oat_dex_files_.push_back(
3635           std::make_unique<art::OatDexFile>(std::move(type_lookup_table)));
3636       dex_file.SetOatDexFile(type_lookup_table_oat_dex_files_.back().get());
3637     }
3638     const TypeLookupTable& table = type_lookup_table_oat_dex_files_.back()->GetTypeLookupTable();
3639     DCHECK(table.Valid());
3640 
3641     // Type tables are required to be 4 byte aligned.
3642     size_t initial_offset = oat_size_;
3643     size_t rodata_offset = RoundUp(initial_offset, 4);
3644     size_t padding_size = rodata_offset - initial_offset;
3645 
3646     if (padding_size != 0u) {
3647       std::vector<uint8_t> buffer(padding_size, 0u);
3648       if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3649         PLOG(ERROR) << "Failed to write lookup table alignment padding."
3650                     << " File: " << oat_dex_file->GetLocation()
3651                     << " Output: " << oat_rodata->GetLocation();
3652         return false;
3653       }
3654     }
3655 
3656     DCHECK_EQ(oat_data_offset_ + rodata_offset,
3657               static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3658     DCHECK_EQ(table_size, table.RawDataLength());
3659 
3660     if (!oat_rodata->WriteFully(table.RawData(), table_size)) {
3661       PLOG(ERROR) << "Failed to write lookup table."
3662                   << " File: " << oat_dex_file->GetLocation()
3663                   << " Output: " << oat_rodata->GetLocation();
3664       return false;
3665     }
3666 
3667     oat_dex_file->lookup_table_offset_ = rodata_offset;
3668 
3669     oat_size_ += padding_size + table_size;
3670     size_oat_lookup_table_ += table_size;
3671     size_oat_lookup_table_alignment_ += padding_size;
3672   }
3673 
3674   if (!oat_rodata->Flush()) {
3675     PLOG(ERROR) << "Failed to flush stream after writing type lookup tables."
3676                 << " File: " << oat_rodata->GetLocation();
3677     return false;
3678   }
3679 
3680   return true;
3681 }
3682 
WriteDexLayoutSections(OutputStream * oat_rodata,const std::vector<const DexFile * > & opened_dex_files)3683 bool OatWriter::WriteDexLayoutSections(OutputStream* oat_rodata,
3684                                        const std::vector<const DexFile*>& opened_dex_files) {
3685   TimingLogger::ScopedTiming split(__FUNCTION__, timings_);
3686 
3687   if (!kWriteDexLayoutInfo) {
3688     return true;
3689   }
3690 
3691   uint32_t expected_offset = oat_data_offset_ + oat_size_;
3692   off_t actual_offset = oat_rodata->Seek(expected_offset, kSeekSet);
3693   if (static_cast<uint32_t>(actual_offset) != expected_offset) {
3694     PLOG(ERROR) << "Failed to seek to dex layout section offset section. Actual: " << actual_offset
3695                 << " Expected: " << expected_offset << " File: " << oat_rodata->GetLocation();
3696     return false;
3697   }
3698 
3699   DCHECK_EQ(opened_dex_files.size(), oat_dex_files_.size());
3700   size_t rodata_offset = oat_size_;
3701   for (size_t i = 0, size = opened_dex_files.size(); i != size; ++i) {
3702     OatDexFile* oat_dex_file = &oat_dex_files_[i];
3703     DCHECK_EQ(oat_dex_file->dex_sections_layout_offset_, 0u);
3704 
3705     // Write dex layout section alignment bytes.
3706     const size_t padding_size =
3707         RoundUp(rodata_offset, alignof(DexLayoutSections)) - rodata_offset;
3708     if (padding_size != 0u) {
3709       std::vector<uint8_t> buffer(padding_size, 0u);
3710       if (!oat_rodata->WriteFully(buffer.data(), padding_size)) {
3711         PLOG(ERROR) << "Failed to write lookup table alignment padding."
3712                     << " File: " << oat_dex_file->GetLocation()
3713                     << " Output: " << oat_rodata->GetLocation();
3714         return false;
3715       }
3716       size_oat_dex_file_dex_layout_sections_alignment_ += padding_size;
3717       rodata_offset += padding_size;
3718     }
3719 
3720     DCHECK_ALIGNED(rodata_offset, alignof(DexLayoutSections));
3721     DCHECK_EQ(oat_data_offset_ + rodata_offset,
3722               static_cast<size_t>(oat_rodata->Seek(0u, kSeekCurrent)));
3723     DCHECK(oat_dex_file != nullptr);
3724     if (!oat_rodata->WriteFully(&oat_dex_file->dex_sections_layout_,
3725                                 sizeof(oat_dex_file->dex_sections_layout_))) {
3726       PLOG(ERROR) << "Failed to write dex layout sections."
3727                   << " File: " << oat_dex_file->GetLocation()
3728                   << " Output: " << oat_rodata->GetLocation();
3729       return false;
3730     }
3731     oat_dex_file->dex_sections_layout_offset_ = rodata_offset;
3732     size_oat_dex_file_dex_layout_sections_ += sizeof(oat_dex_file->dex_sections_layout_);
3733     rodata_offset += sizeof(oat_dex_file->dex_sections_layout_);
3734   }
3735   oat_size_ = rodata_offset;
3736 
3737   if (!oat_rodata->Flush()) {
3738     PLOG(ERROR) << "Failed to flush stream after writing type dex layout sections."
3739                 << " File: " << oat_rodata->GetLocation();
3740     return false;
3741   }
3742 
3743   return true;
3744 }
3745 
FinishVdexFile(File * vdex_file,verifier::VerifierDeps * verifier_deps)3746 bool OatWriter::FinishVdexFile(File* vdex_file, verifier::VerifierDeps* verifier_deps) {
3747   size_t old_vdex_size = vdex_size_;
3748   std::vector<uint8_t> buffer;
3749   buffer.reserve(64 * KB);
3750   WriteVerifierDeps(verifier_deps, &buffer);
3751   DCHECK_EQ(vdex_size_, old_vdex_size + buffer.size());
3752   WriteQuickeningInfo(&buffer);
3753   DCHECK_EQ(vdex_size_, old_vdex_size + buffer.size());
3754 
3755   // Resize the vdex file.
3756   if (vdex_file->SetLength(vdex_size_) != 0) {
3757     PLOG(ERROR) << "Failed to resize vdex file " << vdex_file->GetPath();
3758     return false;
3759   }
3760 
3761   uint8_t* vdex_begin = vdex_begin_;
3762   MemMap extra_map;
3763   if (extract_dex_files_into_vdex_) {
3764     DCHECK(vdex_begin != nullptr);
3765     // Write data to the last already mmapped page of the vdex file.
3766     size_t mmapped_vdex_size = RoundUp(old_vdex_size, kPageSize);
3767     size_t first_chunk_size = std::min(buffer.size(), mmapped_vdex_size - old_vdex_size);
3768     memcpy(vdex_begin + old_vdex_size, buffer.data(), first_chunk_size);
3769 
3770     if (first_chunk_size != buffer.size()) {
3771       size_t tail_size = buffer.size() - first_chunk_size;
3772       std::string error_msg;
3773       extra_map = MemMap::MapFile(
3774           tail_size,
3775           PROT_READ | PROT_WRITE,
3776           MAP_SHARED,
3777           vdex_file->Fd(),
3778           /*start=*/ mmapped_vdex_size,
3779           /*low_4gb=*/ false,
3780           vdex_file->GetPath().c_str(),
3781           &error_msg);
3782       if (!extra_map.IsValid()) {
3783         LOG(ERROR) << "Failed to mmap() vdex file tail. File: " << vdex_file->GetPath()
3784                    << " error: " << error_msg;
3785         return false;
3786       }
3787       memcpy(extra_map.Begin(), buffer.data() + first_chunk_size, tail_size);
3788     }
3789   } else {
3790     DCHECK(vdex_begin == nullptr);
3791     std::string error_msg;
3792     extra_map = MemMap::MapFile(
3793         vdex_size_,
3794         PROT_READ | PROT_WRITE,
3795         MAP_SHARED,
3796         vdex_file->Fd(),
3797         /*start=*/ 0u,
3798         /*low_4gb=*/ false,
3799         vdex_file->GetPath().c_str(),
3800         &error_msg);
3801     if (!extra_map.IsValid()) {
3802       LOG(ERROR) << "Failed to mmap() vdex file. File: " << vdex_file->GetPath()
3803                  << " error: " << error_msg;
3804       return false;
3805     }
3806     vdex_begin = extra_map.Begin();
3807     memcpy(vdex_begin + old_vdex_size, buffer.data(), buffer.size());
3808   }
3809 
3810   // Write checksums
3811   off_t checksums_offset = sizeof(VdexFile::VerifierDepsHeader);
3812   VdexFile::VdexChecksum* checksums_data =
3813       reinterpret_cast<VdexFile::VdexChecksum*>(vdex_begin + checksums_offset);
3814   for (size_t i = 0, size = oat_dex_files_.size(); i != size; ++i) {
3815     OatDexFile* oat_dex_file = &oat_dex_files_[i];
3816     checksums_data[i] = oat_dex_file->dex_file_location_checksum_;
3817     size_vdex_checksums_ += sizeof(VdexFile::VdexChecksum);
3818   }
3819 
3820   // Maybe write dex section header.
3821   DCHECK_NE(vdex_verifier_deps_offset_, 0u);
3822   DCHECK_NE(vdex_quickening_info_offset_, 0u);
3823 
3824   bool has_dex_section = extract_dex_files_into_vdex_;
3825   if (has_dex_section) {
3826     DCHECK_NE(vdex_dex_files_offset_, 0u);
3827     size_t dex_section_size = vdex_dex_shared_data_offset_ - vdex_dex_files_offset_;
3828     size_t dex_shared_data_size = vdex_verifier_deps_offset_ - vdex_dex_shared_data_offset_;
3829     size_t quickening_info_section_size = vdex_size_ - vdex_quickening_info_offset_;
3830 
3831     void* dex_section_header_storage = checksums_data + oat_dex_files_.size();
3832     new (dex_section_header_storage) VdexFile::DexSectionHeader(dex_section_size,
3833                                                                 dex_shared_data_size,
3834                                                                 quickening_info_section_size);
3835     size_vdex_header_ += sizeof(VdexFile::DexSectionHeader);
3836   }
3837 
3838   {
3839     TimingLogger::ScopedTiming split("VDEX flush contents", timings_);
3840     // Sync the data to the disk while the header is invalid. We do not want to end up with
3841     // a valid header and invalid data if the process is suddenly killed.
3842     if (extract_dex_files_into_vdex_) {
3843       // Note: We passed the ownership of the vdex dex file MemMap to the caller,
3844       // so we need to use msync() for the range explicitly.
3845       if (msync(vdex_begin, RoundUp(old_vdex_size, kPageSize), MS_SYNC) != 0) {
3846         PLOG(ERROR) << "Failed to sync vdex file contents" << vdex_file->GetPath();
3847         return false;
3848       }
3849     }
3850     if (extra_map.IsValid() && !extra_map.Sync()) {
3851       PLOG(ERROR) << "Failed to sync vdex file contents" << vdex_file->GetPath();
3852       return false;
3853     }
3854   }
3855 
3856   // Write header.
3857   // TODO: Use `size_quickening_info_` instead of `verifier_deps_section_size` which
3858   // includes `size_quickening_info_alignment_`, adjust code in VdexFile.
3859   size_t verifier_deps_section_size = vdex_quickening_info_offset_ - vdex_verifier_deps_offset_;
3860 
3861   new (vdex_begin) VdexFile::VerifierDepsHeader(
3862       oat_dex_files_.size(), verifier_deps_section_size, has_dex_section);
3863   size_vdex_header_ += sizeof(VdexFile::VerifierDepsHeader);
3864 
3865   // Note: If `extract_dex_files_into_vdex_`, we passed the ownership of the vdex dex file
3866   // MemMap to the caller, so we need to use msync() for the range explicitly.
3867   if (msync(vdex_begin, kPageSize, MS_SYNC) != 0) {
3868     PLOG(ERROR) << "Failed to sync vdex file header " << vdex_file->GetPath();
3869     return false;
3870   }
3871 
3872   return true;
3873 }
3874 
WriteCodeAlignment(OutputStream * out,uint32_t aligned_code_delta)3875 bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
3876   return WriteUpTo16BytesAlignment(out, aligned_code_delta, &size_code_alignment_);
3877 }
3878 
WriteUpTo16BytesAlignment(OutputStream * out,uint32_t size,uint32_t * stat)3879 bool OatWriter::WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat) {
3880   static const uint8_t kPadding[] = {
3881       0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
3882   };
3883   DCHECK_LE(size, sizeof(kPadding));
3884   if (UNLIKELY(!out->WriteFully(kPadding, size))) {
3885     return false;
3886   }
3887   *stat += size;
3888   return true;
3889 }
3890 
SetMultiOatRelativePatcherAdjustment()3891 void OatWriter::SetMultiOatRelativePatcherAdjustment() {
3892   DCHECK(dex_files_ != nullptr);
3893   DCHECK(relative_patcher_ != nullptr);
3894   DCHECK_NE(oat_data_offset_, 0u);
3895   if (image_writer_ != nullptr && !dex_files_->empty()) {
3896     // The oat data begin may not be initialized yet but the oat file offset is ready.
3897     size_t oat_index = image_writer_->GetOatIndexForDexFile(dex_files_->front());
3898     size_t elf_file_offset = image_writer_->GetOatFileOffset(oat_index);
3899     relative_patcher_->StartOatFile(elf_file_offset + oat_data_offset_);
3900   }
3901 }
3902 
OatDexFile(const char * dex_file_location,DexFileSource source,CreateTypeLookupTable create_type_lookup_table,uint32_t dex_file_location_checksum,size_t dex_file_size)3903 OatWriter::OatDexFile::OatDexFile(const char* dex_file_location,
3904                                   DexFileSource source,
3905                                   CreateTypeLookupTable create_type_lookup_table,
3906                                   uint32_t dex_file_location_checksum,
3907                                   size_t dex_file_size)
3908     : source_(std::move(source)),
3909       create_type_lookup_table_(create_type_lookup_table),
3910       dex_file_size_(dex_file_size),
3911       offset_(0),
3912       dex_file_location_size_(strlen(dex_file_location)),
3913       dex_file_location_data_(dex_file_location),
3914       dex_file_location_checksum_(dex_file_location_checksum),
3915       dex_file_offset_(0u),
3916       lookup_table_offset_(0u),
3917       class_offsets_offset_(0u),
3918       method_bss_mapping_offset_(0u),
3919       type_bss_mapping_offset_(0u),
3920       string_bss_mapping_offset_(0u),
3921       dex_sections_layout_offset_(0u),
3922       class_offsets_() {
3923 }
3924 
SizeOf() const3925 size_t OatWriter::OatDexFile::SizeOf() const {
3926   return sizeof(dex_file_location_size_)
3927           + dex_file_location_size_
3928           + sizeof(dex_file_location_checksum_)
3929           + sizeof(dex_file_offset_)
3930           + sizeof(class_offsets_offset_)
3931           + sizeof(lookup_table_offset_)
3932           + sizeof(method_bss_mapping_offset_)
3933           + sizeof(type_bss_mapping_offset_)
3934           + sizeof(string_bss_mapping_offset_)
3935           + sizeof(dex_sections_layout_offset_);
3936 }
3937 
Write(OatWriter * oat_writer,OutputStream * out) const3938 bool OatWriter::OatDexFile::Write(OatWriter* oat_writer, OutputStream* out) const {
3939   const size_t file_offset = oat_writer->oat_data_offset_;
3940   DCHECK_OFFSET_();
3941 
3942   if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
3943     PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
3944     return false;
3945   }
3946   oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
3947 
3948   if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
3949     PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
3950     return false;
3951   }
3952   oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
3953 
3954   if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
3955     PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
3956     return false;
3957   }
3958   oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
3959 
3960   if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
3961     PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
3962     return false;
3963   }
3964   oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
3965 
3966   if (!out->WriteFully(&class_offsets_offset_, sizeof(class_offsets_offset_))) {
3967     PLOG(ERROR) << "Failed to write class offsets offset to " << out->GetLocation();
3968     return false;
3969   }
3970   oat_writer->size_oat_dex_file_class_offsets_offset_ += sizeof(class_offsets_offset_);
3971 
3972   if (!out->WriteFully(&lookup_table_offset_, sizeof(lookup_table_offset_))) {
3973     PLOG(ERROR) << "Failed to write lookup table offset to " << out->GetLocation();
3974     return false;
3975   }
3976   oat_writer->size_oat_dex_file_lookup_table_offset_ += sizeof(lookup_table_offset_);
3977 
3978   if (!out->WriteFully(&dex_sections_layout_offset_, sizeof(dex_sections_layout_offset_))) {
3979     PLOG(ERROR) << "Failed to write dex section layout info to " << out->GetLocation();
3980     return false;
3981   }
3982   oat_writer->size_oat_dex_file_dex_layout_sections_offset_ += sizeof(dex_sections_layout_offset_);
3983 
3984   if (!out->WriteFully(&method_bss_mapping_offset_, sizeof(method_bss_mapping_offset_))) {
3985     PLOG(ERROR) << "Failed to write method bss mapping offset to " << out->GetLocation();
3986     return false;
3987   }
3988   oat_writer->size_oat_dex_file_method_bss_mapping_offset_ += sizeof(method_bss_mapping_offset_);
3989 
3990   if (!out->WriteFully(&type_bss_mapping_offset_, sizeof(type_bss_mapping_offset_))) {
3991     PLOG(ERROR) << "Failed to write type bss mapping offset to " << out->GetLocation();
3992     return false;
3993   }
3994   oat_writer->size_oat_dex_file_type_bss_mapping_offset_ += sizeof(type_bss_mapping_offset_);
3995 
3996   if (!out->WriteFully(&string_bss_mapping_offset_, sizeof(string_bss_mapping_offset_))) {
3997     PLOG(ERROR) << "Failed to write string bss mapping offset to " << out->GetLocation();
3998     return false;
3999   }
4000   oat_writer->size_oat_dex_file_string_bss_mapping_offset_ += sizeof(string_bss_mapping_offset_);
4001 
4002   return true;
4003 }
4004 
WriteClassOffsets(OatWriter * oat_writer,OutputStream * out)4005 bool OatWriter::OatDexFile::WriteClassOffsets(OatWriter* oat_writer, OutputStream* out) {
4006   if (!out->WriteFully(class_offsets_.data(), GetClassOffsetsRawSize())) {
4007     PLOG(ERROR) << "Failed to write oat class offsets for " << GetLocation()
4008                 << " to " << out->GetLocation();
4009     return false;
4010   }
4011   oat_writer->size_oat_class_offsets_ += GetClassOffsetsRawSize();
4012   return true;
4013 }
4014 
OatClass(const dchecked_vector<CompiledMethod * > & compiled_methods,uint32_t compiled_methods_with_code,uint16_t oat_class_type)4015 OatWriter::OatClass::OatClass(const dchecked_vector<CompiledMethod*>& compiled_methods,
4016                               uint32_t compiled_methods_with_code,
4017                               uint16_t oat_class_type)
4018     : compiled_methods_(compiled_methods) {
4019   const uint32_t num_methods = compiled_methods.size();
4020   CHECK_LE(compiled_methods_with_code, num_methods);
4021 
4022   oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
4023 
4024   method_offsets_.resize(compiled_methods_with_code);
4025   method_headers_.resize(compiled_methods_with_code);
4026 
4027   uint32_t oat_method_offsets_offset_from_oat_class = OatClassHeader::SizeOf();
4028   // We only create this instance if there are at least some compiled.
4029   if (oat_class_type == kOatClassSomeCompiled) {
4030     method_bitmap_.reset(new BitVector(num_methods, false, Allocator::GetMallocAllocator()));
4031     method_bitmap_size_ = method_bitmap_->GetSizeOf();
4032     oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
4033     oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
4034   } else {
4035     method_bitmap_ = nullptr;
4036     method_bitmap_size_ = 0;
4037   }
4038 
4039   for (size_t i = 0; i < num_methods; i++) {
4040     CompiledMethod* compiled_method = compiled_methods_[i];
4041     if (HasCompiledCode(compiled_method)) {
4042       oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
4043       oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
4044       if (oat_class_type == kOatClassSomeCompiled) {
4045         method_bitmap_->SetBit(i);
4046       }
4047     } else {
4048       oat_method_offsets_offsets_from_oat_class_[i] = 0;
4049     }
4050   }
4051 }
4052 
SizeOf() const4053 size_t OatWriter::OatClass::SizeOf() const {
4054   return ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
4055           + method_bitmap_size_
4056           + (sizeof(method_offsets_[0]) * method_offsets_.size());
4057 }
4058 
Write(OatWriter * oat_writer,OutputStream * out,const size_t file_offset) const4059 bool OatWriter::OatClassHeader::Write(OatWriter* oat_writer,
4060                                       OutputStream* out,
4061                                       const size_t file_offset) const {
4062   DCHECK_OFFSET_();
4063   if (!out->WriteFully(&status_, sizeof(status_))) {
4064     PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
4065     return false;
4066   }
4067   oat_writer->size_oat_class_status_ += sizeof(status_);
4068 
4069   if (!out->WriteFully(&type_, sizeof(type_))) {
4070     PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
4071     return false;
4072   }
4073   oat_writer->size_oat_class_type_ += sizeof(type_);
4074   return true;
4075 }
4076 
Write(OatWriter * oat_writer,OutputStream * out) const4077 bool OatWriter::OatClass::Write(OatWriter* oat_writer, OutputStream* out) const {
4078   if (method_bitmap_size_ != 0) {
4079     if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
4080       PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
4081       return false;
4082     }
4083     oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
4084 
4085     if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
4086       PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
4087       return false;
4088     }
4089     oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
4090   }
4091 
4092   if (!out->WriteFully(method_offsets_.data(), GetMethodOffsetsRawSize())) {
4093     PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
4094     return false;
4095   }
4096   oat_writer->size_oat_class_method_offsets_ += GetMethodOffsetsRawSize();
4097   return true;
4098 }
4099 
GetDebugInfo() const4100 debug::DebugInfo OatWriter::GetDebugInfo() const {
4101   debug::DebugInfo debug_info{};
4102   debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_info_);
4103   if (VdexWillContainDexFiles()) {
4104     DCHECK_EQ(dex_files_->size(), oat_dex_files_.size());
4105     for (size_t i = 0, size = dex_files_->size(); i != size; ++i) {
4106       const DexFile* dex_file = (*dex_files_)[i];
4107       const OatDexFile& oat_dex_file = oat_dex_files_[i];
4108       uint32_t dex_file_offset = oat_dex_file.dex_file_offset_;
4109       if (dex_file_offset != 0) {
4110         debug_info.dex_files.emplace(dex_file_offset, dex_file);
4111       }
4112     }
4113   }
4114   return debug_info;
4115 }
4116 
4117 }  // namespace linker
4118 }  // namespace art
4119