-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathimage_snapshot.cc
More file actions
960 lines (831 loc) · 32.8 KB
/
Copy pathimage_snapshot.cc
File metadata and controls
960 lines (831 loc) · 32.8 KB
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
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/image_snapshot.h"
#include "platform/assert.h"
#include "vm/compiler/backend/code_statistics.h"
#include "vm/dwarf.h"
#include "vm/elf.h"
#include "vm/hash.h"
#include "vm/hash_map.h"
#include "vm/heap/heap.h"
#include "vm/instructions.h"
#include "vm/json_writer.h"
#include "vm/object.h"
#include "vm/object_store.h"
#include "vm/program_visitor.h"
#include "vm/stub_code.h"
#include "vm/timeline.h"
#include "vm/type_testing_stubs.h"
namespace dart {
#if defined(DART_PRECOMPILER)
DEFINE_FLAG(bool,
print_instruction_stats,
false,
"Print instruction statistics");
DEFINE_FLAG(charp,
print_instructions_sizes_to,
NULL,
"Print sizes of all instruction objects to the given file");
#endif
DEFINE_FLAG(bool,
trace_reused_instructions,
false,
"Print code that lacks reusable instructions");
intptr_t ObjectOffsetTrait::Hashcode(Key key) {
RawObject* obj = key;
ASSERT(!obj->IsSmi());
uword body = RawObject::ToAddr(obj) + sizeof(RawObject);
uword end = RawObject::ToAddr(obj) + obj->HeapSize();
uint32_t hash = obj->GetClassId();
// Don't include the header. Objects in the image are pre-marked, but objects
// in the current isolate are not.
for (uword cursor = body; cursor < end; cursor += sizeof(uint32_t)) {
hash = CombineHashes(hash, *reinterpret_cast<uint32_t*>(cursor));
}
return FinalizeHash(hash, 30);
}
bool ObjectOffsetTrait::IsKeyEqual(Pair pair, Key key) {
RawObject* a = pair.object;
RawObject* b = key;
ASSERT(!a->IsSmi());
ASSERT(!b->IsSmi());
if (a->GetClassId() != b->GetClassId()) {
return false;
}
intptr_t heap_size = a->HeapSize();
if (b->HeapSize() != heap_size) {
return false;
}
// Don't include the header. Objects in the image are pre-marked, but objects
// in the current isolate are not.
uword body_a = RawObject::ToAddr(a) + sizeof(RawObject);
uword body_b = RawObject::ToAddr(b) + sizeof(RawObject);
uword body_size = heap_size - sizeof(RawObject);
return 0 == memcmp(reinterpret_cast<const void*>(body_a),
reinterpret_cast<const void*>(body_b), body_size);
}
ImageWriter::ImageWriter(Heap* heap,
const void* shared_objects,
const void* shared_instructions,
const void* reused_instructions)
: heap_(heap),
next_data_offset_(0),
next_text_offset_(0),
objects_(),
instructions_() {
ResetOffsets();
SetupShared(&shared_objects_, shared_objects);
SetupShared(&shared_instructions_, shared_instructions);
SetupShared(&reuse_instructions_, reused_instructions);
}
void ImageWriter::PrepareForSerialization(
GrowableArray<ImageWriterCommand>* commands) {
if (commands != nullptr) {
const intptr_t initial_offset = next_text_offset_;
for (auto& inst : *commands) {
ASSERT((initial_offset + inst.expected_offset) == next_text_offset_);
switch (inst.op) {
case ImageWriterCommand::InsertInstructionOfCode: {
RawCode* code = inst.insert_instruction_of_code.code;
RawInstructions* instructions = Code::InstructionsOf(code);
const intptr_t offset = next_text_offset_;
instructions_.Add(InstructionsData(instructions, code, offset));
next_text_offset_ += SizeInSnapshot(instructions);
ASSERT(heap_->GetObjectId(instructions) == 0);
heap_->SetObjectId(instructions, offset);
break;
}
case ImageWriterCommand::InsertBytesOfTrampoline: {
auto trampoline_bytes = inst.insert_trampoline_bytes.buffer;
auto trampoline_length = inst.insert_trampoline_bytes.buffer_length;
const intptr_t offset = next_text_offset_;
instructions_.Add(
InstructionsData(trampoline_bytes, trampoline_length, offset));
next_text_offset_ += trampoline_length;
break;
}
default:
UNREACHABLE();
}
}
}
}
void ImageWriter::SetupShared(ObjectOffsetMap* map, const void* shared_image) {
if (shared_image == NULL) {
return;
}
Image image(shared_image);
uword obj_addr = reinterpret_cast<uword>(image.object_start());
uword end_addr = obj_addr + image.object_size();
while (obj_addr < end_addr) {
int32_t offset = obj_addr - reinterpret_cast<uword>(shared_image);
RawObject* raw_obj = RawObject::FromAddr(obj_addr);
ObjectOffsetPair pair;
pair.object = raw_obj;
pair.offset = offset;
map->Insert(pair);
obj_addr += SizeInSnapshot(raw_obj);
}
ASSERT(obj_addr == end_addr);
}
int32_t ImageWriter::GetTextOffsetFor(RawInstructions* instructions,
RawCode* code) {
intptr_t offset = heap_->GetObjectId(instructions);
if (offset != 0) {
return offset;
}
if (!reuse_instructions_.IsEmpty()) {
ObjectOffsetPair* pair = reuse_instructions_.Lookup(instructions);
if (pair == NULL) {
// Code should have been removed by DropCodeWithoutReusableInstructions.
return 0;
}
ASSERT(pair->offset != 0);
return pair->offset;
}
ObjectOffsetPair* pair = shared_instructions_.Lookup(instructions);
if (pair != NULL) {
// Negative offsets tell the reader the offset is w/r/t the shared
// instructions image instead of the app-specific instructions image.
// Compare ImageReader::GetInstructionsAt.
ASSERT(pair->offset != 0);
return -pair->offset;
}
offset = next_text_offset_;
heap_->SetObjectId(instructions, offset);
next_text_offset_ += SizeInSnapshot(instructions);
instructions_.Add(InstructionsData(instructions, code, offset));
ASSERT(offset != 0);
return offset;
}
intptr_t ImageWriter::SizeInSnapshot(RawObject* raw_object) {
return raw_object->HeapSize();
}
bool ImageWriter::GetSharedDataOffsetFor(RawObject* raw_object,
uint32_t* offset) {
ObjectOffsetPair* pair = shared_objects_.Lookup(raw_object);
if (pair == NULL) {
return false;
}
*offset = pair->offset;
return true;
}
uint32_t ImageWriter::GetDataOffsetFor(RawObject* raw_object) {
intptr_t snap_size = SizeInSnapshot(raw_object);
intptr_t offset = next_data_offset_;
next_data_offset_ += snap_size;
objects_.Add(ObjectData(raw_object));
return offset;
}
#if defined(DART_PRECOMPILER)
void ImageWriter::DumpInstructionStats() {
CombinedCodeStatistics instruction_stats;
for (intptr_t i = 0; i < instructions_.length(); i++) {
auto& data = instructions_[i];
CodeStatistics* stats = data.insns_->stats();
if (stats != nullptr) {
stats->AppendTo(&instruction_stats);
}
}
instruction_stats.DumpStatistics();
}
void ImageWriter::DumpInstructionsSizes() {
auto thread = Thread::Current();
auto zone = thread->zone();
auto& cls = Class::Handle(zone);
auto& lib = Library::Handle(zone);
auto& owner = Object::Handle(zone);
auto& url = String::Handle(zone);
auto& name = String::Handle(zone);
JSONWriter js;
js.OpenArray();
for (intptr_t i = 0; i < instructions_.length(); i++) {
auto& data = instructions_[i];
owner = data.code_->owner();
js.OpenObject();
if (owner.IsFunction()) {
cls = Function::Cast(owner).Owner();
name = cls.ScrubbedName();
lib = cls.library();
url = lib.url();
js.PrintPropertyStr("l", url);
js.PrintPropertyStr("c", name);
}
js.PrintProperty("n", data.code_->QualifiedName());
js.PrintProperty("s", SizeInSnapshot(data.insns_->raw()));
js.CloseObject();
}
js.CloseArray();
auto file_open = Dart::file_open_callback();
auto file_write = Dart::file_write_callback();
auto file_close = Dart::file_close_callback();
if ((file_open == nullptr) || (file_write == nullptr) ||
(file_close == nullptr)) {
return;
}
auto file = file_open(FLAG_print_instructions_sizes_to, /*write=*/true);
if (file == nullptr) {
OS::PrintErr("Failed to open file %s\n", FLAG_print_instructions_sizes_to);
return;
}
char* output = nullptr;
intptr_t output_length = 0;
js.Steal(&output, &output_length);
file_write(output, output_length, file);
free(output);
file_close(file);
}
void ImageWriter::DumpStatistics() {
if (FLAG_print_instruction_stats) {
DumpInstructionStats();
}
if (FLAG_print_instructions_sizes_to != nullptr) {
DumpInstructionsSizes();
}
}
#endif
void ImageWriter::Write(WriteStream* clustered_stream, bool vm) {
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
Heap* heap = thread->isolate()->heap();
TIMELINE_DURATION(thread, Isolate, "WriteInstructions");
// Handlify collected raw pointers as building the names below
// will allocate on the Dart heap.
for (intptr_t i = 0; i < instructions_.length(); i++) {
InstructionsData& data = instructions_[i];
const bool is_trampoline = data.trampoline_bytes != nullptr;
if (is_trampoline) continue;
data.insns_ = &Instructions::Handle(zone, data.raw_insns_);
ASSERT(data.raw_code_ != NULL);
data.code_ = &Code::Handle(zone, data.raw_code_);
// Reset object id as an isolate snapshot after a VM snapshot will not use
// the VM snapshot's text image.
heap->SetObjectId(data.insns_->raw(), 0);
}
for (intptr_t i = 0; i < objects_.length(); i++) {
ObjectData& data = objects_[i];
data.obj_ = &Object::Handle(zone, data.raw_obj_);
}
// Append the direct-mapped RO data objects after the clustered snapshot.
offset_space_ = vm ? V8SnapshotProfileWriter::kVmData
: V8SnapshotProfileWriter::kIsolateData;
WriteROData(clustered_stream);
offset_space_ = vm ? V8SnapshotProfileWriter::kVmText
: V8SnapshotProfileWriter::kIsolateText;
WriteText(clustered_stream, vm);
}
void ImageWriter::WriteROData(WriteStream* stream) {
stream->Align(OS::kMaxPreferredCodeAlignment);
// Heap page starts here.
intptr_t section_start = stream->Position();
stream->WriteWord(next_data_offset_); // Data length.
COMPILE_ASSERT(OS::kMaxPreferredCodeAlignment >= kObjectAlignment);
stream->Align(OS::kMaxPreferredCodeAlignment);
ASSERT(stream->Position() - section_start == Image::kHeaderSize);
// Heap page objects start here.
for (intptr_t i = 0; i < objects_.length(); i++) {
const Object& obj = *objects_[i].obj_;
AutoTraceImage(obj, section_start, stream);
NoSafepointScope no_safepoint;
uword start = reinterpret_cast<uword>(obj.raw()) - kHeapObjectTag;
uword end = start + obj.raw()->HeapSize();
// Write object header with the mark and read-only bits set.
uword marked_tags = obj.raw()->ptr()->tags_;
marked_tags = RawObject::OldBit::update(true, marked_tags);
marked_tags = RawObject::OldAndNotMarkedBit::update(false, marked_tags);
marked_tags = RawObject::OldAndNotRememberedBit::update(true, marked_tags);
marked_tags = RawObject::NewBit::update(false, marked_tags);
#if defined(HASH_IN_OBJECT_HEADER)
marked_tags |= static_cast<uword>(obj.raw()->ptr()->hash_) << 32;
#endif
stream->WriteWord(marked_tags);
start += sizeof(uword);
for (uword* cursor = reinterpret_cast<uword*>(start);
cursor < reinterpret_cast<uword*>(end); cursor++) {
stream->WriteWord(*cursor);
}
}
}
AssemblyImageWriter::AssemblyImageWriter(Thread* thread,
Dart_StreamingWriteCallback callback,
void* callback_data,
const void* shared_objects,
const void* shared_instructions)
: ImageWriter(thread->heap(), shared_objects, shared_instructions, nullptr),
assembly_stream_(512 * KB, callback, callback_data),
dwarf_(nullptr) {
#if defined(DART_PRECOMPILER)
Zone* zone = Thread::Current()->zone();
dwarf_ = new (zone) Dwarf(zone, &assembly_stream_, /* elf= */ nullptr);
#endif
}
void AssemblyImageWriter::Finalize() {
#ifdef DART_PRECOMPILER
dwarf_->Write();
#endif
}
static void EnsureAssemblerIdentifier(char* label) {
for (char c = *label; c != '\0'; c = *++label) {
if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9'))) {
continue;
}
*label = '_';
}
}
const char* NameOfStubIsolateSpecificStub(ObjectStore* object_store,
const Code& code) {
if (code.raw() == object_store->build_method_extractor_code()) {
return "_iso_stub_BuildMethodExtractorStub";
} else if (code.raw() == object_store->null_error_stub_with_fpu_regs_stub()) {
return "_iso_stub_NullErrorSharedWithFPURegsStub";
} else if (code.raw() ==
object_store->null_error_stub_without_fpu_regs_stub()) {
return "_iso_stub_NullErrorSharedWithoutFPURegsStub";
} else if (code.raw() ==
object_store->stack_overflow_stub_with_fpu_regs_stub()) {
return "_iso_stub_StackOverflowStubWithFPURegsStub";
} else if (code.raw() ==
object_store->stack_overflow_stub_without_fpu_regs_stub()) {
return "_iso_stub_StackOverflowStubWithoutFPURegsStub";
} else if (code.raw() == object_store->write_barrier_wrappers_stub()) {
return "_iso_stub_WriteBarrierWrappersStub";
} else if (code.raw() == object_store->array_write_barrier_stub()) {
return "_iso_stub_ArrayWriteBarrierStub";
}
return nullptr;
}
void AssemblyImageWriter::WriteText(WriteStream* clustered_stream, bool vm) {
Zone* zone = Thread::Current()->zone();
const char* instructions_symbol =
vm ? "_kDartVmSnapshotInstructions" : "_kDartIsolateSnapshotInstructions";
assembly_stream_.Print(".text\n");
assembly_stream_.Print(".globl %s\n", instructions_symbol);
// Start snapshot at page boundary.
ASSERT(VirtualMemory::PageSize() >= OS::kMaxPreferredCodeAlignment);
assembly_stream_.Print(".balign %" Pd ", 0\n", VirtualMemory::PageSize());
assembly_stream_.Print("%s:\n", instructions_symbol);
// This head also provides the gap to make the instructions snapshot
// look like a HeapPage.
intptr_t instructions_length = next_text_offset_;
WriteWordLiteralText(instructions_length);
intptr_t header_words = Image::kHeaderSize / sizeof(uword);
for (intptr_t i = 1; i < header_words; i++) {
WriteWordLiteralText(0);
}
FrameUnwindPrologue();
Object& owner = Object::Handle(zone);
String& str = String::Handle(zone);
ObjectStore* object_store = Isolate::Current()->object_store();
TypeTestingStubNamer tts;
intptr_t text_offset = 0;
ASSERT(offset_space_ != V8SnapshotProfileWriter::kSnapshot);
for (intptr_t i = 0; i < instructions_.length(); i++) {
auto& data = instructions_[i];
const bool is_trampoline = data.trampoline_bytes != nullptr;
ASSERT((data.text_offset_ - instructions_[0].text_offset_) == text_offset);
if (is_trampoline) {
if (profile_writer_ != nullptr) {
const intptr_t offset = Image::kHeaderSize + text_offset;
profile_writer_->SetObjectTypeAndName({offset_space_, offset},
"Trampolines",
/*name=*/nullptr);
profile_writer_->AttributeBytesTo({offset_space_, offset},
data.trampline_length);
}
const auto start = reinterpret_cast<uword>(data.trampoline_bytes);
const auto end = start + data.trampline_length;
text_offset += WriteByteSequence(start, end);
delete[] data.trampoline_bytes;
data.trampoline_bytes = nullptr;
continue;
}
const intptr_t instr_start = text_offset;
const Instructions& insns = *data.insns_;
const Code& code = *data.code_;
if (profile_writer_ != nullptr) {
const intptr_t offset = Image::kHeaderSize + text_offset;
profile_writer_->SetObjectTypeAndName({offset_space_, offset},
"Instructions",
/*name=*/nullptr);
profile_writer_->AttributeBytesTo({offset_space_, offset},
SizeInSnapshot(insns.raw()));
}
ASSERT(insns.raw()->HeapSize() % sizeof(uint64_t) == 0);
// 1. Write from the header to the entry point.
{
NoSafepointScope no_safepoint;
uword beginning = reinterpret_cast<uword>(insns.raw_ptr());
uword entry = beginning + Instructions::HeaderSize();
// Write Instructions with the mark and read-only bits set.
uword marked_tags = insns.raw_ptr()->tags_;
marked_tags = RawObject::OldBit::update(true, marked_tags);
marked_tags = RawObject::OldAndNotMarkedBit::update(false, marked_tags);
marked_tags =
RawObject::OldAndNotRememberedBit::update(true, marked_tags);
marked_tags = RawObject::NewBit::update(false, marked_tags);
#if defined(HASH_IN_OBJECT_HEADER)
// Can't use GetObjectTagsAndHash because the update methods discard the
// high bits.
marked_tags |= static_cast<uword>(insns.raw_ptr()->hash_) << 32;
#endif
WriteWordLiteralText(marked_tags);
beginning += sizeof(uword);
text_offset += sizeof(uword);
text_offset += WriteByteSequence(beginning, entry);
ASSERT((text_offset - instr_start) == insns.HeaderSize());
}
// 2. Write a label at the entry point.
// Linux's perf uses these labels.
ASSERT(!code.IsNull());
owner = code.owner();
if (owner.IsNull()) {
const char* name = StubCode::NameOfStub(insns.EntryPoint());
if (name != nullptr) {
assembly_stream_.Print("Precompiled_Stub_%s:\n", name);
} else {
if (name == nullptr) {
name = NameOfStubIsolateSpecificStub(object_store, code);
}
ASSERT(name != nullptr);
assembly_stream_.Print("Precompiled__%s:\n", name);
}
} else if (owner.IsClass()) {
str = Class::Cast(owner).Name();
const char* name = str.ToCString();
EnsureAssemblerIdentifier(const_cast<char*>(name));
assembly_stream_.Print("Precompiled_AllocationStub_%s_%" Pd ":\n", name,
i);
} else if (owner.IsAbstractType()) {
const char* name = tts.StubNameForType(AbstractType::Cast(owner));
assembly_stream_.Print("Precompiled_%s:\n", name);
} else if (owner.IsFunction()) {
const char* name = Function::Cast(owner).ToQualifiedCString();
EnsureAssemblerIdentifier(const_cast<char*>(name));
assembly_stream_.Print("Precompiled_%s_%" Pd ":\n", name, i);
} else {
UNREACHABLE();
}
#ifdef DART_PRECOMPILER
// Create a label for use by DWARF.
if ((dwarf_ != nullptr) && !code.IsNull()) {
const intptr_t dwarf_index = dwarf_->AddCode(code);
assembly_stream_.Print(".Lcode%" Pd ":\n", dwarf_index);
}
#endif
{
// 3. Write from the entry point to the end.
NoSafepointScope no_safepoint;
uword beginning = reinterpret_cast<uword>(insns.raw_ptr());
uword entry = beginning + Instructions::HeaderSize();
uword payload_size = insns.raw()->HeapSize() - insns.HeaderSize();
uword end = entry + payload_size;
ASSERT(Utils::IsAligned(beginning, sizeof(uword)));
ASSERT(Utils::IsAligned(entry, sizeof(uword)));
ASSERT(Utils::IsAligned(end, sizeof(uword)));
text_offset += WriteByteSequence(entry, end);
}
ASSERT((text_offset - instr_start) == insns.raw()->HeapSize());
}
FrameUnwindEpilogue();
#if defined(TARGET_OS_LINUX) || defined(TARGET_OS_ANDROID) || \
defined(TARGET_OS_FUCHSIA)
assembly_stream_.Print(".section .rodata\n");
#elif defined(TARGET_OS_MACOS) || defined(TARGET_OS_MACOS_IOS)
assembly_stream_.Print(".const\n");
#else
UNIMPLEMENTED();
#endif
const char* data_symbol =
vm ? "_kDartVmSnapshotData" : "_kDartIsolateSnapshotData";
assembly_stream_.Print(".globl %s\n", data_symbol);
assembly_stream_.Print(".balign %" Pd ", 0\n",
OS::kMaxPreferredCodeAlignment);
assembly_stream_.Print("%s:\n", data_symbol);
uword buffer = reinterpret_cast<uword>(clustered_stream->buffer());
intptr_t length = clustered_stream->bytes_written();
WriteByteSequence(buffer, buffer + length);
}
void AssemblyImageWriter::FrameUnwindPrologue() {
// Creates DWARF's .debug_frame
// CFI = Call frame information
// CFA = Canonical frame address
assembly_stream_.Print(".cfi_startproc\n");
#if defined(TARGET_ARCH_X64)
assembly_stream_.Print(".cfi_def_cfa rbp, 0\n"); // CFA is fp+0
assembly_stream_.Print(".cfi_offset rbp, 0\n"); // saved fp is *(CFA+0)
assembly_stream_.Print(".cfi_offset rip, 8\n"); // saved pc is *(CFA+8)
// saved sp is CFA+16
// Should be ".cfi_value_offset rsp, 16", but requires gcc newer than late
// 2016 and not supported by Android's libunwind.
// DW_CFA_expression 0x10
// uleb128 register (rsp) 7 (DWARF register number)
// uleb128 size of operation 2
// DW_OP_plus_uconst 0x23
// uleb128 addend 16
assembly_stream_.Print(".cfi_escape 0x10, 31, 2, 0x23, 16\n");
#elif defined(TARGET_ARCH_ARM64)
COMPILE_ASSERT(FP == R29);
COMPILE_ASSERT(LR == R30);
assembly_stream_.Print(".cfi_def_cfa x29, 0\n"); // CFA is fp+0
assembly_stream_.Print(".cfi_offset x29, 0\n"); // saved fp is *(CFA+0)
assembly_stream_.Print(".cfi_offset x30, 8\n"); // saved pc is *(CFA+8)
// saved sp is CFA+16
// Should be ".cfi_value_offset sp, 16", but requires gcc newer than late
// 2016 and not supported by Android's libunwind.
// DW_CFA_expression 0x10
// uleb128 register (x31) 31
// uleb128 size of operation 2
// DW_OP_plus_uconst 0x23
// uleb128 addend 16
assembly_stream_.Print(".cfi_escape 0x10, 31, 2, 0x23, 16\n");
#elif defined(TARGET_ARCH_ARM)
#if defined(TARGET_OS_MACOS) || defined(TARGET_OS_MACOS_IOS)
COMPILE_ASSERT(FP == R7);
assembly_stream_.Print(".cfi_def_cfa r7, 0\n"); // CFA is fp+j0
assembly_stream_.Print(".cfi_offset r7, 0\n"); // saved fp is *(CFA+0)
#else
COMPILE_ASSERT(FP == R11);
assembly_stream_.Print(".cfi_def_cfa r11, 0\n"); // CFA is fp+0
assembly_stream_.Print(".cfi_offset r11, 0\n"); // saved fp is *(CFA+0)
#endif
assembly_stream_.Print(".cfi_offset lr, 4\n"); // saved pc is *(CFA+4)
// saved sp is CFA+8
// Should be ".cfi_value_offset sp, 8", but requires gcc newer than late
// 2016 and not supported by Android's libunwind.
// DW_CFA_expression 0x10
// uleb128 register (sp) 13
// uleb128 size of operation 2
// DW_OP_plus_uconst 0x23
// uleb128 addend 8
assembly_stream_.Print(".cfi_escape 0x10, 13, 2, 0x23, 8\n");
// libunwind on ARM may use .ARM.exidx instead of .debug_frame
#if !defined(TARGET_OS_MACOS) && !defined(TARGET_OS_MACOS_IOS)
COMPILE_ASSERT(FP == R11);
assembly_stream_.Print(".fnstart\n");
assembly_stream_.Print(".save {r11, lr}\n");
assembly_stream_.Print(".setfp r11, sp, #0\n");
#endif
#endif
}
void AssemblyImageWriter::FrameUnwindEpilogue() {
#if defined(TARGET_ARCH_ARM)
#if !defined(TARGET_OS_MACOS) && !defined(TARGET_OS_MACOS_IOS)
assembly_stream_.Print(".fnend\n");
#endif
#endif
assembly_stream_.Print(".cfi_endproc\n");
}
intptr_t AssemblyImageWriter::WriteByteSequence(uword start, uword end) {
for (uword* cursor = reinterpret_cast<uword*>(start);
cursor < reinterpret_cast<uword*>(end); cursor++) {
WriteWordLiteralText(*cursor);
}
return end - start;
}
BlobImageWriter::BlobImageWriter(Thread* thread,
uint8_t** instructions_blob_buffer,
ReAlloc alloc,
intptr_t initial_size,
const void* shared_objects,
const void* shared_instructions,
const void* reused_instructions,
Elf* elf,
Dwarf* dwarf)
: ImageWriter(thread->heap(),
shared_objects,
shared_instructions,
reused_instructions),
instructions_blob_stream_(instructions_blob_buffer, alloc, initial_size),
elf_(elf),
dwarf_(dwarf) {
#ifndef DART_PRECOMPILER
RELEASE_ASSERT(elf_ == nullptr);
RELEASE_ASSERT(dwarf_ == nullptr);
#endif
}
intptr_t BlobImageWriter::WriteByteSequence(uword start, uword end) {
for (uword* cursor = reinterpret_cast<uword*>(start);
cursor < reinterpret_cast<uword*>(end); cursor++) {
instructions_blob_stream_.WriteWord(*cursor);
}
return end - start;
}
void BlobImageWriter::WriteText(WriteStream* clustered_stream, bool vm) {
#ifdef DART_PRECOMPILER
intptr_t segment_base = 0;
if (elf_ != nullptr) {
segment_base = elf_->NextMemoryOffset();
}
#endif
// This header provides the gap to make the instructions snapshot look like a
// HeapPage.
intptr_t instructions_length = next_text_offset_;
instructions_blob_stream_.WriteWord(instructions_length);
intptr_t header_words = Image::kHeaderSize / sizeof(uword);
for (intptr_t i = 1; i < header_words; i++) {
instructions_blob_stream_.WriteWord(0);
}
intptr_t text_offset = 0;
NoSafepointScope no_safepoint;
for (intptr_t i = 0; i < instructions_.length(); i++) {
auto& data = instructions_[i];
const bool is_trampoline = data.trampoline_bytes != nullptr;
ASSERT((data.text_offset_ - instructions_[0].text_offset_) == text_offset);
if (is_trampoline) {
const auto start = reinterpret_cast<uword>(data.trampoline_bytes);
const auto end = start + data.trampline_length;
text_offset += WriteByteSequence(start, end);
delete[] data.trampoline_bytes;
data.trampoline_bytes = nullptr;
continue;
}
const intptr_t instr_start = text_offset;
const Instructions& insns = *instructions_[i].insns_;
AutoTraceImage(insns, 0, &this->instructions_blob_stream_);
uword beginning = reinterpret_cast<uword>(insns.raw_ptr());
uword entry = beginning + Instructions::HeaderSize();
uword payload_size = insns.Size();
payload_size = Utils::RoundUp(payload_size, OS::PreferredCodeAlignment());
uword end = entry + payload_size;
ASSERT(Utils::IsAligned(beginning, sizeof(uword)));
ASSERT(Utils::IsAligned(entry, sizeof(uword)));
#ifdef DART_PRECOMPILER
const Code& code = *instructions_[i].code_;
if ((elf_ != nullptr) && (dwarf_ != nullptr) && !code.IsNull()) {
intptr_t segment_offset = instructions_blob_stream_.bytes_written() +
Instructions::HeaderSize();
dwarf_->AddCode(code, segment_base + segment_offset);
}
#endif
// Write Instructions with the mark and read-only bits set.
uword marked_tags = insns.raw_ptr()->tags_;
marked_tags = RawObject::OldBit::update(true, marked_tags);
marked_tags = RawObject::OldAndNotMarkedBit::update(false, marked_tags);
marked_tags = RawObject::OldAndNotRememberedBit::update(true, marked_tags);
marked_tags = RawObject::NewBit::update(false, marked_tags);
#if defined(HASH_IN_OBJECT_HEADER)
// Can't use GetObjectTagsAndHash because the update methods discard the
// high bits.
marked_tags |= static_cast<uword>(insns.raw_ptr()->hash_) << 32;
#endif
instructions_blob_stream_.WriteWord(marked_tags);
text_offset += sizeof(uword);
beginning += sizeof(uword);
text_offset += WriteByteSequence(beginning, end);
ASSERT((text_offset - instr_start) ==
ImageWriter::SizeInSnapshot(insns.raw()));
}
#ifdef DART_PRECOMPILER
if (elf_ != nullptr) {
const char* instructions_symbol = vm ? "_kDartVmSnapshotInstructions"
: "_kDartIsolateSnapshotInstructions";
intptr_t segment_base2 =
elf_->AddText(instructions_symbol, instructions_blob_stream_.buffer(),
instructions_blob_stream_.bytes_written());
ASSERT(segment_base == segment_base2);
}
#endif
}
ImageReader::ImageReader(const uint8_t* data_image,
const uint8_t* instructions_image,
const uint8_t* shared_data_image,
const uint8_t* shared_instructions_image)
: data_image_(data_image),
instructions_image_(instructions_image),
shared_data_image_(shared_data_image),
shared_instructions_image_(shared_instructions_image) {
ASSERT(data_image != NULL);
ASSERT(instructions_image != NULL);
}
RawApiError* ImageReader::VerifyAlignment() const {
if (!Utils::IsAligned(data_image_, kObjectAlignment) ||
!Utils::IsAligned(shared_data_image_, kObjectAlignment) ||
!Utils::IsAligned(instructions_image_, OS::PreferredCodeAlignment()) ||
!Utils::IsAligned(shared_instructions_image_,
OS::PreferredCodeAlignment())) {
return ApiError::New(
String::Handle(String::New("Snapshot is misaligned", Heap::kOld)),
Heap::kOld);
}
return ApiError::null();
}
RawInstructions* ImageReader::GetInstructionsAt(int32_t offset) const {
ASSERT(Utils::IsAligned(offset, OS::PreferredCodeAlignment()));
RawObject* result;
if (offset < 0) {
result = RawObject::FromAddr(
reinterpret_cast<uword>(shared_instructions_image_) - offset);
} else {
result = RawObject::FromAddr(reinterpret_cast<uword>(instructions_image_) +
offset);
}
ASSERT(result->IsInstructions());
ASSERT(result->IsMarked());
return Instructions::RawCast(result);
}
RawObject* ImageReader::GetObjectAt(uint32_t offset) const {
ASSERT(Utils::IsAligned(offset, kObjectAlignment));
RawObject* result =
RawObject::FromAddr(reinterpret_cast<uword>(data_image_) + offset);
ASSERT(result->IsMarked());
return result;
}
RawObject* ImageReader::GetSharedObjectAt(uint32_t offset) const {
ASSERT(Utils::IsAligned(offset, kObjectAlignment));
RawObject* result =
RawObject::FromAddr(reinterpret_cast<uword>(shared_data_image_) + offset);
ASSERT(result->IsMarked());
return result;
}
void DropCodeWithoutReusableInstructions(const void* reused_instructions) {
class DropCodeVisitor : public FunctionVisitor, public ClassVisitor {
public:
explicit DropCodeVisitor(const void* reused_instructions)
: code_(Code::Handle()),
instructions_(Instructions::Handle()),
pool_(ObjectPool::Handle()),
table_(Array::Handle()),
entry_(Object::Handle()) {
ImageWriter::SetupShared(&reused_instructions_, reused_instructions);
if (FLAG_trace_reused_instructions) {
OS::PrintErr("%" Pd " reusable instructions\n",
reused_instructions_.Size());
}
}
void Visit(const Class& cls) {
code_ = cls.allocation_stub();
if (!code_.IsNull()) {
if (!CanKeep(code_)) {
if (FLAG_trace_reused_instructions) {
OS::PrintErr("No reusable instructions for %s\n", cls.ToCString());
}
cls.DisableAllocationStub();
}
}
}
void Visit(const Function& func) {
if (func.HasCode()) {
code_ = func.CurrentCode();
if (!CanKeep(code_)) {
if (FLAG_trace_reused_instructions) {
OS::PrintErr("No reusable instructions for %s\n", func.ToCString());
}
func.ClearCode();
func.ClearICDataArray();
return;
}
}
code_ = func.unoptimized_code();
if (!code_.IsNull() && !CanKeep(code_)) {
if (FLAG_trace_reused_instructions) {
OS::PrintErr("No reusable instructions for %s\n", func.ToCString());
}
func.ClearCode();
func.ClearICDataArray();
}
}
bool CanKeep(const Code& code) {
if (!IsAvailable(code)) {
return false;
}
pool_ = code.object_pool();
for (intptr_t i = 0; i < pool_.Length(); i++) {
if (pool_.TypeAt(i) == ObjectPool::EntryType::kTaggedObject) {
entry_ = pool_.ObjectAt(i);
if (entry_.IsCode() && !IsAvailable(Code::Cast(entry_))) {
return false;
}
}
}
table_ = code.static_calls_target_table();
if (!table_.IsNull()) {
StaticCallsTable static_calls(table_);
for (auto& view : static_calls) {
entry_ = view.Get<Code::kSCallTableCodeTarget>();
if (entry_.IsCode() && !IsAvailable(Code::Cast(entry_))) {
return false;
}
}
}
return true;
}
private:
bool IsAvailable(const Code& code) {
ObjectOffsetPair* pair = reused_instructions_.Lookup(code.instructions());
return pair != NULL;
}
ObjectOffsetMap reused_instructions_;
Code& code_;
Instructions& instructions_;
ObjectPool& pool_;
Array& table_;
Object& entry_;
DISALLOW_COPY_AND_ASSIGN(DropCodeVisitor);
};
DropCodeVisitor visitor(reused_instructions);
ProgramVisitor::VisitClasses(&visitor);
ProgramVisitor::VisitFunctions(&visitor);
}
} // namespace dart