-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
kernel_loader.cc
2267 lines (2004 loc) · 88.4 KB
/
kernel_loader.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) 2016, 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/kernel_loader.h"
#include <string.h>
#include "vm/compiler/frontend/constant_evaluator.h"
#include "vm/compiler/frontend/kernel_translation_helper.h"
#include "vm/dart_api_impl.h"
#include "vm/flags.h"
#include "vm/heap/heap.h"
#include "vm/kernel_binary.h"
#include "vm/longjump.h"
#include "vm/object_store.h"
#include "vm/parser.h"
#include "vm/reusable_handles.h"
#include "vm/service_isolate.h"
#include "vm/symbols.h"
#include "vm/thread.h"
#if !defined(DART_PRECOMPILED_RUNTIME)
namespace dart {
namespace kernel {
#define Z (zone_)
#define I (isolate_)
#define T (type_translator_)
#define H (translation_helper_)
static const char* const kVMServiceIOLibraryUri = "dart:vmservice_io";
class SimpleExpressionConverter {
public:
SimpleExpressionConverter(TranslationHelper* translation_helper,
KernelReaderHelper* reader_helper)
: translation_helper_(*translation_helper),
zone_(translation_helper_.zone()),
simple_value_(NULL),
helper_(reader_helper) {}
bool IsSimple(intptr_t kernel_offset) {
AlternativeReadingScope alt(&helper_->reader_, kernel_offset);
uint8_t payload = 0;
Tag tag = helper_->ReadTag(&payload); // read tag.
switch (tag) {
case kBigIntLiteral: {
const String& literal_str =
H.DartString(helper_->ReadStringReference(),
Heap::kOld); // read index into string table.
simple_value_ = &Integer::ZoneHandle(Z, Integer::New(literal_str));
if (simple_value_->IsNull()) {
H.ReportError("Integer literal %s is out of range",
literal_str.ToCString());
UNREACHABLE();
}
*simple_value_ = H.Canonicalize(*simple_value_);
return true;
}
case kStringLiteral:
simple_value_ = &H.DartSymbolPlain(
helper_->ReadStringReference()); // read index into string table.
return true;
case kSpecializedIntLiteral:
simple_value_ =
&Integer::ZoneHandle(Z, Integer::New(static_cast<int32_t>(payload) -
SpecializedIntLiteralBias,
Heap::kOld));
*simple_value_ = H.Canonicalize(*simple_value_);
return true;
case kNegativeIntLiteral:
simple_value_ = &Integer::ZoneHandle(
Z, Integer::New(-static_cast<int64_t>(helper_->ReadUInt()),
Heap::kOld)); // read value.
*simple_value_ = H.Canonicalize(*simple_value_);
return true;
case kPositiveIntLiteral:
simple_value_ = &Integer::ZoneHandle(
Z, Integer::New(static_cast<int64_t>(helper_->ReadUInt()),
Heap::kOld)); // read value.
*simple_value_ = H.Canonicalize(*simple_value_);
return true;
case kDoubleLiteral:
simple_value_ = &Double::ZoneHandle(
Z, Double::New(helper_->ReadDouble(), Heap::kOld)); // read value.
*simple_value_ = H.Canonicalize(*simple_value_);
return true;
case kTrueLiteral:
simple_value_ = &Bool::Handle(Z, Bool::Get(true).raw());
return true;
case kFalseLiteral:
simple_value_ = &Bool::Handle(Z, Bool::Get(false).raw());
return true;
case kNullLiteral:
simple_value_ = &Instance::ZoneHandle(Z, Instance::null());
return true;
default:
return false;
}
}
const Instance& SimpleValue() { return *simple_value_; }
Zone* zone() const { return zone_; }
private:
TranslationHelper& translation_helper_;
Zone* zone_;
Instance* simple_value_;
KernelReaderHelper* helper_;
DISALLOW_COPY_AND_ASSIGN(SimpleExpressionConverter);
};
RawArray* KernelLoader::MakeFieldsArray() {
const intptr_t len = fields_.length();
const Array& res = Array::Handle(zone_, Array::New(len, Heap::kOld));
for (intptr_t i = 0; i < len; i++) {
res.SetAt(i, *fields_[i]);
}
return res.raw();
}
RawArray* KernelLoader::MakeFunctionsArray() {
const intptr_t len = functions_.length();
const Array& res = Array::Handle(zone_, Array::New(len, Heap::kOld));
for (intptr_t i = 0; i < len; i++) {
res.SetAt(i, *functions_[i]);
}
return res.raw();
}
RawLibrary* BuildingTranslationHelper::LookupLibraryByKernelLibrary(
NameIndex library) {
return loader_->LookupLibrary(library);
}
RawClass* BuildingTranslationHelper::LookupClassByKernelClass(NameIndex klass) {
#if defined(DEBUG)
LibraryLookupHandleScope library_lookup_handle_scope(library_lookup_handle_);
#endif // defined(DEBUG)
library_lookup_handle_ = loader_->LookupLibraryFromClass(klass);
return loader_->LookupClass(library_lookup_handle_, klass);
}
LibraryIndex::LibraryIndex(const ExternalTypedData& kernel_data)
: reader_(kernel_data) {
intptr_t data_size = reader_.size();
procedure_count_ = reader_.ReadUInt32At(data_size - 4);
procedure_index_offset_ = data_size - 4 - (procedure_count_ + 1) * 4;
class_count_ = reader_.ReadUInt32At(procedure_index_offset_ - 4);
class_index_offset_ = procedure_index_offset_ - 4 - (class_count_ + 1) * 4;
}
ClassIndex::ClassIndex(const uint8_t* buffer,
intptr_t buffer_size,
intptr_t class_offset,
intptr_t class_size)
: reader_(buffer, buffer_size) {
Init(class_offset, class_size);
}
ClassIndex::ClassIndex(const ExternalTypedData& library_kernel_data,
intptr_t class_offset,
intptr_t class_size)
: reader_(library_kernel_data) {
Init(class_offset, class_size);
}
void ClassIndex::Init(intptr_t class_offset, intptr_t class_size) {
procedure_count_ = reader_.ReadUInt32At(class_offset + class_size - 4);
procedure_index_offset_ =
class_offset + class_size - 4 - (procedure_count_ + 1) * 4;
}
using UriToSourceTable = DirectChainedHashMap<UriToSourceTableTrait>;
KernelLoader::KernelLoader(Program* program,
UriToSourceTable* uri_to_source_table)
: program_(program),
thread_(Thread::Current()),
zone_(thread_->zone()),
isolate_(thread_->isolate()),
patch_classes_(Array::ZoneHandle(zone_)),
library_kernel_offset_(-1), // Set to the correct value in LoadLibrary
correction_offset_(-1), // Set to the correct value in LoadLibrary
loading_native_wrappers_library_(false),
library_kernel_data_(ExternalTypedData::ZoneHandle(zone_)),
kernel_program_info_(KernelProgramInfo::ZoneHandle(zone_)),
translation_helper_(this, thread_, Heap::kOld),
helper_(zone_,
&translation_helper_,
program_->kernel_data(),
program_->kernel_data_size(),
0),
type_translator_(&helper_, &active_class_, /* finalize= */ false),
inferred_type_metadata_helper_(&helper_),
bytecode_metadata_helper_(&helper_, &active_class_),
external_name_class_(Class::Handle(Z)),
external_name_field_(Field::Handle(Z)),
potential_natives_(GrowableObjectArray::Handle(Z)),
potential_pragma_functions_(GrowableObjectArray::Handle(Z)),
potential_extension_libraries_(GrowableObjectArray::Handle(Z)),
pragma_class_(Class::Handle(Z)),
name_index_handle_(Smi::Handle(Z)),
expression_evaluation_library_(Library::Handle(Z)),
expression_evaluation_function_(Function::Handle(Z)) {
if (!program->is_single_program()) {
FATAL(
"Trying to load a concatenated dill file at a time where that is "
"not allowed");
}
InitializeFields(uri_to_source_table);
}
void KernelLoader::ReadObfuscationProhibitions() {
ObfuscationProhibitionsMetadataHelper helper(&helper_);
helper.ReadProhibitions();
}
Object& KernelLoader::LoadEntireProgram(Program* program,
bool process_pending_classes) {
Thread* thread = Thread::Current();
TIMELINE_DURATION(thread, Isolate, "LoadKernel");
if (program->is_single_program()) {
KernelLoader loader(program, /*uri_to_source_table=*/nullptr);
return Object::Handle(loader.LoadProgram(process_pending_classes));
}
kernel::Reader reader(program->kernel_data(), program->kernel_data_size());
GrowableArray<intptr_t> subprogram_file_starts;
index_programs(&reader, &subprogram_file_starts);
Zone* zone = thread->zone();
Library& library = Library::Handle(zone);
intptr_t subprogram_count = subprogram_file_starts.length() - 1;
// First index all source tables.
UriToSourceTable uri_to_source_table;
UriToSourceTableEntry wrapper;
for (intptr_t i = subprogram_count - 1; i >= 0; --i) {
intptr_t subprogram_start = subprogram_file_starts.At(i);
intptr_t subprogram_end = subprogram_file_starts.At(i + 1);
Thread* thread_ = Thread::Current();
Zone* zone_ = thread_->zone();
TranslationHelper translation_helper(thread);
KernelReaderHelper helper_(zone_, &translation_helper,
program->kernel_data() + subprogram_start,
subprogram_end - subprogram_start, 0);
const intptr_t source_table_size = helper_.SourceTableSize();
for (intptr_t index = 0; index < source_table_size; ++index) {
const String& uri_string = helper_.SourceTableUriFor(index);
wrapper.uri = &uri_string;
TypedData& line_starts =
TypedData::Handle(Z, helper_.GetLineStartsFor(index));
if (line_starts.Length() == 0) continue;
const String& script_source = helper_.GetSourceFor(index);
wrapper.uri = &uri_string;
UriToSourceTableEntry* pair = uri_to_source_table.LookupValue(&wrapper);
if (pair != NULL) {
// At least two entries with content. Unless the content is the same
// that's not valid.
if (pair->sources->CompareTo(script_source) != 0 ||
!pair->line_starts->CanonicalizeEquals(line_starts)) {
FATAL(
"Invalid kernel binary: Contains at least two source entries "
"that do not agree.");
}
} else {
UriToSourceTableEntry* tmp = new UriToSourceTableEntry();
tmp->uri = &uri_string;
tmp->sources = &script_source;
tmp->line_starts = &line_starts;
uri_to_source_table.Insert(tmp);
}
}
}
// Create "fake programs" for each sub-program.
for (intptr_t i = subprogram_count - 1; i >= 0; --i) {
intptr_t subprogram_start = subprogram_file_starts.At(i);
intptr_t subprogram_end = subprogram_file_starts.At(i + 1);
reader.set_raw_buffer(program->kernel_data() + subprogram_start);
reader.set_size(subprogram_end - subprogram_start);
reader.set_offset(0);
Program* subprogram = Program::ReadFrom(&reader);
ASSERT(subprogram->is_single_program());
KernelLoader loader(subprogram, &uri_to_source_table);
Object& load_result = Object::Handle(loader.LoadProgram(false));
if (load_result.IsError()) return load_result;
if (load_result.IsLibrary()) {
library ^= load_result.raw();
}
delete subprogram;
}
if (process_pending_classes && !ClassFinalizer::ProcessPendingClasses()) {
// Class finalization failed -> sticky error would be set.
return Error::Handle(thread->StealStickyError());
}
return library;
}
void KernelLoader::index_programs(
kernel::Reader* reader,
GrowableArray<intptr_t>* subprogram_file_starts) {
// Dill files can be concatenated (e.g. cat a.dill b.dill > c.dill), so we
// need to first index the (possibly combined) file.
// First entry becomes last entry.
// Last entry is for ease of calculating size of last subprogram.
subprogram_file_starts->Add(reader->size());
reader->set_offset(reader->size() - 4);
while (reader->offset() > 0) {
intptr_t size = reader->ReadUInt32();
intptr_t start = reader->offset() - size;
if (start < 0) {
FATAL("Invalid kernel binary: Indicated size is invalid.");
}
subprogram_file_starts->Add(start);
reader->set_offset(start - 4);
}
subprogram_file_starts->Reverse();
}
RawString* KernelLoader::FindSourceForScript(const uint8_t* kernel_buffer,
intptr_t kernel_buffer_length,
const String& uri) {
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
TranslationHelper translation_helper(thread);
KernelReaderHelper reader(zone, &translation_helper, kernel_buffer,
kernel_buffer_length, 0);
intptr_t source_table_size = reader.SourceTableSize();
for (intptr_t i = 0; i < source_table_size; ++i) {
const String& source_uri = reader.SourceTableUriFor(i);
if (source_uri.EndsWith(uri)) {
return reader.GetSourceFor(i).raw();
}
}
return String::null();
}
void KernelLoader::InitializeFields(UriToSourceTable* uri_to_source_table) {
const intptr_t source_table_size = helper_.SourceTableSize();
const Array& scripts =
Array::Handle(Z, Array::New(source_table_size, Heap::kOld));
patch_classes_ = Array::New(source_table_size, Heap::kOld);
// Copy the Kernel string offsets out of the binary and into the VM's heap.
ASSERT(program_->string_table_offset() >= 0);
Reader reader(program_->kernel_data(), program_->kernel_data_size());
reader.set_offset(program_->string_table_offset());
intptr_t count = reader.ReadUInt() + 1;
TypedData& offsets = TypedData::Handle(
Z, TypedData::New(kTypedDataUint32ArrayCid, count, Heap::kOld));
offsets.SetUint32(0, 0);
intptr_t end_offset = 0;
for (intptr_t i = 1; i < count; ++i) {
end_offset = reader.ReadUInt();
offsets.SetUint32(i << 2, end_offset);
}
// Create view of the string data.
const ExternalTypedData& data = ExternalTypedData::Handle(
Z,
reader.ExternalDataFromTo(reader.offset(), reader.offset() + end_offset));
// Create a view of the constants table. The trailing ComponentIndex is
// negligible in size.
const ExternalTypedData& constants_table = ExternalTypedData::Handle(
Z, reader.ExternalDataFromTo(program_->constant_table_offset(),
program_->kernel_data_size()));
// Copy the canonical names into the VM's heap. Encode them as unsigned, so
// the parent indexes are adjusted when extracted.
reader.set_offset(program_->name_table_offset());
count = reader.ReadUInt() * 2;
TypedData& names = TypedData::Handle(
Z, TypedData::New(kTypedDataUint32ArrayCid, count, Heap::kOld));
for (intptr_t i = 0; i < count; ++i) {
names.SetUint32(i << 2, reader.ReadUInt());
}
// Create view of metadata payloads.
const ExternalTypedData& metadata_payloads = ExternalTypedData::Handle(
Z, reader.ExternalDataFromTo(program_->metadata_payloads_offset(),
program_->metadata_mappings_offset()));
ASSERT(Utils::IsAligned(metadata_payloads.DataAddr(0), kWordSize));
// Create view of metadata mappings.
const ExternalTypedData& metadata_mappings = ExternalTypedData::Handle(
Z, reader.ExternalDataFromTo(program_->metadata_mappings_offset(),
program_->string_table_offset()));
const Array& libraries_cache =
Array::Handle(Z, HashTables::New<UnorderedHashMap<SmiTraits>>(
program_->library_count(), Heap::kOld));
const intptr_t kClassesPerLibraryGuess = 5;
const Array& classes_cache = Array::Handle(
Z, HashTables::New<UnorderedHashMap<SmiTraits>>(
kClassesPerLibraryGuess * program_->library_count(), Heap::kOld));
kernel_program_info_ = KernelProgramInfo::New(
offsets, data, names, metadata_payloads, metadata_mappings,
constants_table, scripts, libraries_cache, classes_cache);
H.InitFromKernelProgramInfo(kernel_program_info_);
Script& script = Script::Handle(Z);
for (intptr_t index = 0; index < source_table_size; ++index) {
script = LoadScriptAt(index, uri_to_source_table);
scripts.SetAt(index, script);
}
if (FLAG_enable_interpreter || FLAG_use_bytecode_compiler) {
bytecode_metadata_helper_.ReadBytecodeComponent();
}
}
KernelLoader::KernelLoader(const Script& script,
const ExternalTypedData& kernel_data,
intptr_t data_program_offset)
: program_(NULL),
thread_(Thread::Current()),
zone_(thread_->zone()),
isolate_(thread_->isolate()),
patch_classes_(Array::ZoneHandle(zone_)),
library_kernel_offset_(data_program_offset),
correction_offset_(0),
loading_native_wrappers_library_(false),
library_kernel_data_(ExternalTypedData::ZoneHandle(zone_)),
kernel_program_info_(
KernelProgramInfo::ZoneHandle(zone_, script.kernel_program_info())),
translation_helper_(this, thread_, Heap::kOld),
helper_(zone_, &translation_helper_, script, kernel_data, 0),
type_translator_(&helper_, &active_class_, /* finalize= */ false),
inferred_type_metadata_helper_(&helper_),
bytecode_metadata_helper_(&helper_, &active_class_),
external_name_class_(Class::Handle(Z)),
external_name_field_(Field::Handle(Z)),
potential_natives_(GrowableObjectArray::Handle(Z)),
potential_pragma_functions_(GrowableObjectArray::Handle(Z)),
potential_extension_libraries_(GrowableObjectArray::Handle(Z)),
pragma_class_(Class::Handle(Z)),
name_index_handle_(Smi::Handle(Z)),
expression_evaluation_library_(Library::Handle(Z)),
expression_evaluation_function_(Function::Handle(Z)) {
ASSERT(T.active_class_ == &active_class_);
T.finalize_ = false;
const Array& scripts = Array::Handle(Z, kernel_program_info_.scripts());
patch_classes_ = Array::New(scripts.Length(), Heap::kOld);
library_kernel_data_ = kernel_data.raw();
H.InitFromKernelProgramInfo(kernel_program_info_);
}
const Array& KernelLoader::ReadConstantTable() {
if (program_->library_count() == 0) {
return Array::empty_array();
}
// We use the very first library's toplevel class as an owner for an
// [ActiveClassScope]
//
// Though since constants cannot refer to types containing type parameter
// references, the only purpose of the class is to serve as an owner for
// signature functions (which get created for function types).
const dart::Library& owner_library =
Library::Handle(Z, LookupLibrary(library_canonical_name(0)));
const dart::Class& toplevel_class =
Class::Handle(Z, owner_library.toplevel_class());
ActiveClassScope active_class_scope(&active_class_, &toplevel_class);
helper_.SetOffset(program_->constant_table_offset());
TypeTranslator type_translator_(&helper_, &active_class_,
true /* finalize */);
ASSERT(type_translator_.active_class_ == &active_class_);
ConstantHelper helper(Z, &helper_, &type_translator_, &active_class_,
skip_vmservice_library_);
return helper.ReadConstantTable();
}
void KernelLoader::EvaluateDelayedPragmas() {
potential_pragma_functions_ =
kernel_program_info_.potential_pragma_functions();
if (potential_pragma_functions_.IsNull()) return;
Thread* thread = Thread::Current();
NoOOBMessageScope no_msg_scope(thread);
NoReloadScope no_reload_scope(thread->isolate(), thread);
Function& function = Function::Handle();
Library& library = Library::Handle();
Class& klass = Class::Handle();
for (int i = 0; i < potential_pragma_functions_.Length(); ++i) {
function ^= potential_pragma_functions_.At(i);
klass = function.Owner();
library = klass.library();
library.GetMetadata(function);
}
potential_pragma_functions_ = GrowableObjectArray::null();
kernel_program_info_.set_potential_pragma_functions(
GrowableObjectArray::Handle(Z));
}
void KernelLoader::AnnotateNativeProcedures(const Array& constant_table_array) {
KernelConstantsMap constant_table(constant_table_array.raw());
potential_natives_ = kernel_program_info_.potential_natives();
const intptr_t length =
!potential_natives_.IsNull() ? potential_natives_.Length() : 0;
if (length > 0) {
// Obtain `dart:_internal::ExternalName.name`.
EnsureExternalClassIsLookedUp();
Instance& constant = Instance::Handle(Z);
String& native_name = String::Handle(Z);
// Start scanning all candidates in [potential_natives] for the annotation
// constant. If the annotation is found, flag the [Function] as native and
// attach the native name to it.
Function& function = Function::Handle(Z);
for (intptr_t i = 0; i < length; ++i) {
function ^= potential_natives_.At(i);
helper_.SetOffset(function.KernelDataProgramOffset() +
function.kernel_offset());
{
ProcedureHelper procedure_helper(&helper_);
procedure_helper.ReadUntilExcluding(ProcedureHelper::kAnnotations);
}
const intptr_t annotation_count = helper_.ReadListLength();
for (intptr_t j = 0; j < annotation_count; ++j) {
const intptr_t tag = helper_.PeekTag();
if (tag == kConstantExpression) {
helper_.ReadByte(); // Skip the tag.
// We have a candiate. Let's look if it's an instance of the
// ExternalName class.
const intptr_t constant_table_offset = helper_.ReadUInt();
constant ^= constant_table.GetOrDie(constant_table_offset);
if (constant.clazz() == external_name_class_.raw()) {
// We found the annotation, let's flag the function as native and
// set the native name!
native_name ^= constant.GetField(external_name_field_);
function.set_is_native(true);
function.set_native_name(native_name);
function.set_is_external(false);
break;
}
} else {
helper_.SkipExpression();
}
}
}
// Clear out the list of [Function] objects which might need their native
// name to be set after reading the constant table from the kernel blob.
potential_natives_ = GrowableObjectArray::null();
kernel_program_info_.set_potential_natives(potential_natives_);
}
ASSERT(constant_table.Release().raw() == constant_table_array.raw());
}
RawString* KernelLoader::DetectExternalNameCtor() {
helper_.ReadTag();
helper_.ReadPosition();
NameIndex annotation_class = H.EnclosingName(
helper_.ReadCanonicalNameReference()); // read target reference,
if (!IsClassName(annotation_class, Symbols::DartInternal(),
Symbols::ExternalName())) {
helper_.SkipArguments();
return String::null();
}
// Read arguments:
intptr_t total_arguments = helper_.ReadUInt(); // read argument count.
helper_.SkipListOfDartTypes(); // read list of types.
intptr_t positional_arguments = helper_.ReadListLength();
ASSERT(total_arguments == 1 && positional_arguments == 1);
Tag tag = helper_.ReadTag();
ASSERT(tag == kStringLiteral);
String& result = H.DartSymbolPlain(
helper_.ReadStringReference()); // read index into string table.
// List of named.
intptr_t list_length = helper_.ReadListLength(); // read list length.
ASSERT(list_length == 0);
return result.raw();
}
bool KernelLoader::IsClassName(NameIndex name,
const String& library,
const String& klass) {
ASSERT(H.IsClass(name));
StringIndex class_name_index = H.CanonicalNameString(name);
if (!H.StringEquals(class_name_index, klass.ToCString())) {
return false;
}
ASSERT(H.IsLibrary(H.CanonicalNameParent(name)));
StringIndex library_name_index =
H.CanonicalNameString(H.CanonicalNameParent(name));
return H.StringEquals(library_name_index, library.ToCString());
}
bool KernelLoader::DetectPragmaCtor() {
helper_.ReadTag();
helper_.ReadPosition();
NameIndex annotation_class = H.EnclosingName(
helper_.ReadCanonicalNameReference()); // read target reference
helper_.SkipArguments();
return IsClassName(annotation_class, Symbols::DartCore(), Symbols::Pragma());
}
void KernelLoader::LoadNativeExtensionLibraries(
const Array& constant_table_array) {
const intptr_t length = !potential_extension_libraries_.IsNull()
? potential_extension_libraries_.Length()
: 0;
if (length == 0) return;
KernelConstantsMap constant_table(constant_table_array.raw());
// Obtain `dart:_internal::ExternalName.name`.
EnsureExternalClassIsLookedUp();
Instance& constant = Instance::Handle(Z);
String& uri_path = String::Handle(Z);
Library& library = Library::Handle(Z);
#if !defined(DART_PRECOMPILER)
Object& result = Object::Handle(Z);
#endif
for (intptr_t i = 0; i < length; ++i) {
library ^= potential_extension_libraries_.At(i);
helper_.SetOffset(library.kernel_offset());
LibraryHelper library_helper(&helper_);
library_helper.ReadUntilExcluding(LibraryHelper::kAnnotations);
const intptr_t annotation_count = helper_.ReadListLength();
for (intptr_t j = 0; j < annotation_count; ++j) {
uri_path = String::null();
const intptr_t tag = helper_.PeekTag();
if (tag == kConstantExpression) {
helper_.ReadByte(); // Skip the tag.
const intptr_t constant_table_index = helper_.ReadUInt();
constant ^= constant_table.GetOrDie(constant_table_index);
if (constant.clazz() == external_name_class_.raw()) {
uri_path ^= constant.GetField(external_name_field_);
}
} else if (tag == kConstructorInvocation ||
tag == kConstConstructorInvocation) {
uri_path = DetectExternalNameCtor();
} else {
helper_.SkipExpression();
}
if (uri_path.IsNull()) continue;
#if !defined(DART_PRECOMPILER)
if (!I->HasTagHandler()) {
H.ReportError("no library handler registered.");
}
I->BlockClassFinalization();
result = I->CallTagHandler(Dart_kImportExtensionTag, library, uri_path);
I->UnblockClassFinalization();
if (result.IsError()) {
H.ReportError(Error::Cast(result), "library handler failed");
}
#endif
// Create a dummy library and add it as an import to the current library.
// This allows later to discover and reload this native extension, e.g.
// when running from an app-jit snapshot.
// See Loader::ReloadNativeExtensions(...) which relies on
// Dart_GetImportsOfScheme('dart-ext').
const auto& native_library = Library::Handle(Library::New(uri_path));
library.AddImport(Namespace::Handle(Namespace::New(
native_library, Array::null_array(), Array::null_array())));
}
}
potential_extension_libraries_ = GrowableObjectArray::null();
ASSERT(constant_table.Release().raw() == constant_table_array.raw());
}
RawObject* KernelLoader::LoadProgram(bool process_pending_classes) {
ASSERT(kernel_program_info_.constants() == Array::null());
if (!program_->is_single_program()) {
FATAL(
"Trying to load a concatenated dill file at a time where that is "
"not allowed");
}
LongJumpScope jump;
if (setjmp(*jump.Set()) == 0) {
// Note that `problemsAsJson` on Component is implicitly skipped.
const intptr_t length = program_->library_count();
Object& last_library = Library::Handle(Z);
for (intptr_t i = 0; i < length; i++) {
last_library = LoadLibrary(i);
}
if (process_pending_classes) {
if (!ClassFinalizer::ProcessPendingClasses()) {
// Class finalization failed -> sticky error would be set.
return H.thread()->StealStickyError();
}
}
// Set pending fields array to flag constant table loading.
ASSERT(I->object_store()->pending_unevaluated_const_fields() ==
GrowableObjectArray::null());
GrowableObjectArray& pending_unevaluated_const_fields =
GrowableObjectArray::Handle(Z, GrowableObjectArray::New());
I->object_store()->set_pending_unevaluated_const_fields(
pending_unevaluated_const_fields);
// All classes were successfully loaded, so let's:
// a) load & canonicalize the constant table
const Array& constants = ReadConstantTable();
// b) set the native names for native functions which have been created
// so far (the rest will be directly set during LoadProcedure)
AnnotateNativeProcedures(constants);
LoadNativeExtensionLibraries(constants);
// c) update all scripts with the constants array
ASSERT(kernel_program_info_.constants() == Array::null());
kernel_program_info_.set_constants(constants);
kernel_program_info_.set_constants_table(ExternalTypedData::Handle(Z));
// d) evaluate pending field initializers
Error& error = Error::Handle(Z);
Field& field = Field::Handle(Z);
for (intptr_t i = 0, n = pending_unevaluated_const_fields.Length(); i < n;
i++) {
field ^= pending_unevaluated_const_fields.At(i);
error = field.Initialize();
if (!error.IsNull()) {
H.ReportError(error, "postponed field initializer");
}
}
pending_unevaluated_const_fields = GrowableObjectArray::null();
I->object_store()->set_pending_unevaluated_const_fields(
pending_unevaluated_const_fields);
// e) evaluate pragmas that were delayed
EvaluateDelayedPragmas();
NameIndex main = program_->main_method();
if (main != -1) {
NameIndex main_library = H.EnclosingName(main);
return LookupLibrary(main_library);
}
return bytecode_metadata_helper_.GetMainLibrary();
}
// Either class finalization failed or we caught a compile error.
// In both cases sticky error would be set.
return Thread::Current()->StealStickyError();
}
RawObject* KernelLoader::LoadExpressionEvaluationFunction(
const String& library_url,
const String& klass) {
// Find the original context, i.e. library/class, in which the evaluation will
// happen.
const Library& real_library =
Library::Handle(Z, Library::LookupLibrary(thread_, library_url));
ASSERT(!real_library.IsNull());
const Class& real_class = Class::Handle(
Z, klass.IsNull() ? real_library.toplevel_class()
: real_library.LookupClassAllowPrivate(klass));
ASSERT(!real_class.IsNull());
const intptr_t num_cids = I->class_table()->NumCids();
const intptr_t num_libs =
GrowableObjectArray::Handle(I->object_store()->libraries()).Length();
// Load the "evaluate:source" expression evaluation library.
ASSERT(expression_evaluation_library_.IsNull());
ASSERT(expression_evaluation_function_.IsNull());
const Object& result = Object::Handle(Z, LoadProgram(true));
if (result.IsError()) {
return result.raw();
}
ASSERT(!expression_evaluation_library_.IsNull());
ASSERT(!expression_evaluation_function_.IsNull());
ASSERT(GrowableObjectArray::Handle(I->object_store()->libraries()).Length() ==
num_libs);
ASSERT(I->class_table()->NumCids() == num_cids);
// Make the expression evaluation function have the right kernel data and
// parent.
auto& eval_data = ExternalTypedData::Handle(
Z, expression_evaluation_library_.kernel_data());
auto& eval_script =
Script::Handle(Z, expression_evaluation_function_.script());
expression_evaluation_function_.SetKernelDataAndScript(
eval_script, eval_data, expression_evaluation_library_.kernel_offset());
expression_evaluation_function_.set_owner(real_class);
return expression_evaluation_function_.raw();
}
void KernelLoader::FindModifiedLibraries(Program* program,
Isolate* isolate,
BitVector* modified_libs,
bool force_reload,
bool* is_empty_program,
intptr_t* p_num_classes,
intptr_t* p_num_procedures) {
LongJumpScope jump;
Zone* zone = Thread::Current()->zone();
if (setjmp(*jump.Set()) == 0) {
if (force_reload) {
// If a reload is being forced we mark all libraries as having
// been modified.
const GrowableObjectArray& libs =
GrowableObjectArray::Handle(isolate->object_store()->libraries());
intptr_t num_libs = libs.Length();
Library& lib = dart::Library::Handle(zone);
for (intptr_t i = 0; i < num_libs; i++) {
lib ^= libs.At(i);
if (!lib.is_dart_scheme()) {
modified_libs->Add(lib.index());
}
}
return;
}
if (p_num_classes != nullptr) {
*p_num_classes = 0;
}
if (p_num_procedures != nullptr) {
*p_num_procedures = 0;
}
// Now go through all the libraries that are present in the incremental
// kernel files, these will constitute the modified libraries.
*is_empty_program = true;
if (program->is_single_program()) {
KernelLoader loader(program, /*uri_to_source_table=*/nullptr);
loader.walk_incremental_kernel(modified_libs, is_empty_program,
p_num_classes, p_num_procedures);
}
kernel::Reader reader(program->kernel_data(), program->kernel_data_size());
GrowableArray<intptr_t> subprogram_file_starts;
index_programs(&reader, &subprogram_file_starts);
// Create "fake programs" for each sub-program.
intptr_t subprogram_count = subprogram_file_starts.length() - 1;
for (intptr_t i = 0; i < subprogram_count; ++i) {
intptr_t subprogram_start = subprogram_file_starts.At(i);
intptr_t subprogram_end = subprogram_file_starts.At(i + 1);
reader.set_raw_buffer(program->kernel_data() + subprogram_start);
reader.set_size(subprogram_end - subprogram_start);
reader.set_offset(0);
Program* subprogram = Program::ReadFrom(&reader);
ASSERT(subprogram->is_single_program());
KernelLoader loader(subprogram, /*uri_to_source_table=*/nullptr);
loader.walk_incremental_kernel(modified_libs, is_empty_program,
p_num_classes, p_num_procedures);
delete subprogram;
}
}
}
void KernelLoader::walk_incremental_kernel(BitVector* modified_libs,
bool* is_empty_program,
intptr_t* p_num_classes,
intptr_t* p_num_procedures) {
intptr_t length = program_->library_count();
*is_empty_program = *is_empty_program && (length == 0);
bool collect_library_stats =
p_num_classes != nullptr || p_num_procedures != nullptr;
intptr_t num_classes = 0;
intptr_t num_procedures = 0;
Library& lib = Library::Handle(Z);
for (intptr_t i = 0; i < length; i++) {
intptr_t kernel_offset = library_offset(i);
helper_.SetOffset(kernel_offset);
LibraryHelper library_helper(&helper_);
library_helper.ReadUntilIncluding(LibraryHelper::kCanonicalName);
lib = LookupLibraryOrNull(library_helper.canonical_name_);
if (!lib.IsNull() && !lib.is_dart_scheme()) {
// This is a library that already exists so mark it as being modified.
modified_libs->Add(lib.index());
}
if (collect_library_stats) {
intptr_t library_end = library_offset(i + 1);
library_kernel_data_ =
helper_.reader_.ExternalDataFromTo(kernel_offset, library_end);
LibraryIndex library_index(library_kernel_data_);
num_classes += library_index.class_count();
num_procedures += library_index.procedure_count();
}
}
if (p_num_classes != nullptr) {
*p_num_classes += num_classes;
}
if (p_num_procedures != nullptr) {
*p_num_procedures += num_procedures;
}
}
void KernelLoader::ReadInferredType(const Field& field,
intptr_t kernel_offset) {
const InferredTypeMetadata type =
inferred_type_metadata_helper_.GetInferredType(kernel_offset);
if (type.IsTrivial()) {
return;
}
field.set_guarded_cid(type.cid);
field.set_is_nullable(type.IsNullable());
field.set_guarded_list_length(Field::kNoFixedLength);
}
void KernelLoader::CheckForInitializer(const Field& field) {
if (helper_.PeekTag() == kSomething) {
SimpleExpressionConverter converter(&H, &helper_);
const bool has_simple_initializer =
converter.IsSimple(helper_.ReaderOffset() + 1);
if (!has_simple_initializer || !converter.SimpleValue().IsNull()) {
field.set_has_initializer(true);
return;
}
}
if (FLAG_enable_interpreter || FLAG_use_bytecode_compiler) {
if (bytecode_metadata_helper_.HasBytecode(field.kernel_offset() +
library_kernel_offset_)) {
field.set_has_initializer(true);
return;
}
}
field.set_has_initializer(false);
}
RawLibrary* KernelLoader::LoadLibrary(intptr_t index) {
if (!program_->is_single_program()) {
FATAL(
"Trying to load a concatenated dill file at a time where that is "
"not allowed");
}
// Read library index.
library_kernel_offset_ = library_offset(index);
correction_offset_ = library_kernel_offset_;
intptr_t library_end = library_offset(index + 1);
intptr_t library_size = library_end - library_kernel_offset_;
// NOTE: Since |helper_| is used to load the overall kernel program,
// it's reader's offset is an offset into the overall kernel program.
// Hence, when setting the kernel offsets of field and functions, one
// has to subtract the library's kernel offset from the reader's
// offset.
helper_.SetOffset(library_kernel_offset_);
LibraryHelper library_helper(&helper_);
library_helper.ReadUntilIncluding(LibraryHelper::kCanonicalName);
if (!FLAG_precompiled_mode && !I->should_load_vmservice()) {
StringIndex lib_name_index =
H.CanonicalNameString(library_helper.canonical_name_);
if (H.StringEquals(lib_name_index, kVMServiceIOLibraryUri)) {
// We are not the service isolate and we are not generating an AOT
// snapshot so we skip loading 'dart:vmservice_io'.
skip_vmservice_library_ = library_helper.canonical_name_;
ASSERT(H.IsLibrary(skip_vmservice_library_));
return Library::null();
}
}
Library& library =
Library::Handle(Z, LookupLibrary(library_helper.canonical_name_));
// The Kernel library is external implies that it is already loaded.
ASSERT(!library_helper.IsExternal() || library.Loaded());
if (library.Loaded()) return library.raw();
library_kernel_data_ = helper_.reader_.ExternalDataFromTo(
library_kernel_offset_, library_kernel_offset_ + library_size);