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