-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathbytecode_reader.cc
2489 lines (2167 loc) · 87.6 KB
/
bytecode_reader.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) 2024, 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/bytecode_reader.h"
#include "vm/globals.h"
#if defined(DART_DYNAMIC_MODULES)
#include "vm/bit_vector.h"
#include "vm/bootstrap.h"
#include "vm/class_finalizer.h"
#include "vm/class_id.h"
#include "vm/closure_functions_cache.h"
#include "vm/code_descriptors.h"
#include "vm/compiler/api/deopt_id.h"
#include "vm/compiler/assembler/disassembler_kbc.h"
#include "vm/constants_kbc.h"
#include "vm/dart_entry.h"
#include "vm/flags.h"
#include "vm/hash.h"
#include "vm/hash_table.h"
#include "vm/longjump.h"
#include "vm/object_store.h"
#include "vm/resolver.h"
#include "vm/reusable_handles.h"
#include "vm/stack_frame_kbc.h"
#include "vm/symbols.h"
#include "vm/timeline.h"
#define Z (zone_)
#define IG (thread_->isolate_group())
namespace dart {
DEFINE_FLAG(bool, dump_kernel_bytecode, false, "Dump kernel bytecode");
namespace bytecode {
class BytecodeOffsetsMapTraits {
public:
static const char* Name() { return "BytecodeOffsetsMapTraits"; }
static bool ReportStats() { return false; }
static bool IsMatch(const Object& a, const Object& b) {
return (a.ptr() == b.ptr());
}
static uword Hash(const Object& key) {
if (key.IsClass()) {
return Class::Cast(key).id();
} else if (key.IsFunction()) {
return Function::Cast(key).Hash();
} else if (key.IsField()) {
return Field::Cast(key).Hash();
} else {
UNREACHABLE();
}
}
};
using BytecodeOffsetsMap = UnorderedHashMap<BytecodeOffsetsMapTraits>;
BytecodeLoader::BytecodeLoader(Thread* thread, const TypedDataBase& binary)
: thread_(thread),
binary_(binary),
bytecode_component_array_(Array::Handle(thread->zone())),
bytecode_offsets_map_(
Array::Handle(thread->zone(),
HashTables::New<BytecodeOffsetsMap>(16))) {
ASSERT(thread_ == Thread::Current());
ASSERT(thread_->bytecode_loader() == nullptr);
thread_->set_bytecode_loader(this);
ASSERT(!binary_.IsNull());
ASSERT(binary_.IsExternalOrExternalView());
}
BytecodeLoader::~BytecodeLoader() {
ASSERT(thread_->bytecode_loader() == this);
thread_->set_bytecode_loader(nullptr);
}
FunctionPtr BytecodeLoader::LoadBytecode() {
ASSERT(IsolateGroup::Current()->program_lock()->IsCurrentThreadWriter());
BytecodeReaderHelper component_reader(thread_, binary_);
bytecode_component_array_ = component_reader.ReadBytecodeComponent();
BytecodeComponentData bytecode_component(bytecode_component_array_);
BytecodeReaderHelper bytecode_reader(thread_, &bytecode_component);
AlternativeReadingScope alt(&bytecode_reader.reader(),
bytecode_component.GetLibraryIndexOffset());
bytecode_reader.ReadLibraryDeclarations(bytecode_component.GetNumLibraries());
if (bytecode_component.GetMainOffset() == 0) {
return Function::null();
}
AlternativeReadingScope alt2(&bytecode_reader.reader(),
bytecode_component.GetMainOffset());
return Function::RawCast(bytecode_reader.ReadObject());
}
void BytecodeLoader::SetOffset(const Object& obj, intptr_t offset) {
BytecodeOffsetsMap map(bytecode_offsets_map_.ptr());
map.UpdateOrInsert(obj, Smi::Handle(thread_->zone(), Smi::New(offset)));
bytecode_offsets_map_ = map.Release().ptr();
}
intptr_t BytecodeLoader::GetOffset(const Object& obj) {
BytecodeOffsetsMap map(bytecode_offsets_map_.ptr());
const auto value = map.GetOrNull(obj);
ASSERT(value != Object::null());
const intptr_t offset = Smi::Value(Smi::RawCast(value));
ASSERT(map.Release().ptr() == bytecode_offsets_map_.ptr());
return offset;
}
BytecodeReaderHelper::BytecodeReaderHelper(Thread* thread,
const TypedDataBase& typed_data)
: reader_(typed_data),
thread_(thread),
zone_(thread->zone()),
bytecode_component_(nullptr),
scoped_function_(Function::Handle(thread->zone())),
scoped_function_name_(String::Handle(thread->zone())),
scoped_function_class_(Class::Handle(thread->zone())) {}
BytecodeReaderHelper::BytecodeReaderHelper(
Thread* thread,
BytecodeComponentData* bytecode_component)
: reader_(TypedDataBase::Handle(thread->zone(),
bytecode_component->GetTypedData())),
thread_(thread),
zone_(thread->zone()),
bytecode_component_(bytecode_component),
scoped_function_(Function::Handle(thread->zone())),
scoped_function_name_(String::Handle(thread->zone())),
scoped_function_class_(Class::Handle(thread->zone())) {}
void BytecodeReaderHelper::ReadCode(const Function& function,
intptr_t code_offset) {
ASSERT(IsolateGroup::Current()->program_lock()->IsCurrentThreadWriter());
ASSERT(!function.IsImplicitGetterFunction() &&
!function.IsImplicitSetterFunction());
if (code_offset == 0) {
FATAL("Function %s (kind %s) doesn't have bytecode",
function.ToFullyQualifiedCString(),
Function::KindToCString(function.kind()));
}
AlternativeReadingScope alt(&reader_, code_offset);
const auto& signature = FunctionType::Handle(Z, function.signature());
FunctionTypeScope function_type_scope(this, signature);
const intptr_t flags = reader_.ReadUInt();
const bool has_exceptions_table =
(flags & Code::kHasExceptionsTableFlag) != 0;
const bool has_source_positions =
(flags & Code::kHasSourcePositionsFlag) != 0;
const bool has_local_variables = (flags & Code::kHasLocalVariablesFlag) != 0;
const bool has_nullable_fields = (flags & Code::kHasNullableFieldsFlag) != 0;
const bool has_closures = (flags & Code::kHasClosuresFlag) != 0;
const bool has_parameter_flags = (flags & Code::kHasParameterFlagsFlag) != 0;
const bool has_forwarding_stub_target =
(flags & Code::kHasForwardingStubTargetFlag) != 0;
const bool has_default_function_type_args =
(flags & Code::kHasDefaultFunctionTypeArgsFlag) != 0;
if (has_parameter_flags) {
intptr_t num_flags = reader_.ReadUInt();
for (intptr_t i = 0; i < num_flags; ++i) {
reader_.ReadUInt();
}
}
if (has_forwarding_stub_target) {
reader_.ReadUInt();
}
if (has_default_function_type_args) {
reader_.ReadUInt();
}
intptr_t num_closures = 0;
if (has_closures) {
num_closures = reader_.ReadListLength();
closures_ = &Array::Handle(Z, Array::New(num_closures));
for (intptr_t i = 0; i < num_closures; i++) {
ReadClosureDeclaration(function, i);
}
}
// Create object pool and read pool entries.
const intptr_t obj_count = reader_.ReadListLength();
const ObjectPool& pool = ObjectPool::Handle(Z, ObjectPool::New(obj_count));
ReadConstantPool(function, pool, 0);
// Read bytecode and attach to function.
const Bytecode& bytecode = Bytecode::Handle(Z, ReadBytecode(pool));
bytecode.set_code_offset(code_offset);
function.AttachBytecode(bytecode);
ReadExceptionsTable(function, bytecode, has_exceptions_table);
ReadSourcePositions(bytecode, has_source_positions);
ReadLocalVariables(bytecode, has_local_variables);
if (FLAG_dump_kernel_bytecode) {
KernelBytecodeDisassembler::Disassemble(function);
}
// Initialization of fields with null literal is elided from bytecode.
// Record the corresponding stores if field guards are enabled.
if (has_nullable_fields) {
ASSERT(function.IsGenerativeConstructor());
const intptr_t num_fields = reader_.ReadListLength();
if (IG->use_field_guards()) {
Field& field = Field::Handle(Z);
for (intptr_t i = 0; i < num_fields; i++) {
field ^= ReadObject();
field.RecordStore(Object::null_object());
}
} else {
for (intptr_t i = 0; i < num_fields; i++) {
ReadObject();
}
}
}
// Read closures.
if (has_closures) {
Function& closure = Function::Handle(Z);
Bytecode& closure_bytecode = Bytecode::Handle(Z);
for (intptr_t i = 0; i < num_closures; i++) {
closure ^= closures_->At(i);
const intptr_t flags = reader_.ReadUInt();
const bool has_exceptions_table =
(flags & ClosureCode::kHasExceptionsTableFlag) != 0;
const bool has_source_positions =
(flags & ClosureCode::kHasSourcePositionsFlag) != 0;
const bool has_local_variables =
(flags & ClosureCode::kHasLocalVariablesFlag) != 0;
// Read closure bytecode and attach to closure function.
closure_bytecode = ReadBytecode(pool);
closure.AttachBytecode(closure_bytecode);
ReadExceptionsTable(closure, closure_bytecode, has_exceptions_table);
ReadSourcePositions(closure_bytecode, has_source_positions);
ReadLocalVariables(closure_bytecode, has_local_variables);
if (FLAG_dump_kernel_bytecode) {
KernelBytecodeDisassembler::Disassemble(closure);
}
}
}
}
void BytecodeReaderHelper::ReadClosureDeclaration(const Function& function,
intptr_t closureIndex) {
// Closure flags, must be in sync with ClosureDeclaration constants in
// pkg/dart2bytecode/lib/declarations.dart.
const int kHasOptionalPositionalParamsFlag = 1 << 0;
const int kHasOptionalNamedParamsFlag = 1 << 1;
const int kHasTypeParamsFlag = 1 << 2;
const int kHasSourcePositionsFlag = 1 << 3;
const int kIsAsyncFlag = 1 << 4;
const int kIsAsyncStarFlag = 1 << 5;
const int kIsSyncStarFlag = 1 << 6;
const int kIsDebuggableFlag = 1 << 7;
const int kHasParameterFlagsFlag = 1 << 8;
const intptr_t flags = reader_.ReadUInt();
Object& parent = Object::Handle(Z, ReadObject());
if (!parent.IsFunction()) {
ASSERT(parent.IsField());
ASSERT(function.kind() == UntaggedFunction::kFieldInitializer);
// Closure in a static field initializer, so use current function as parent.
parent = function.ptr();
}
String& name = String::CheckedHandle(Z, ReadObject());
ASSERT(name.IsSymbol());
TokenPosition position = TokenPosition::kNoSource;
TokenPosition end_position = TokenPosition::kNoSource;
if ((flags & kHasSourcePositionsFlag) != 0) {
position = reader_.ReadPosition();
end_position = reader_.ReadPosition();
}
const Function& closure = Function::Handle(
Z, Function::NewClosureFunction(name, Function::Cast(parent), position));
NOT_IN_PRECOMPILED(closure.set_end_token_pos(end_position));
if ((flags & kIsSyncStarFlag) != 0) {
closure.set_modifier(UntaggedFunction::kSyncGen);
closure.set_is_inlinable(false);
} else if ((flags & kIsAsyncFlag) != 0) {
closure.set_modifier(UntaggedFunction::kAsync);
closure.set_is_inlinable(false);
} else if ((flags & kIsAsyncStarFlag) != 0) {
closure.set_modifier(UntaggedFunction::kAsyncGen);
closure.set_is_inlinable(false);
}
closure.set_is_debuggable((flags & kIsDebuggableFlag) != 0);
closures_->SetAt(closureIndex, closure);
auto& signature = FunctionType::Handle(Z, closure.signature());
signature = ReadFunctionSignature(
signature, (flags & kHasOptionalPositionalParamsFlag) != 0,
(flags & kHasOptionalNamedParamsFlag) != 0,
(flags & kHasTypeParamsFlag) != 0,
/* has_positional_param_names = */ true,
(flags & kHasParameterFlagsFlag) != 0);
closure.SetSignature(signature);
}
FunctionTypePtr BytecodeReaderHelper::ReadFunctionSignature(
const FunctionType& signature,
bool has_optional_positional_params,
bool has_optional_named_params,
bool has_type_params,
bool has_positional_param_names,
bool has_parameter_flags) {
FunctionTypeScope function_type_scope(this, signature);
if (has_type_params) {
ReadTypeParametersDeclaration(Class::Handle(Z), signature);
}
const intptr_t kImplicitClosureParam = 1;
const intptr_t num_params = kImplicitClosureParam + reader_.ReadUInt();
intptr_t num_required_params = num_params;
if (has_optional_positional_params || has_optional_named_params) {
num_required_params = kImplicitClosureParam + reader_.ReadUInt();
}
signature.set_num_implicit_parameters(kImplicitClosureParam);
signature.set_num_fixed_parameters(num_required_params);
signature.SetNumOptionalParameters(num_params - num_required_params,
!has_optional_named_params);
signature.set_parameter_types(
Array::Handle(Z, Array::New(num_params, Heap::kOld)));
signature.CreateNameArrayIncludingFlags(Heap::kOld);
intptr_t i = 0;
signature.SetParameterTypeAt(i, AbstractType::dynamic_type());
++i;
AbstractType& type = AbstractType::Handle(Z);
String& name = String::Handle(Z);
for (; i < num_params; ++i) {
if (has_positional_param_names ||
(has_optional_named_params && (i >= num_required_params))) {
name ^= ReadObject();
if (has_optional_named_params && (i >= num_required_params)) {
signature.SetParameterNameAt(i, name);
}
}
type ^= ReadObject();
signature.SetParameterTypeAt(i, type);
}
if (has_parameter_flags) {
ASSERT(has_optional_named_params);
intptr_t num_flags = reader_.ReadUInt();
for (intptr_t i = 0; i < num_flags; ++i) {
intptr_t flag = reader_.ReadUInt();
if ((flag & Parameter::kIsRequiredFlag) != 0) {
signature.SetIsRequiredAt(num_required_params + i);
}
}
}
type ^= ReadObject();
signature.set_result_type(type);
// Finalize function type.
return FunctionType::RawCast(
ClassFinalizer::FinalizeType(signature, ClassFinalizer::kCanonicalize));
}
void BytecodeReaderHelper::ReadTypeParametersDeclaration(
const Class& parameterized_class,
const FunctionType& parameterized_signature) {
ASSERT(parameterized_class.IsNull() != parameterized_signature.IsNull());
const intptr_t num_type_params = reader_.ReadUInt();
ASSERT(num_type_params > 0);
// First setup the type parameters, so if any of the following code uses it
// (in a recursive way) we're fine.
//
// Step a) Create TypeParameters object (without bounds and defaults).
const TypeParameters& type_parameters =
TypeParameters::Handle(Z, TypeParameters::New(num_type_params));
if (!parameterized_class.IsNull()) {
ASSERT(parameterized_class.type_parameters() == TypeParameters::null());
parameterized_class.set_type_parameters(type_parameters);
} else {
ASSERT(parameterized_signature.type_parameters() == TypeParameters::null());
parameterized_signature.SetTypeParameters(type_parameters);
}
String& name = String::Handle(Z);
AbstractType& type = AbstractType::Handle(Z);
for (intptr_t i = 0; i < num_type_params; ++i) {
name ^= ReadObject();
ASSERT(name.IsSymbol());
type_parameters.SetNameAt(i, name);
// Set bound temporarily to dynamic in order to
// allow type finalization of type parameter types.
type_parameters.SetBoundAt(i, Object::dynamic_type());
}
// Step b) Fill in the bounds and defaults of all [TypeParameter]s.
for (intptr_t i = 0; i < num_type_params; ++i) {
type ^= ReadObject();
type_parameters.SetBoundAt(i, type);
type ^= ReadObject();
type_parameters.SetDefaultAt(i, type);
}
}
intptr_t BytecodeReaderHelper::ReadConstantPool(const Function& function,
const ObjectPool& pool,
intptr_t start_index) {
// These enums and the code below reading the constant pool from kernel must
// be kept in sync with pkg/dart2bytecode/lib/constant_pool.dart.
enum ConstantPoolTag {
kInvalid,
kObjectRef,
kClass,
kType,
kStaticField,
kInstanceField,
kTypeArgumentsField,
kClosureFunction,
kEndClosureFunctionScope,
kSubtypeTestCache,
kEmptyTypeArguments,
kDirectCall,
kInterfaceCall,
kInstantiatedInterfaceCall,
kDynamicCall,
};
Object& obj = Object::Handle(Z);
Object& elem = Object::Handle(Z);
Field& field = Field::Handle(Z);
Class& cls = Class::Handle(Z);
String& name = String::Handle(Z);
const intptr_t obj_count = pool.Length();
for (intptr_t i = start_index; i < obj_count; ++i) {
const intptr_t tag = reader_.ReadByte();
switch (tag) {
case ConstantPoolTag::kInvalid:
UNREACHABLE();
case ConstantPoolTag::kStaticField:
obj = ReadObject();
ASSERT(obj.IsField());
break;
case ConstantPoolTag::kInstanceField:
field ^= ReadObject();
// InstanceField constant occupies 2 entries.
// The first entry is used for field offset.
obj = Smi::New(field.HostOffset() / kCompressedWordSize);
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// The second entry is used for field object.
obj = field.ptr();
break;
case ConstantPoolTag::kClass:
obj = ReadObject();
ASSERT(obj.IsClass());
break;
case ConstantPoolTag::kTypeArgumentsField:
cls ^= ReadObject();
obj = Smi::New(cls.host_type_arguments_field_offset() /
kCompressedWordSize);
break;
case ConstantPoolTag::kType:
obj = ReadObject();
ASSERT(obj.IsAbstractType());
break;
case ConstantPoolTag::kClosureFunction: {
intptr_t closure_index = reader_.ReadUInt();
obj = closures_->At(closure_index);
ASSERT(obj.IsFunction());
// Set current entry.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, obj);
const auto& signature =
FunctionType::Handle(Z, Function::Cast(obj).signature());
FunctionTypeScope function_type_scope(this, signature);
// Read constant pool until corresponding EndClosureFunctionScope.
i = ReadConstantPool(function, pool, i + 1);
// Proceed with the rest of entries.
continue;
}
case ConstantPoolTag::kEndClosureFunctionScope: {
// EndClosureFunctionScope entry is not used and set to null.
obj = Object::null();
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, obj);
return i;
}
case ConstantPoolTag::kSubtypeTestCache: {
obj = SubtypeTestCache::New(SubtypeTestCache::kMaxInputs);
} break;
case ConstantPoolTag::kEmptyTypeArguments:
obj = Object::empty_type_arguments().ptr();
break;
case ConstantPoolTag::kObjectRef:
obj = ReadObject();
break;
case ConstantPoolTag::kDirectCall: {
// DirectCall constant occupies 2 entries.
// The first entry is used for target function.
obj = ReadObject();
ASSERT(obj.IsFunction());
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
case ConstantPoolTag::kInterfaceCall: {
elem = ReadObject();
ASSERT(elem.IsFunction());
// InterfaceCall constant occupies 2 entries.
// The first entry is used for interface target.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, elem);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
case ConstantPoolTag::kInstantiatedInterfaceCall: {
elem = ReadObject();
ASSERT(elem.IsFunction());
// InstantiatedInterfaceCall constant occupies 3 entries:
// 1) Interface target.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, elem);
++i;
ASSERT(i < obj_count);
// 2) Arguments descriptor.
obj = ReadObject();
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, obj);
++i;
ASSERT(i < obj_count);
// 3) Static receiver type.
obj = ReadObject();
} break;
case ConstantPoolTag::kDynamicCall: {
name ^= ReadObject();
ASSERT(name.IsSymbol());
// Do not mangle ==:
// * operator == takes an Object so it is either not checked or
// checked at the entry because the parameter is marked covariant,
// neither of those cases require a dynamic invocation forwarder
if (!Field::IsGetterName(name) &&
(name.ptr() != Symbols::EqualOperator().ptr())) {
name = Function::CreateDynamicInvocationForwarderName(name);
}
// DynamicCall constant occupies 2 entries: selector and arguments
// descriptor.
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, name);
++i;
ASSERT(i < obj_count);
// The second entry is used for arguments descriptor.
obj = ReadObject();
} break;
default:
UNREACHABLE();
}
pool.SetTypeAt(i, ObjectPool::EntryType::kTaggedObject,
ObjectPool::Patchability::kNotPatchable,
ObjectPool::SnapshotBehavior::kNotSnapshotable);
pool.SetObjectAt(i, obj);
}
return obj_count - 1;
}
BytecodePtr BytecodeReaderHelper::ReadBytecode(const ObjectPool& pool) {
const intptr_t size = reader_.ReadUInt();
const intptr_t offset = reader_.offset();
const uint8_t* data = reader_.BufferAt(offset);
reader_.set_offset(offset + size);
// Create and return bytecode object.
return Bytecode::New(reinterpret_cast<uword>(data), size, offset,
*(reader_.typed_data()), pool);
}
void BytecodeReaderHelper::ReadExceptionsTable(const Function& function,
const Bytecode& bytecode,
bool has_exceptions_table) {
const intptr_t try_block_count =
has_exceptions_table ? reader_.ReadListLength() : 0;
if (try_block_count > 0) {
const ObjectPool& pool = ObjectPool::Handle(Z, bytecode.object_pool());
AbstractType& handler_type = AbstractType::Handle(Z);
Array& handler_types = Array::Handle(Z);
DescriptorList* pc_descriptors_list = new (Z) DescriptorList(Z);
ExceptionHandlerList* exception_handlers_list =
new (Z) ExceptionHandlerList(function);
// Encoding of ExceptionsTable is described in
// pkg/dart2bytecode/lib/exceptions.dart.
for (intptr_t try_index = 0; try_index < try_block_count; try_index++) {
intptr_t outer_try_index_plus1 = reader_.ReadUInt();
intptr_t outer_try_index = outer_try_index_plus1 - 1;
// PcDescriptors are expressed in terms of return addresses.
intptr_t start_pc =
KernelBytecode::BytecodePcToOffset(reader_.ReadUInt(),
/* is_return_address = */ true);
intptr_t end_pc =
KernelBytecode::BytecodePcToOffset(reader_.ReadUInt(),
/* is_return_address = */ true);
intptr_t handler_pc =
KernelBytecode::BytecodePcToOffset(reader_.ReadUInt(),
/* is_return_address = */ false);
uint8_t flags = reader_.ReadByte();
const uint8_t kFlagNeedsStackTrace = 1 << 0;
const uint8_t kFlagIsSynthetic = 1 << 1;
const bool needs_stacktrace = (flags & kFlagNeedsStackTrace) != 0;
const bool is_generated = (flags & kFlagIsSynthetic) != 0;
intptr_t type_count = reader_.ReadListLength();
ASSERT(type_count > 0);
handler_types = Array::New(type_count, Heap::kOld);
for (intptr_t i = 0; i < type_count; i++) {
intptr_t type_index = reader_.ReadUInt();
ASSERT(type_index < pool.Length());
handler_type ^= pool.ObjectAt(type_index);
handler_types.SetAt(i, handler_type);
}
pc_descriptors_list->AddDescriptor(
UntaggedPcDescriptors::kOther, start_pc, DeoptId::kNone,
TokenPosition::kNoSource, try_index,
UntaggedPcDescriptors::kInvalidYieldIndex);
pc_descriptors_list->AddDescriptor(
UntaggedPcDescriptors::kOther, end_pc, DeoptId::kNone,
TokenPosition::kNoSource, try_index,
UntaggedPcDescriptors::kInvalidYieldIndex);
// The exception handler keeps a zone handle of the types array, rather
// than a raw pointer. Do not share the handle across iterations to avoid
// clobbering the array.
exception_handlers_list->AddHandler(
try_index, outer_try_index, handler_pc, is_generated,
Array::ZoneHandle(Z, handler_types.ptr()), needs_stacktrace);
}
const PcDescriptors& descriptors = PcDescriptors::Handle(
Z, pc_descriptors_list->FinalizePcDescriptors(bytecode.PayloadStart()));
bytecode.set_pc_descriptors(descriptors);
const ExceptionHandlers& handlers = ExceptionHandlers::Handle(
Z, exception_handlers_list->FinalizeExceptionHandlers(
bytecode.PayloadStart()));
bytecode.set_exception_handlers(handlers);
} else {
bytecode.set_pc_descriptors(Object::empty_descriptors());
bytecode.set_exception_handlers(Object::empty_exception_handlers());
}
}
void BytecodeReaderHelper::ReadSourcePositions(const Bytecode& bytecode,
bool has_source_positions) {
if (!has_source_positions) {
return;
}
intptr_t offset = reader_.ReadUInt();
bytecode.set_source_positions_binary_offset(
bytecode_component_->GetSourcePositionsOffset() + offset);
}
void BytecodeReaderHelper::ReadLocalVariables(const Bytecode& bytecode,
bool has_local_variables) {
if (!has_local_variables) {
return;
}
reader_.ReadUInt(); // Skip local variables offset.
}
ArrayPtr BytecodeReaderHelper::ReadBytecodeComponent() {
ASSERT(IsolateGroup::Current()->program_lock()->IsCurrentThreadWriter());
AlternativeReadingScope alt(&reader_, 0);
const intptr_t start_offset = reader_.offset();
intptr_t magic = reader_.ReadUInt32();
if (magic != KernelBytecode::kMagicValue) {
FATAL("Unexpected Dart bytecode magic %" Px, magic);
}
const intptr_t version = reader_.ReadUInt32();
if (version != KernelBytecode::kBytecodeFormatVersion) {
FATAL("Unsupported Dart bytecode format version %" Pd
". "
"This version of Dart VM supports bytecode format version %" Pd ".",
version, KernelBytecode::kBytecodeFormatVersion);
}
reader_.ReadUInt32(); // Skip stringTable.numItems
const intptr_t string_table_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip objectTable.numItems
const intptr_t object_table_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip main.numItems
const intptr_t main_offset = start_offset + reader_.ReadUInt32();
const intptr_t num_libraries = reader_.ReadUInt32();
const intptr_t library_index_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip libraries.numItems
const intptr_t libraries_offset = start_offset + reader_.ReadUInt32();
const intptr_t num_classes = reader_.ReadUInt32();
const intptr_t classes_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip members.numItems
const intptr_t members_offset = start_offset + reader_.ReadUInt32();
const intptr_t num_codes = reader_.ReadUInt32();
const intptr_t codes_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip sourcePositions.numItems
const intptr_t source_positions_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip sourceFiles.numItems
const intptr_t source_files_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip lineStarts.numItems
const intptr_t line_starts_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip localVariables.numItems
const intptr_t local_variables_offset = start_offset + reader_.ReadUInt32();
reader_.ReadUInt32(); // Skip annotations.numItems
const intptr_t annotations_offset = start_offset + reader_.ReadUInt32();
// Read header of string table.
reader_.set_offset(string_table_offset);
const intptr_t num_one_byte_strings = reader_.ReadUInt32();
const intptr_t num_two_byte_strings = reader_.ReadUInt32();
const intptr_t strings_contents_offset =
reader_.offset() + (num_one_byte_strings + num_two_byte_strings) * 4;
// Read header of object table.
reader_.set_offset(object_table_offset);
const intptr_t num_objects = reader_.ReadUInt();
const intptr_t objects_size = reader_.ReadUInt();
// Skip over contents of objects.
const intptr_t objects_contents_offset = reader_.offset();
const intptr_t object_offsets_offset = objects_contents_offset + objects_size;
reader_.set_offset(object_offsets_offset);
auto& bytecode_component_array = Array::Handle(
Z, BytecodeComponentData::New(
Z, *(reader_.typed_data()), version, num_objects,
string_table_offset, strings_contents_offset,
object_offsets_offset, objects_contents_offset, main_offset,
num_libraries, library_index_offset, libraries_offset, num_classes,
classes_offset, members_offset, num_codes, codes_offset,
source_positions_offset, source_files_offset, line_starts_offset,
local_variables_offset, annotations_offset, Heap::kOld));
BytecodeComponentData bytecode_component(bytecode_component_array);
// Read object offsets.
Smi& offs = Smi::Handle(Z);
for (intptr_t i = 0; i < num_objects; ++i) {
offs = Smi::New(reader_.ReadUInt());
bytecode_component.SetObject(i, offs);
}
return bytecode_component_array.ptr();
}
void BytecodeReaderHelper::ResetObjects() {
reader_.set_offset(bytecode_component_->GetObjectOffsetsOffset());
const intptr_t num_objects = bytecode_component_->GetNumObjects();
// Read object offsets.
Smi& offs = Smi::Handle(Z);
for (intptr_t i = 0; i < num_objects; ++i) {
offs = Smi::New(reader_.ReadUInt());
bytecode_component_->SetObject(i, offs);
}
}
ObjectPtr BytecodeReaderHelper::ReadObject() {
uint32_t header = reader_.ReadUInt();
if ((header & kReferenceBit) != 0) {
intptr_t index = header >> kIndexShift;
if (index == 0) {
return Object::null();
}
ObjectPtr obj = bytecode_component_->GetObject(index);
if (obj->IsHeapObject()) {
return obj;
}
// Object is not loaded yet.
intptr_t offset = bytecode_component_->GetObjectsContentsOffset() +
Smi::Value(Smi::RawCast(obj));
AlternativeReadingScope alt(&reader_, offset);
header = reader_.ReadUInt();
obj = ReadObjectContents(header);
ASSERT(obj->IsHeapObject());
{
REUSABLE_OBJECT_HANDLESCOPE(thread_);
Object& obj_handle = thread_->ObjectHandle();
obj_handle = obj;
bytecode_component_->SetObject(index, obj_handle);
}
return obj;
}
return ReadObjectContents(header);
}
StringPtr BytecodeReaderHelper::ConstructorName(const Class& cls,
const String& name) {
GrowableHandlePtrArray<const String> pieces(Z, 3);
pieces.Add(String::Handle(Z, cls.Name()));
pieces.Add(Symbols::Dot());
pieces.Add(name);
return Symbols::FromConcatAll(thread_, pieces);
}
ObjectPtr BytecodeReaderHelper::ReadObjectContents(uint32_t header) {
ASSERT(((header & kReferenceBit) == 0));
// Must be in sync with enum ObjectKind in
// pkg/dart2bytecode/lib/object_table.dart.
enum ObjectKind {
kInvalid,
kLibrary,
kScript,
kClass,
kMember,
kClosure,
kName,
kConstObject,
kType,
kTypeArguments,
kArgDesc,
};
// Member flags, must be in sync with _MemberHandle constants in
// pkg/dart2bytecode/lib/object_table.dart.
const intptr_t kFlagIsField = kFlagBit0;
const intptr_t kFlagIsConstructor = kFlagBit1;
// ArgDesc flags, must be in sync with _ArgDescHandle constants in
// pkg/dart2bytecode/lib/object_table.dart.
const int kFlagHasNamedArgs = kFlagBit0;
const int kFlagHasTypeArgs = kFlagBit1;
// Script flags, must be in sync with _ScriptHandle constants in
// pkg/dart2bytecode/lib/object_table.dart.
const int kFlagHasSourceFile = kFlagBit0;
// Name flags, must be in sync with _NameHandle constants in
// pkg/dart2bytecode/lib/object_table.dart.
const intptr_t kFlagIsPublic = kFlagBit0;
const intptr_t kind = (header >> kKindShift) & kKindMask;
const intptr_t flags = header & kFlagsMask;
switch (kind) {
case kInvalid:
UNREACHABLE();
break;
case kLibrary: {
String& uri = String::CheckedHandle(Z, ReadObject());
LibraryPtr library = Library::LookupLibrary(thread_, uri);
if (library == Library::null()) {
FATAL("Unable to find library %s", uri.ToCString());
}
return library;
}
case kClass: {
const Library& library = Library::CheckedHandle(Z, ReadObject());
const String& class_name = String::CheckedHandle(Z, ReadObject());
if (class_name.ptr() == Symbols::Empty().ptr()) {
NoSafepointScope no_safepoint_scope(thread_);
ClassPtr cls = library.toplevel_class();
if (cls == Class::null()) {
FATAL("Unable to find toplevel class %s", library.ToCString());
}
return cls;
}
ClassPtr cls = library.LookupClassAllowPrivate(class_name);
if (cls == Class::null()) {
FATAL("Unable to find class %s in %s", class_name.ToCString(),
library.ToCString());
}
return cls;
}
case kMember: {
const Class& cls = Class::CheckedHandle(Z, ReadObject());
String& name = String::CheckedHandle(Z, ReadObject());
if ((flags & kFlagIsField) != 0) {
FieldPtr field = cls.LookupField(name);
if (field == Field::null()) {
FATAL("Unable to find field %s in %s", name.ToCString(),
cls.ToCString());
}
return field;
} else {
if ((flags & kFlagIsConstructor) != 0) {
name = ConstructorName(cls, name);
}
ASSERT(!name.IsNull() && name.IsSymbol());
if (name.ptr() == scoped_function_name_.ptr() &&
cls.ptr() == scoped_function_class_.ptr()) {
return scoped_function_.ptr();
}
FunctionPtr function = Function::null();
if ((flags & kFlagIsConstructor) != 0) {
if (cls.EnsureIsAllocateFinalized(thread_) == Error::null()) {
function = Resolver::ResolveFunction(Z, cls, name);
}
} else {
if (cls.EnsureIsFinalized(thread_) == Error::null()) {
function = Resolver::ResolveFunction(Z, cls, name);
}
}
if (function == Function::null()) {
// When requesting a getter, also return method extractors.
if (Field::IsGetterName(name)) {
String& method_name =
String::Handle(Z, Field::NameFromGetter(name));
function = Resolver::ResolveFunction(Z, cls, method_name);
if (function != Function::null()) {
function = Function::Handle(Z, function).GetMethodExtractor(name);
if (function != Function::null()) {
return function;
}
}
}
FATAL("Unable to find function %s in %s", name.ToCString(),
cls.ToCString());
}
return function;
}
}
case kClosure: {
ReadObject(); // Skip enclosing member.
const intptr_t closure_index = reader_.ReadUInt();
return closures_->At(closure_index);
}
case kName: {
if ((flags & kFlagIsPublic) == 0) {
const Library& library = Library::CheckedHandle(Z, ReadObject());
ASSERT(!library.IsNull());