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 #ifndef ART_DEX2OAT_LINKER_OAT_WRITER_H_
18 #define ART_DEX2OAT_LINKER_OAT_WRITER_H_
19 
20 #include <stdint.h>
21 #include <cstddef>
22 #include <list>
23 #include <memory>
24 #include <vector>
25 
26 #include "base/array_ref.h"
27 #include "base/dchecked_vector.h"
28 #include "base/os.h"
29 #include "base/mem_map.h"
30 #include "base/safe_map.h"
31 #include "debug/debug_info.h"
32 #include "dex/compact_dex_level.h"
33 #include "dex/method_reference.h"
34 #include "dex/string_reference.h"
35 #include "dex/type_reference.h"
36 #include "linker/relative_patcher.h"  // For RelativePatcherTargetProvider.
37 #include "mirror/class.h"
38 
39 namespace art {
40 
41 class BitVector;
42 class CompiledMethod;
43 class CompilerDriver;
44 class CompilerOptions;
45 class DexContainer;
46 class OatHeader;
47 class OutputStream;
48 class ProfileCompilationInfo;
49 class TimingLogger;
50 class TypeLookupTable;
51 class VdexFile;
52 class ZipEntry;
53 
54 namespace debug {
55 struct MethodDebugInfo;
56 }  // namespace debug
57 
58 namespace verifier {
59 class VerifierDeps;
60 }  // namespace verifier
61 
62 namespace linker {
63 
64 class ImageWriter;
65 class MultiOatRelativePatcher;
66 
67 enum class CopyOption {
68   kNever,
69   kAlways,
70   kOnlyIfCompressed
71 };
72 
73 // OatHeader         variable length with count of D OatDexFiles
74 //
75 // TypeLookupTable[0] one descriptor to class def index hash table for each OatDexFile.
76 // TypeLookupTable[1]
77 // ...
78 // TypeLookupTable[D]
79 //
80 // ClassOffsets[0]   one table of OatClass offsets for each class def for each OatDexFile.
81 // ClassOffsets[1]
82 // ...
83 // ClassOffsets[D]
84 //
85 // OatClass[0]       one variable sized OatClass for each of C DexFile::ClassDefs
86 // OatClass[1]       contains OatClass entries with class status, offsets to code, etc.
87 // ...
88 // OatClass[C]
89 //
90 // MethodBssMapping  one variable sized MethodBssMapping for each dex file, optional.
91 // MethodBssMapping
92 // ...
93 // MethodBssMapping
94 //
95 // VmapTable         one variable sized VmapTable blob (CodeInfo or QuickeningInfo).
96 // VmapTable         VmapTables are deduplicated.
97 // ...
98 // VmapTable
99 //
100 // OatDexFile[0]     one variable sized OatDexFile with offsets to Dex and OatClasses
101 // OatDexFile[1]
102 // ...
103 // OatDexFile[D]
104 //
105 // padding           if necessary so that the following code will be page aligned
106 //
107 // OatMethodHeader   fixed size header for a CompiledMethod including the size of the MethodCode.
108 // MethodCode        one variable sized blob with the code of a CompiledMethod.
109 // OatMethodHeader   (OatMethodHeader, MethodCode) pairs are deduplicated.
110 // MethodCode
111 // ...
112 // OatMethodHeader
113 // MethodCode
114 //
115 class OatWriter {
116  public:
117   enum class CreateTypeLookupTable {
118     kCreate,
119     kDontCreate,
120     kDefault = kCreate
121   };
122 
123   OatWriter(const CompilerOptions& compiler_options,
124             TimingLogger* timings,
125             ProfileCompilationInfo* info,
126             CompactDexLevel compact_dex_level);
127 
128   // To produce a valid oat file, the user must first add sources with any combination of
129   //   - AddDexFileSource(),
130   //   - AddRawDexFileSource(),
131   //   - AddVdexDexFilesSource().
132   // Then the user must call in order
133   //   - WriteAndOpenDexFiles()
134   //   - StartRoData()
135   //   - WriteVerifierDeps()
136   //   - WriteQuickeningInfo()
137   //   - WriteChecksumsAndVdexHeader()
138   //   - PrepareLayout(),
139   //   - WriteRodata(),
140   //   - WriteCode(),
141   //   - WriteDataBimgRelRo() iff GetDataBimgRelRoSize() != 0,
142   //   - WriteHeader().
143 
144   // Add dex file source(s) from a file, either a plain dex file or
145   // a zip file with one or more dex files.
146   bool AddDexFileSource(
147       const char* filename,
148       const char* location,
149       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
150   // Add dex file source(s) from a file specified by a file handle.
151   // Note: The `dex_file_fd` specifies a plain dex file or a zip file.
152   bool AddDexFileSource(
153       File&& dex_file_fd,
154       const char* location,
155       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
156   // Add dex file source from raw memory.
157   bool AddRawDexFileSource(
158       const ArrayRef<const uint8_t>& data,
159       const char* location,
160       uint32_t location_checksum,
161       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
162   // Add dex file source(s) from a vdex file.
163   bool AddVdexDexFilesSource(
164       const VdexFile& vdex_file,
165       const char* location,
166       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
167   dchecked_vector<std::string> GetSourceLocations() const;
168 
169   // Write raw dex files to the vdex file, mmap the file and open the dex files from it.
170   // The `verify` setting dictates whether the dex file verifier should check the dex files.
171   // This is generally the case, and should only be false for tests.
172   // If `update_input_vdex` is true, then this method won't actually write the dex files,
173   // and the compiler will just re-use the existing vdex file.
174   bool WriteAndOpenDexFiles(File* vdex_file,
175                             bool verify,
176                             bool update_input_vdex,
177                             CopyOption copy_dex_files,
178                             /*out*/ std::vector<MemMap>* opened_dex_files_map,
179                             /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files);
180   // Start writing .rodata, including supporting data structures for dex files.
181   bool StartRoData(const std::vector<const DexFile*>& dex_files,
182                    OutputStream* oat_rodata,
183                    SafeMap<std::string, std::string>* key_value_store);
184   // Initialize the writer with the given parameters.
185   void Initialize(const CompilerDriver* compiler_driver,
186                   ImageWriter* image_writer,
187                   const std::vector<const DexFile*>& dex_files);
188   bool WriteQuickeningInfo(OutputStream* vdex_out);
189   bool WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps);
190   bool WriteChecksumsAndVdexHeader(OutputStream* vdex_out);
191 
192   // Prepare layout of remaining data.
193   void PrepareLayout(MultiOatRelativePatcher* relative_patcher);
194   // Write the rest of .rodata section (ClassOffsets[], OatClass[], maps).
195   bool WriteRodata(OutputStream* out);
196   // Write the code to the .text section.
197   bool WriteCode(OutputStream* out);
198   // Write the boot image relocation data to the .data.bimg.rel.ro section.
199   bool WriteDataBimgRelRo(OutputStream* out);
200   // Check the size of the written oat file.
201   bool CheckOatSize(OutputStream* out, size_t file_offset, size_t relative_offset);
202   // Write the oat header. This finalizes the oat file.
203   bool WriteHeader(OutputStream* out);
204 
205   // Returns whether the oat file has an associated image.
HasImage()206   bool HasImage() const {
207     // Since the image is being created at the same time as the oat file,
208     // check if there's an image writer.
209     return image_writer_ != nullptr;
210   }
211 
GetOatHeader()212   const OatHeader& GetOatHeader() const {
213     return *oat_header_;
214   }
215 
GetCodeSize()216   size_t GetCodeSize() const {
217     return code_size_;
218   }
219 
GetOatSize()220   size_t GetOatSize() const {
221     return oat_size_;
222   }
223 
GetDataBimgRelRoSize()224   size_t GetDataBimgRelRoSize() const {
225     return data_bimg_rel_ro_size_;
226   }
227 
GetBssSize()228   size_t GetBssSize() const {
229     return bss_size_;
230   }
231 
GetBssMethodsOffset()232   size_t GetBssMethodsOffset() const {
233     return bss_methods_offset_;
234   }
235 
GetBssRootsOffset()236   size_t GetBssRootsOffset() const {
237     return bss_roots_offset_;
238   }
239 
GetVdexSize()240   size_t GetVdexSize() const {
241     return vdex_size_;
242   }
243 
GetOatDataOffset()244   size_t GetOatDataOffset() const {
245     return oat_data_offset_;
246   }
247 
248   ~OatWriter();
249 
250   debug::DebugInfo GetDebugInfo() const;
251 
GetCompilerDriver()252   const CompilerDriver* GetCompilerDriver() const {
253     return compiler_driver_;
254   }
255 
GetCompilerOptions()256   const CompilerOptions& GetCompilerOptions() const {
257     return compiler_options_;
258   }
259 
260  private:
261   class ChecksumUpdatingOutputStream;
262   class DexFileSource;
263   class OatClassHeader;
264   class OatClass;
265   class OatDexFile;
266 
267   // The function VisitDexMethods() below iterates through all the methods in all
268   // the compiled dex files in order of their definitions. The method visitor
269   // classes provide individual bits of processing for each of the passes we need to
270   // first collect the data we want to write to the oat file and then, in later passes,
271   // to actually write it.
272   class DexMethodVisitor;
273   class OatDexMethodVisitor;
274   class InitBssLayoutMethodVisitor;
275   class InitOatClassesMethodVisitor;
276   class LayoutCodeMethodVisitor;
277   class LayoutReserveOffsetCodeMethodVisitor;
278   struct OrderedMethodData;
279   class OrderedMethodVisitor;
280   class InitCodeMethodVisitor;
281   class InitMapMethodVisitor;
282   class InitImageMethodVisitor;
283   class WriteCodeMethodVisitor;
284   class WriteMapMethodVisitor;
285   class WriteQuickeningInfoMethodVisitor;
286   class WriteQuickeningInfoOffsetsMethodVisitor;
287 
288   // Visit all the methods in all the compiled dex files in their definition order
289   // with a given DexMethodVisitor.
290   bool VisitDexMethods(DexMethodVisitor* visitor);
291 
292   // If `update_input_vdex` is true, then this method won't actually write the dex files,
293   // and the compiler will just re-use the existing vdex file.
294   bool WriteDexFiles(OutputStream* out,
295                      File* file,
296                      bool update_input_vdex,
297                      CopyOption copy_dex_files);
298   bool WriteDexFile(OutputStream* out,
299                     File* file,
300                     OatDexFile* oat_dex_file,
301                     bool update_input_vdex);
302   bool SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file);
303   bool LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file);
304   bool WriteDexFile(OutputStream* out,
305                     File* file,
306                     OatDexFile* oat_dex_file,
307                     ZipEntry* dex_file);
308   bool WriteDexFile(OutputStream* out,
309                     File* file,
310                     OatDexFile* oat_dex_file,
311                     File* dex_file);
312   bool WriteDexFile(OutputStream* out,
313                     OatDexFile* oat_dex_file,
314                     const uint8_t* dex_file,
315                     bool update_input_vdex);
316   bool OpenDexFiles(File* file,
317                     bool verify,
318                     /*out*/ std::vector<MemMap>* opened_dex_files_map,
319                     /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files);
320 
321   size_t InitOatHeader(uint32_t num_dex_files, SafeMap<std::string, std::string>* key_value_store);
322   size_t InitClassOffsets(size_t offset);
323   size_t InitOatClasses(size_t offset);
324   size_t InitOatMaps(size_t offset);
325   size_t InitIndexBssMappings(size_t offset);
326   size_t InitOatDexFiles(size_t offset);
327   size_t InitOatCode(size_t offset);
328   size_t InitOatCodeDexFiles(size_t offset);
329   size_t InitDataBimgRelRoLayout(size_t offset);
330   void InitBssLayout(InstructionSet instruction_set);
331 
332   size_t WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset);
333   size_t WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset);
334   size_t WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset);
335   size_t WriteIndexBssMappings(OutputStream* out, size_t file_offset, size_t relative_offset);
336   size_t WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset);
337   size_t WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset);
338   size_t WriteCodeDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset);
339   size_t WriteDataBimgRelRo(OutputStream* out, size_t file_offset, size_t relative_offset);
340 
341   bool RecordOatDataOffset(OutputStream* out);
342   bool WriteTypeLookupTables(OutputStream* oat_rodata,
343                              const std::vector<const DexFile*>& opened_dex_files);
344   bool WriteDexLayoutSections(OutputStream* oat_rodata,
345                               const std::vector<const DexFile*>& opened_dex_files);
346   bool WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta);
347   bool WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat);
348   void SetMultiOatRelativePatcherAdjustment();
349   void CloseSources();
350 
351   bool MayHaveCompiledMethods() const;
352 
VdexWillContainDexFiles()353   bool VdexWillContainDexFiles() const {
354     return dex_files_ != nullptr && extract_dex_files_into_vdex_;
355   }
356 
357   enum class WriteState {
358     kAddingDexFileSources,
359     kStartRoData,
360     kInitialize,
361     kPrepareLayout,
362     kWriteRoData,
363     kWriteText,
364     kWriteDataBimgRelRo,
365     kWriteHeader,
366     kDone
367   };
368 
369   WriteState write_state_;
370   TimingLogger* timings_;
371 
372   std::vector<std::unique_ptr<File>> raw_dex_files_;
373   std::vector<std::unique_ptr<ZipArchive>> zip_archives_;
374   std::vector<std::unique_ptr<ZipEntry>> zipped_dex_files_;
375 
376   // Using std::list<> which doesn't move elements around on push/emplace_back().
377   // We need this because we keep plain pointers to the strings' c_str().
378   std::list<std::string> zipped_dex_file_locations_;
379 
380   dchecked_vector<debug::MethodDebugInfo> method_info_;
381 
382   std::vector<uint8_t> code_info_data_;
383 
384   const CompilerDriver* compiler_driver_;
385   const CompilerOptions& compiler_options_;
386   ImageWriter* image_writer_;
387   // Whether the dex files being compiled are going to be extracted to the vdex.
388   bool extract_dex_files_into_vdex_;
389 
390   // note OatFile does not take ownership of the DexFiles
391   const std::vector<const DexFile*>* dex_files_;
392 
393   // Whether this is the primary oat file.
394   bool primary_oat_file_;
395 
396   // Size required for Vdex data structures.
397   size_t vdex_size_;
398 
399   // Offset of section holding Dex files inside Vdex.
400   size_t vdex_dex_files_offset_;
401 
402   // Offset of section holding shared dex data section in the Vdex.
403   size_t vdex_dex_shared_data_offset_;
404 
405   // Offset of section holding VerifierDeps inside Vdex.
406   size_t vdex_verifier_deps_offset_;
407 
408   // Offset of section holding quickening info inside Vdex.
409   size_t vdex_quickening_info_offset_;
410 
411   // OAT checksum.
412   uint32_t oat_checksum_;
413 
414   // Size of the .text segment.
415   size_t code_size_;
416 
417   // Size required for Oat data structures.
418   size_t oat_size_;
419 
420   // The start of the required .data.bimg.rel.ro section.
421   size_t data_bimg_rel_ro_start_;
422 
423   // The size of the required .data.bimg.rel.ro section holding the boot image relocations.
424   size_t data_bimg_rel_ro_size_;
425 
426   // The start of the required .bss section.
427   size_t bss_start_;
428 
429   // The size of the required .bss section holding the DexCache data and GC roots.
430   size_t bss_size_;
431 
432   // The offset of the methods in .bss section.
433   size_t bss_methods_offset_;
434 
435   // The offset of the GC roots in .bss section.
436   size_t bss_roots_offset_;
437 
438   // Map for allocating .data.bimg.rel.ro entries. Indexed by the boot image offset of the
439   // relocation. The value is the assigned offset within the .data.bimg.rel.ro section.
440   SafeMap<uint32_t, size_t> data_bimg_rel_ro_entries_;
441 
442   // Map for recording references to ArtMethod entries in .bss.
443   SafeMap<const DexFile*, BitVector> bss_method_entry_references_;
444 
445   // Map for recording references to GcRoot<mirror::Class> entries in .bss.
446   SafeMap<const DexFile*, BitVector> bss_type_entry_references_;
447 
448   // Map for recording references to GcRoot<mirror::String> entries in .bss.
449   SafeMap<const DexFile*, BitVector> bss_string_entry_references_;
450 
451   // Map for allocating ArtMethod entries in .bss. Indexed by MethodReference for the target
452   // method in the dex file with the "method reference value comparator" for deduplication.
453   // The value is the target offset for patching, starting at `bss_start_ + bss_methods_offset_`.
454   SafeMap<MethodReference, size_t, MethodReferenceValueComparator> bss_method_entries_;
455 
456   // Map for allocating Class entries in .bss. Indexed by TypeReference for the source
457   // type in the dex file with the "type value comparator" for deduplication. The value
458   // is the target offset for patching, starting at `bss_start_ + bss_roots_offset_`.
459   SafeMap<TypeReference, size_t, TypeReferenceValueComparator> bss_type_entries_;
460 
461   // Map for allocating String entries in .bss. Indexed by StringReference for the source
462   // string in the dex file with the "string value comparator" for deduplication. The value
463   // is the target offset for patching, starting at `bss_start_ + bss_roots_offset_`.
464   SafeMap<StringReference, size_t, StringReferenceValueComparator> bss_string_entries_;
465 
466   // Offset of the oat data from the start of the mmapped region of the elf file.
467   size_t oat_data_offset_;
468 
469   // Fake OatDexFiles to hold type lookup tables for the compiler.
470   std::vector<std::unique_ptr<art::OatDexFile>> type_lookup_table_oat_dex_files_;
471 
472   // data to write
473   std::unique_ptr<OatHeader> oat_header_;
474   dchecked_vector<OatDexFile> oat_dex_files_;
475   dchecked_vector<OatClassHeader> oat_class_headers_;
476   dchecked_vector<OatClass> oat_classes_;
477   std::unique_ptr<const std::vector<uint8_t>> jni_dlsym_lookup_trampoline_;
478   std::unique_ptr<const std::vector<uint8_t>> jni_dlsym_lookup_critical_trampoline_;
479   std::unique_ptr<const std::vector<uint8_t>> quick_generic_jni_trampoline_;
480   std::unique_ptr<const std::vector<uint8_t>> quick_imt_conflict_trampoline_;
481   std::unique_ptr<const std::vector<uint8_t>> quick_resolution_trampoline_;
482   std::unique_ptr<const std::vector<uint8_t>> quick_to_interpreter_bridge_;
483 
484   // output stats
485   uint32_t size_vdex_header_;
486   uint32_t size_vdex_checksums_;
487   uint32_t size_dex_file_alignment_;
488   uint32_t size_executable_offset_alignment_;
489   uint32_t size_oat_header_;
490   uint32_t size_oat_header_key_value_store_;
491   uint32_t size_dex_file_;
492   uint32_t size_verifier_deps_;
493   uint32_t size_verifier_deps_alignment_;
494   uint32_t size_quickening_info_;
495   uint32_t size_quickening_info_alignment_;
496   uint32_t size_interpreter_to_interpreter_bridge_;
497   uint32_t size_interpreter_to_compiled_code_bridge_;
498   uint32_t size_jni_dlsym_lookup_trampoline_;
499   uint32_t size_jni_dlsym_lookup_critical_trampoline_;
500   uint32_t size_quick_generic_jni_trampoline_;
501   uint32_t size_quick_imt_conflict_trampoline_;
502   uint32_t size_quick_resolution_trampoline_;
503   uint32_t size_quick_to_interpreter_bridge_;
504   uint32_t size_trampoline_alignment_;
505   uint32_t size_method_header_;
506   uint32_t size_code_;
507   uint32_t size_code_alignment_;
508   uint32_t size_data_bimg_rel_ro_;
509   uint32_t size_data_bimg_rel_ro_alignment_;
510   uint32_t size_relative_call_thunks_;
511   uint32_t size_misc_thunks_;
512   uint32_t size_vmap_table_;
513   uint32_t size_method_info_;
514   uint32_t size_oat_dex_file_location_size_;
515   uint32_t size_oat_dex_file_location_data_;
516   uint32_t size_oat_dex_file_location_checksum_;
517   uint32_t size_oat_dex_file_offset_;
518   uint32_t size_oat_dex_file_class_offsets_offset_;
519   uint32_t size_oat_dex_file_lookup_table_offset_;
520   uint32_t size_oat_dex_file_dex_layout_sections_offset_;
521   uint32_t size_oat_dex_file_dex_layout_sections_;
522   uint32_t size_oat_dex_file_dex_layout_sections_alignment_;
523   uint32_t size_oat_dex_file_method_bss_mapping_offset_;
524   uint32_t size_oat_dex_file_type_bss_mapping_offset_;
525   uint32_t size_oat_dex_file_string_bss_mapping_offset_;
526   uint32_t size_oat_lookup_table_alignment_;
527   uint32_t size_oat_lookup_table_;
528   uint32_t size_oat_class_offsets_alignment_;
529   uint32_t size_oat_class_offsets_;
530   uint32_t size_oat_class_type_;
531   uint32_t size_oat_class_status_;
532   uint32_t size_oat_class_method_bitmaps_;
533   uint32_t size_oat_class_method_offsets_;
534   uint32_t size_method_bss_mappings_;
535   uint32_t size_type_bss_mappings_;
536   uint32_t size_string_bss_mappings_;
537 
538   // The helper for processing relative patches is external so that we can patch across oat files.
539   MultiOatRelativePatcher* relative_patcher_;
540 
541   // Profile info used to generate new layout of files.
542   ProfileCompilationInfo* profile_compilation_info_;
543 
544   // Compact dex level that is generated.
545   CompactDexLevel compact_dex_level_;
546 
547   using OrderedMethodList = std::vector<OrderedMethodData>;
548 
549   // List of compiled methods, sorted by the order defined in OrderedMethodData.
550   // Methods can be inserted more than once in case of duplicated methods.
551   // This pointer is only non-null after InitOatCodeDexFiles succeeds.
552   std::unique_ptr<OrderedMethodList> ordered_methods_;
553 
554   // Container of shared dex data.
555   std::unique_ptr<DexContainer> dex_container_;
556 
557   DISALLOW_COPY_AND_ASSIGN(OatWriter);
558 };
559 
560 }  // namespace linker
561 }  // namespace art
562 
563 #endif  // ART_DEX2OAT_LINKER_OAT_WRITER_H_
564