This repository was archived by the owner on Feb 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathoat_writer.cc
2469 lines (2191 loc) · 95.4 KB
/
oat_writer.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "oat_writer.h"
#include <unistd.h>
#include <zlib.h>
#include "arch/arm64/instruction_set_features_arm64.h"
#include "art_method-inl.h"
#include "base/allocator.h"
#include "base/bit_vector.h"
#include "base/file_magic.h"
#include "base/stl_util.h"
#include "base/unix_file/fd_file.h"
#include "class_linker.h"
#include "compiled_class.h"
#include "compiled_method.h"
#include "debug/method_debug_info.h"
#include "dex/verification_results.h"
#include "dex_file-inl.h"
#include "driver/compiler_driver.h"
#include "driver/compiler_options.h"
#include "gc/space/image_space.h"
#include "gc/space/space.h"
#include "handle_scope-inl.h"
#include "image_writer.h"
#include "linker/multi_oat_relative_patcher.h"
#include "linker/output_stream.h"
#include "mirror/array.h"
#include "mirror/class_loader.h"
#include "mirror/dex_cache-inl.h"
#include "mirror/object-inl.h"
#include "oat_quick_method_header.h"
#include "os.h"
#include "safe_map.h"
#include "scoped_thread_state_change.h"
#include "type_lookup_table.h"
#include "utils/dex_cache_arrays_layout-inl.h"
#include "verifier/method_verifier.h"
#include "zip_archive.h"
namespace art {
namespace { // anonymous namespace
typedef DexFile::Header __attribute__((aligned(1))) UnalignedDexFileHeader;
const UnalignedDexFileHeader* AsUnalignedDexFileHeader(const uint8_t* raw_data) {
return reinterpret_cast<const UnalignedDexFileHeader*>(raw_data);
}
class ChecksumUpdatingOutputStream : public OutputStream {
public:
ChecksumUpdatingOutputStream(OutputStream* out, OatHeader* oat_header)
: OutputStream(out->GetLocation()), out_(out), oat_header_(oat_header) { }
bool WriteFully(const void* buffer, size_t byte_count) OVERRIDE {
oat_header_->UpdateChecksum(buffer, byte_count);
return out_->WriteFully(buffer, byte_count);
}
off_t Seek(off_t offset, Whence whence) OVERRIDE {
return out_->Seek(offset, whence);
}
bool Flush() OVERRIDE {
return out_->Flush();
}
private:
OutputStream* const out_;
OatHeader* const oat_header_;
};
} // anonymous namespace
// Defines the location of the raw dex file to write.
class OatWriter::DexFileSource {
public:
explicit DexFileSource(ZipEntry* zip_entry)
: type_(kZipEntry), source_(zip_entry) {
DCHECK(source_ != nullptr);
}
explicit DexFileSource(File* raw_file)
: type_(kRawFile), source_(raw_file) {
DCHECK(source_ != nullptr);
}
explicit DexFileSource(const uint8_t* dex_file)
: type_(kRawData), source_(dex_file) {
DCHECK(source_ != nullptr);
}
bool IsZipEntry() const { return type_ == kZipEntry; }
bool IsRawFile() const { return type_ == kRawFile; }
bool IsRawData() const { return type_ == kRawData; }
ZipEntry* GetZipEntry() const {
DCHECK(IsZipEntry());
DCHECK(source_ != nullptr);
return static_cast<ZipEntry*>(const_cast<void*>(source_));
}
File* GetRawFile() const {
DCHECK(IsRawFile());
DCHECK(source_ != nullptr);
return static_cast<File*>(const_cast<void*>(source_));
}
const uint8_t* GetRawData() const {
DCHECK(IsRawData());
DCHECK(source_ != nullptr);
return static_cast<const uint8_t*>(source_);
}
void Clear() {
type_ = kNone;
source_ = nullptr;
}
private:
enum Type {
kNone,
kZipEntry,
kRawFile,
kRawData,
};
Type type_;
const void* source_;
};
class OatWriter::OatClass {
public:
OatClass(size_t offset,
const dchecked_vector<CompiledMethod*>& compiled_methods,
uint32_t num_non_null_compiled_methods,
mirror::Class::Status status);
OatClass(OatClass&& src) = default;
size_t GetOatMethodOffsetsOffsetFromOatHeader(size_t class_def_method_index_) const;
size_t GetOatMethodOffsetsOffsetFromOatClass(size_t class_def_method_index_) const;
size_t SizeOf() const;
bool Write(OatWriter* oat_writer, OutputStream* out, const size_t file_offset) const;
CompiledMethod* GetCompiledMethod(size_t class_def_method_index) const {
return compiled_methods_[class_def_method_index];
}
// Offset of start of OatClass from beginning of OatHeader. It is
// used to validate file position when writing.
size_t offset_;
// CompiledMethods for each class_def_method_index, or null if no method is available.
dchecked_vector<CompiledMethod*> compiled_methods_;
// Offset from OatClass::offset_ to the OatMethodOffsets for the
// class_def_method_index. If 0, it means the corresponding
// CompiledMethod entry in OatClass::compiled_methods_ should be
// null and that the OatClass::type_ should be kOatClassBitmap.
dchecked_vector<uint32_t> oat_method_offsets_offsets_from_oat_class_;
// Data to write.
static_assert(mirror::Class::Status::kStatusMax < (1 << 16), "class status won't fit in 16bits");
int16_t status_;
static_assert(OatClassType::kOatClassMax < (1 << 16), "oat_class type won't fit in 16bits");
uint16_t type_;
uint32_t method_bitmap_size_;
// bit vector indexed by ClassDef method index. When
// OatClassType::type_ is kOatClassBitmap, a set bit indicates the
// method has an OatMethodOffsets in methods_offsets_, otherwise
// the entry was ommited to save space. If OatClassType::type_ is
// not is kOatClassBitmap, the bitmap will be null.
std::unique_ptr<BitVector> method_bitmap_;
// OatMethodOffsets and OatMethodHeaders for each CompiledMethod
// present in the OatClass. Note that some may be missing if
// OatClass::compiled_methods_ contains null values (and
// oat_method_offsets_offsets_from_oat_class_ should contain 0
// values in this case).
dchecked_vector<OatMethodOffsets> method_offsets_;
dchecked_vector<OatQuickMethodHeader> method_headers_;
private:
size_t GetMethodOffsetsRawSize() const {
return method_offsets_.size() * sizeof(method_offsets_[0]);
}
DISALLOW_COPY_AND_ASSIGN(OatClass);
};
class OatWriter::OatDexFile {
public:
OatDexFile(const char* dex_file_location,
DexFileSource source,
CreateTypeLookupTable create_type_lookup_table);
OatDexFile(OatDexFile&& src) = default;
const char* GetLocation() const {
return dex_file_location_data_;
}
void ReserveTypeLookupTable(OatWriter* oat_writer);
void ReserveClassOffsets(OatWriter* oat_writer);
size_t SizeOf() const;
bool Write(OatWriter* oat_writer, OutputStream* out) const;
bool WriteClassOffsets(OatWriter* oat_writer, OutputStream* out);
// The source of the dex file.
DexFileSource source_;
// Whether to create the type lookup table.
CreateTypeLookupTable create_type_lookup_table_;
// Dex file size. Initialized when writing the dex file.
size_t dex_file_size_;
// Offset of start of OatDexFile from beginning of OatHeader. It is
// used to validate file position when writing.
size_t offset_;
// Data to write.
uint32_t dex_file_location_size_;
const char* dex_file_location_data_;
uint32_t dex_file_location_checksum_;
uint32_t dex_file_offset_;
uint32_t class_offsets_offset_;
uint32_t lookup_table_offset_;
// Data to write to a separate section.
dchecked_vector<uint32_t> class_offsets_;
private:
size_t GetClassOffsetsRawSize() const {
return class_offsets_.size() * sizeof(class_offsets_[0]);
}
DISALLOW_COPY_AND_ASSIGN(OatDexFile);
};
#define DCHECK_OFFSET() \
DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
<< "file_offset=" << file_offset << " relative_offset=" << relative_offset
#define DCHECK_OFFSET_() \
DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
<< "file_offset=" << file_offset << " offset_=" << offset_
OatWriter::OatWriter(bool compiling_boot_image, TimingLogger* timings)
: write_state_(WriteState::kAddingDexFileSources),
timings_(timings),
raw_dex_files_(),
zip_archives_(),
zipped_dex_files_(),
zipped_dex_file_locations_(),
compiler_driver_(nullptr),
image_writer_(nullptr),
compiling_boot_image_(compiling_boot_image),
dex_files_(nullptr),
size_(0u),
bss_size_(0u),
oat_data_offset_(0u),
oat_header_(nullptr),
size_dex_file_alignment_(0),
size_executable_offset_alignment_(0),
size_oat_header_(0),
size_oat_header_key_value_store_(0),
size_dex_file_(0),
size_interpreter_to_interpreter_bridge_(0),
size_interpreter_to_compiled_code_bridge_(0),
size_jni_dlsym_lookup_(0),
size_quick_generic_jni_trampoline_(0),
size_quick_imt_conflict_trampoline_(0),
size_quick_resolution_trampoline_(0),
size_quick_to_interpreter_bridge_(0),
size_trampoline_alignment_(0),
size_method_header_(0),
size_code_(0),
size_code_alignment_(0),
size_relative_call_thunks_(0),
size_misc_thunks_(0),
size_vmap_table_(0),
size_oat_dex_file_location_size_(0),
size_oat_dex_file_location_data_(0),
size_oat_dex_file_location_checksum_(0),
size_oat_dex_file_offset_(0),
size_oat_dex_file_class_offsets_offset_(0),
size_oat_dex_file_lookup_table_offset_(0),
size_oat_lookup_table_alignment_(0),
size_oat_lookup_table_(0),
size_oat_class_offsets_alignment_(0),
size_oat_class_offsets_(0),
size_oat_class_type_(0),
size_oat_class_status_(0),
size_oat_class_method_bitmaps_(0),
size_oat_class_method_offsets_(0),
relative_patcher_(nullptr),
absolute_patch_locations_() {
}
bool OatWriter::AddDexFileSource(const char* filename,
const char* location,
CreateTypeLookupTable create_type_lookup_table) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
uint32_t magic;
std::string error_msg;
ScopedFd fd(OpenAndReadMagic(filename, &magic, &error_msg));
if (fd.get() == -1) {
PLOG(ERROR) << "Failed to read magic number from dex file: '" << filename << "'";
return false;
} else if (IsDexMagic(magic)) {
// The file is open for reading, not writing, so it's OK to let the File destructor
// close it without checking for explicit Close(), so pass checkUsage = false.
raw_dex_files_.emplace_back(new File(fd.release(), location, /* checkUsage */ false));
oat_dex_files_.emplace_back(location,
DexFileSource(raw_dex_files_.back().get()),
create_type_lookup_table);
} else if (IsZipMagic(magic)) {
if (!AddZippedDexFilesSource(std::move(fd), location, create_type_lookup_table)) {
return false;
}
} else {
LOG(ERROR) << "Expected valid zip or dex file: '" << filename << "'";
return false;
}
return true;
}
// Add dex file source(s) from a zip file specified by a file handle.
bool OatWriter::AddZippedDexFilesSource(ScopedFd&& zip_fd,
const char* location,
CreateTypeLookupTable create_type_lookup_table) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
std::string error_msg;
zip_archives_.emplace_back(ZipArchive::OpenFromFd(zip_fd.release(), location, &error_msg));
ZipArchive* zip_archive = zip_archives_.back().get();
if (zip_archive == nullptr) {
LOG(ERROR) << "Failed to open zip from file descriptor for '" << location << "': "
<< error_msg;
return false;
}
for (size_t i = 0; ; ++i) {
std::string entry_name = DexFile::GetMultiDexClassesDexName(i);
std::unique_ptr<ZipEntry> entry(zip_archive->Find(entry_name.c_str(), &error_msg));
if (entry == nullptr) {
break;
}
zipped_dex_files_.push_back(std::move(entry));
zipped_dex_file_locations_.push_back(DexFile::GetMultiDexLocation(i, location));
const char* full_location = zipped_dex_file_locations_.back().c_str();
oat_dex_files_.emplace_back(full_location,
DexFileSource(zipped_dex_files_.back().get()),
create_type_lookup_table);
}
if (zipped_dex_file_locations_.empty()) {
LOG(ERROR) << "No dex files in zip file '" << location << "': " << error_msg;
return false;
}
return true;
}
// Add dex file source from raw memory.
bool OatWriter::AddRawDexFileSource(const ArrayRef<const uint8_t>& data,
const char* location,
uint32_t location_checksum,
CreateTypeLookupTable create_type_lookup_table) {
DCHECK(write_state_ == WriteState::kAddingDexFileSources);
if (data.size() < sizeof(DexFile::Header)) {
LOG(ERROR) << "Provided data is shorter than dex file header. size: "
<< data.size() << " File: " << location;
return false;
}
if (!ValidateDexFileHeader(data.data(), location)) {
return false;
}
const UnalignedDexFileHeader* header = AsUnalignedDexFileHeader(data.data());
if (data.size() < header->file_size_) {
LOG(ERROR) << "Truncated dex file data. Data size: " << data.size()
<< " file size from header: " << header->file_size_ << " File: " << location;
return false;
}
oat_dex_files_.emplace_back(location, DexFileSource(data.data()), create_type_lookup_table);
oat_dex_files_.back().dex_file_location_checksum_ = location_checksum;
return true;
}
dchecked_vector<const char*> OatWriter::GetSourceLocations() const {
dchecked_vector<const char*> locations;
locations.reserve(oat_dex_files_.size());
for (const OatDexFile& oat_dex_file : oat_dex_files_) {
locations.push_back(oat_dex_file.GetLocation());
}
return locations;
}
bool OatWriter::WriteAndOpenDexFiles(
OutputStream* rodata,
File* file,
InstructionSet instruction_set,
const InstructionSetFeatures* instruction_set_features,
SafeMap<std::string, std::string>* key_value_store,
bool verify,
/*out*/ std::unique_ptr<MemMap>* opened_dex_files_map,
/*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
CHECK(write_state_ == WriteState::kAddingDexFileSources);
size_t offset = InitOatHeader(instruction_set,
instruction_set_features,
dchecked_integral_cast<uint32_t>(oat_dex_files_.size()),
key_value_store);
offset = InitOatDexFiles(offset);
size_ = offset;
std::unique_ptr<MemMap> dex_files_map;
std::vector<std::unique_ptr<const DexFile>> dex_files;
if (!WriteDexFiles(rodata, file)) {
return false;
}
// Reserve space for type lookup tables and update type_lookup_table_offset_.
for (OatDexFile& oat_dex_file : oat_dex_files_) {
oat_dex_file.ReserveTypeLookupTable(this);
}
size_t size_after_type_lookup_tables = size_;
// Reserve space for class offsets and update class_offsets_offset_.
for (OatDexFile& oat_dex_file : oat_dex_files_) {
oat_dex_file.ReserveClassOffsets(this);
}
ChecksumUpdatingOutputStream checksum_updating_rodata(rodata, oat_header_.get());
if (!WriteOatDexFiles(&checksum_updating_rodata) ||
!ExtendForTypeLookupTables(rodata, file, size_after_type_lookup_tables) ||
!OpenDexFiles(file, verify, &dex_files_map, &dex_files) ||
!WriteTypeLookupTables(dex_files_map.get(), dex_files)) {
return false;
}
// Do a bulk checksum update for Dex[] and TypeLookupTable[]. Doing it piece by
// piece would be difficult because we're not using the OutpuStream directly.
if (!oat_dex_files_.empty()) {
size_t size = size_after_type_lookup_tables - oat_dex_files_[0].dex_file_offset_;
oat_header_->UpdateChecksum(dex_files_map->Begin(), size);
}
*opened_dex_files_map = std::move(dex_files_map);
*opened_dex_files = std::move(dex_files);
write_state_ = WriteState::kPrepareLayout;
return true;
}
void OatWriter::PrepareLayout(const CompilerDriver* compiler,
ImageWriter* image_writer,
const std::vector<const DexFile*>& dex_files,
linker::MultiOatRelativePatcher* relative_patcher) {
CHECK(write_state_ == WriteState::kPrepareLayout);
compiler_driver_ = compiler;
image_writer_ = image_writer;
dex_files_ = &dex_files;
relative_patcher_ = relative_patcher;
SetMultiOatRelativePatcherAdjustment();
if (compiling_boot_image_) {
CHECK(image_writer_ != nullptr);
}
InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
CHECK_EQ(instruction_set, oat_header_->GetInstructionSet());
uint32_t offset = size_;
{
TimingLogger::ScopedTiming split("InitOatClasses", timings_);
offset = InitOatClasses(offset);
}
{
TimingLogger::ScopedTiming split("InitOatMaps", timings_);
offset = InitOatMaps(offset);
}
{
TimingLogger::ScopedTiming split("InitOatCode", timings_);
offset = InitOatCode(offset);
}
{
TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings_);
offset = InitOatCodeDexFiles(offset);
}
size_ = offset;
if (!HasBootImage()) {
// Allocate space for app dex cache arrays in the .bss section.
size_t bss_start = RoundUp(size_, kPageSize);
size_t pointer_size = GetInstructionSetPointerSize(instruction_set);
bss_size_ = 0u;
for (const DexFile* dex_file : *dex_files_) {
dex_cache_arrays_offsets_.Put(dex_file, bss_start + bss_size_);
DexCacheArraysLayout layout(pointer_size, dex_file);
bss_size_ += layout.Size();
}
}
CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
if (compiling_boot_image_) {
CHECK_EQ(image_writer_ != nullptr,
oat_header_->GetStoreValueByKey(OatHeader::kImageLocationKey) == nullptr);
}
write_state_ = WriteState::kWriteRoData;
}
OatWriter::~OatWriter() {
}
class OatWriter::DexMethodVisitor {
public:
DexMethodVisitor(OatWriter* writer, size_t offset)
: writer_(writer),
offset_(offset),
dex_file_(nullptr),
class_def_index_(DexFile::kDexNoIndex) {
}
virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
DCHECK(dex_file_ == nullptr);
DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
dex_file_ = dex_file;
class_def_index_ = class_def_index;
return true;
}
virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
virtual bool EndClass() {
if (kIsDebugBuild) {
dex_file_ = nullptr;
class_def_index_ = DexFile::kDexNoIndex;
}
return true;
}
size_t GetOffset() const {
return offset_;
}
protected:
virtual ~DexMethodVisitor() { }
OatWriter* const writer_;
// The offset is usually advanced for each visited method by the derived class.
size_t offset_;
// The dex file and class def index are set in StartClass().
const DexFile* dex_file_;
size_t class_def_index_;
};
class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
public:
OatDexMethodVisitor(OatWriter* writer, size_t offset)
: DexMethodVisitor(writer, offset),
oat_class_index_(0u),
method_offsets_index_(0u) {
}
bool StartClass(const DexFile* dex_file, size_t class_def_index) {
DexMethodVisitor::StartClass(dex_file, class_def_index);
DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
method_offsets_index_ = 0u;
return true;
}
bool EndClass() {
++oat_class_index_;
return DexMethodVisitor::EndClass();
}
protected:
size_t oat_class_index_;
size_t method_offsets_index_;
};
class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
public:
InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
: DexMethodVisitor(writer, offset),
compiled_methods_(),
num_non_null_compiled_methods_(0u) {
size_t num_classes = 0u;
for (const OatDexFile& oat_dex_file : writer_->oat_dex_files_) {
num_classes += oat_dex_file.class_offsets_.size();
}
writer_->oat_classes_.reserve(num_classes);
compiled_methods_.reserve(256u);
}
bool StartClass(const DexFile* dex_file, size_t class_def_index) {
DexMethodVisitor::StartClass(dex_file, class_def_index);
compiled_methods_.clear();
num_non_null_compiled_methods_ = 0u;
return true;
}
bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED,
const ClassDataItemIterator& it) {
// Fill in the compiled_methods_ array for methods that have a
// CompiledMethod. We track the number of non-null entries in
// num_non_null_compiled_methods_ since we only want to allocate
// OatMethodOffsets for the compiled methods.
uint32_t method_idx = it.GetMemberIndex();
CompiledMethod* compiled_method =
writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
compiled_methods_.push_back(compiled_method);
if (compiled_method != nullptr) {
++num_non_null_compiled_methods_;
}
return true;
}
bool EndClass() {
ClassReference class_ref(dex_file_, class_def_index_);
CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
mirror::Class::Status status;
if (compiled_class != nullptr) {
status = compiled_class->GetStatus();
} else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
status = mirror::Class::kStatusError;
} else {
status = mirror::Class::kStatusNotReady;
}
writer_->oat_classes_.emplace_back(offset_,
compiled_methods_,
num_non_null_compiled_methods_,
status);
offset_ += writer_->oat_classes_.back().SizeOf();
return DexMethodVisitor::EndClass();
}
private:
dchecked_vector<CompiledMethod*> compiled_methods_;
size_t num_non_null_compiled_methods_;
};
class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
public:
InitCodeMethodVisitor(OatWriter* writer, size_t offset)
: OatDexMethodVisitor(writer, offset),
debuggable_(writer->GetCompilerDriver()->GetCompilerOptions().GetDebuggable()) {
writer_->absolute_patch_locations_.reserve(
writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
}
bool EndClass() {
OatDexMethodVisitor::EndClass();
if (oat_class_index_ == writer_->oat_classes_.size()) {
offset_ = writer_->relative_patcher_->ReserveSpaceEnd(offset_);
}
return true;
}
bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
SHARED_REQUIRES(Locks::mutator_lock_) {
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
if (compiled_method != nullptr) {
// Derived from CompiledMethod.
uint32_t quick_code_offset = 0;
ArrayRef<const uint8_t> quick_code = compiled_method->GetQuickCode();
uint32_t code_size = quick_code.size() * sizeof(uint8_t);
uint32_t thumb_offset = compiled_method->CodeDelta();
// Deduplicate code arrays if we are not producing debuggable code.
bool deduped = true;
MethodReference method_ref(dex_file_, it.GetMemberIndex());
if (debuggable_) {
quick_code_offset = writer_->relative_patcher_->GetOffset(method_ref);
if (quick_code_offset != 0u) {
// Duplicate methods, we want the same code for both of them so that the oat writer puts
// the same code in both ArtMethods so that we do not get different oat code at runtime.
} else {
quick_code_offset = NewQuickCodeOffset(compiled_method, it, thumb_offset);
deduped = false;
}
} else {
quick_code_offset = dedupe_map_.GetOrCreate(
compiled_method,
[this, &deduped, compiled_method, &it, thumb_offset]() {
deduped = false;
return NewQuickCodeOffset(compiled_method, it, thumb_offset);
});
}
if (code_size != 0) {
if (writer_->relative_patcher_->GetOffset(method_ref) != 0u) {
// TODO: Should this be a hard failure?
LOG(WARNING) << "Multiple definitions of "
<< PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
<< " offsets " << writer_->relative_patcher_->GetOffset(method_ref)
<< " " << quick_code_offset;
} else {
writer_->relative_patcher_->SetOffset(method_ref, quick_code_offset);
}
}
// Update quick method header.
DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
uint32_t vmap_table_offset = method_header->vmap_table_offset_;
// If we don't have quick code, then we must have a vmap, as that is how the dex2dex
// compiler records its transformations.
DCHECK(!quick_code.empty() || vmap_table_offset != 0);
// The code offset was 0 when the mapping/vmap table offset was set, so it's set
// to 0-offset and we need to adjust it by code_offset.
uint32_t code_offset = quick_code_offset - thumb_offset;
if (vmap_table_offset != 0u && code_offset != 0u) {
vmap_table_offset += code_offset;
DCHECK_LT(vmap_table_offset, code_offset) << "Overflow in oat offsets";
}
uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
*method_header = OatQuickMethodHeader(vmap_table_offset,
frame_size_in_bytes,
core_spill_mask,
fp_spill_mask,
code_size);
if (!deduped) {
// Update offsets. (Checksum is updated when writing.)
offset_ += sizeof(*method_header); // Method header is prepended before code.
offset_ += code_size;
// Record absolute patch locations.
if (!compiled_method->GetPatches().empty()) {
uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
for (const LinkerPatch& patch : compiled_method->GetPatches()) {
if (!patch.IsPcRelative()) {
writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
}
}
}
}
const CompilerOptions& compiler_options = writer_->compiler_driver_->GetCompilerOptions();
// Exclude quickened dex methods (code_size == 0) since they have no native code.
if (compiler_options.GenerateAnyDebugInfo() && code_size != 0) {
bool has_code_info = method_header->IsOptimized();
// Record debug information for this function if we are doing that.
debug::MethodDebugInfo info = debug::MethodDebugInfo();
info.trampoline_name = nullptr;
info.dex_file = dex_file_;
info.class_def_index = class_def_index_;
info.dex_method_index = it.GetMemberIndex();
info.access_flags = it.GetMethodAccessFlags();
info.code_item = it.GetMethodCodeItem();
info.isa = compiled_method->GetInstructionSet();
info.deduped = deduped;
info.is_native_debuggable = compiler_options.GetNativeDebuggable();
info.is_optimized = method_header->IsOptimized();
info.is_code_address_text_relative = true;
info.code_address = code_offset - writer_->oat_header_->GetExecutableOffset();
info.code_size = code_size;
info.frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
info.code_info = has_code_info ? compiled_method->GetVmapTable().data() : nullptr;
info.cfi = compiled_method->GetCFIInfo();
writer_->method_info_.push_back(info);
}
DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
offsets->code_offset_ = quick_code_offset;
++method_offsets_index_;
}
return true;
}
private:
struct CodeOffsetsKeyComparator {
bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
// Code is deduplicated by CompilerDriver, compare only data pointers.
if (lhs->GetQuickCode().data() != rhs->GetQuickCode().data()) {
return lhs->GetQuickCode().data() < rhs->GetQuickCode().data();
}
// If the code is the same, all other fields are likely to be the same as well.
if (UNLIKELY(lhs->GetVmapTable().data() != rhs->GetVmapTable().data())) {
return lhs->GetVmapTable().data() < rhs->GetVmapTable().data();
}
if (UNLIKELY(lhs->GetPatches().data() != rhs->GetPatches().data())) {
return lhs->GetPatches().data() < rhs->GetPatches().data();
}
return false;
}
};
uint32_t NewQuickCodeOffset(CompiledMethod* compiled_method,
const ClassDataItemIterator& it,
uint32_t thumb_offset) {
offset_ = writer_->relative_patcher_->ReserveSpace(
offset_, compiled_method, MethodReference(dex_file_, it.GetMemberIndex()));
offset_ = compiled_method->AlignCode(offset_);
DCHECK_ALIGNED_PARAM(offset_,
GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
return offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
}
// Deduplication is already done on a pointer basis by the compiler driver,
// so we can simply compare the pointers to find out if things are duplicated.
SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
// Cache of compiler's --debuggable option.
const bool debuggable_;
};
class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
public:
InitMapMethodVisitor(OatWriter* writer, size_t offset)
: OatDexMethodVisitor(writer, offset) {
}
bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
SHARED_REQUIRES(Locks::mutator_lock_) {
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
if (compiled_method != nullptr) {
DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
DCHECK_EQ(oat_class->method_headers_[method_offsets_index_].vmap_table_offset_, 0u);
ArrayRef<const uint8_t> map = compiled_method->GetVmapTable();
uint32_t map_size = map.size() * sizeof(map[0]);
if (map_size != 0u) {
size_t offset = dedupe_map_.GetOrCreate(
map.data(),
[this, map_size]() {
uint32_t new_offset = offset_;
offset_ += map_size;
return new_offset;
});
// Code offset is not initialized yet, so set the map offset to 0u-offset.
DCHECK_EQ(oat_class->method_offsets_[method_offsets_index_].code_offset_, 0u);
oat_class->method_headers_[method_offsets_index_].vmap_table_offset_ = 0u - offset;
}
++method_offsets_index_;
}
return true;
}
private:
// Deduplication is already done on a pointer basis by the compiler driver,
// so we can simply compare the pointers to find out if things are duplicated.
SafeMap<const uint8_t*, uint32_t> dedupe_map_;
};
class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
public:
InitImageMethodVisitor(OatWriter* writer, size_t offset)
: OatDexMethodVisitor(writer, offset),
pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
}
bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
SHARED_REQUIRES(Locks::mutator_lock_) {
const DexFile::TypeId& type_id =
dex_file_->GetTypeId(dex_file_->GetClassDef(class_def_index_).class_idx_);
const char* class_descriptor = dex_file_->GetTypeDescriptor(type_id);
// Skip methods that are not in the image.
if (!writer_->GetCompilerDriver()->IsImageClass(class_descriptor)) {
return true;
}
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
OatMethodOffsets offsets(0u);
if (compiled_method != nullptr) {
DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
offsets = oat_class->method_offsets_[method_offsets_index_];
++method_offsets_index_;
}
ClassLinker* linker = Runtime::Current()->GetClassLinker();
// Unchecked as we hold mutator_lock_ on entry.
ScopedObjectAccessUnchecked soa(Thread::Current());
StackHandleScope<1> hs(soa.Self());
Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(
Thread::Current(), *dex_file_)));
ArtMethod* method;
if (writer_->HasBootImage()) {
const InvokeType invoke_type = it.GetMethodInvokeType(
dex_file_->GetClassDef(class_def_index_));
method = linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
*dex_file_,
it.GetMemberIndex(),
dex_cache,
ScopedNullHandle<mirror::ClassLoader>(),
nullptr,
invoke_type);
if (method == nullptr) {
LOG(INTERNAL_FATAL) << "Unexpected failure to resolve a method: "
<< PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
soa.Self()->AssertPendingException();
mirror::Throwable* exc = soa.Self()->GetException();
std::string dump = exc->Dump();
LOG(FATAL) << dump;
UNREACHABLE();
}
} else {
// Should already have been resolved by the compiler, just peek into the dex cache.
// It may not be resolved if the class failed to verify, in this case, don't set the
// entrypoint. This is not fatal since the dex cache will contain a resolution method.
method = dex_cache->GetResolvedMethod(it.GetMemberIndex(), linker->GetImagePointerSize());
}
if (method != nullptr &&
compiled_method != nullptr &&
compiled_method->GetQuickCode().size() != 0) {
method->SetEntryPointFromQuickCompiledCodePtrSize(
reinterpret_cast<void*>(offsets.code_offset_), pointer_size_);
}
return true;
}
protected:
const size_t pointer_size_;
};
class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
public:
WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
: OatDexMethodVisitor(writer, relative_offset),
out_(out),
file_offset_(file_offset),
soa_(Thread::Current()),
no_thread_suspension_(soa_.Self(), "OatWriter patching"),
class_linker_(Runtime::Current()->GetClassLinker()),
dex_cache_(nullptr) {
patched_code_.reserve(16 * KB);
if (writer_->HasBootImage()) {
// If we're creating the image, the address space must be ready so that we can apply patches.
CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
}
}
~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
}
bool StartClass(const DexFile* dex_file, size_t class_def_index)
SHARED_REQUIRES(Locks::mutator_lock_) {
OatDexMethodVisitor::StartClass(dex_file, class_def_index);
if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
dex_cache_ = class_linker_->FindDexCache(Thread::Current(), *dex_file);
DCHECK(dex_cache_ != nullptr);
}
return true;
}
bool EndClass() SHARED_REQUIRES(Locks::mutator_lock_) {
bool result = OatDexMethodVisitor::EndClass();
if (oat_class_index_ == writer_->oat_classes_.size()) {
DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
if (UNLIKELY(offset_ == 0u)) {
PLOG(ERROR) << "Failed to write final relative call thunks";
result = false;
}
}
return result;
}
bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
SHARED_REQUIRES(Locks::mutator_lock_) {
OatClass* oat_class = &writer_->oat_classes_[oat_class_index_];
const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
// No thread suspension since dex_cache_ that may get invalidated if that occurs.
ScopedAssertNoThreadSuspension tsc(Thread::Current(), __FUNCTION__);
if (compiled_method != nullptr) { // ie. not an abstract method
size_t file_offset = file_offset_;
OutputStream* out = out_;