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