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