-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
isolate.cc
1439 lines (1290 loc) · 50.4 KB
/
isolate.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) 2012, 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 <memory>
#include <utility>
#include "include/dart_native_api.h"
#include "platform/assert.h"
#include "platform/unicode.h"
#include "vm/bootstrap_natives.h"
#include "vm/class_finalizer.h"
#include "vm/dart.h"
#include "vm/dart_api_impl.h"
#include "vm/dart_api_message.h"
#include "vm/dart_entry.h"
#include "vm/exceptions.h"
#include "vm/hash_table.h"
#include "vm/lockers.h"
#include "vm/longjump.h"
#include "vm/message_handler.h"
#include "vm/message_snapshot.h"
#include "vm/object.h"
#include "vm/object_graph_copy.h"
#include "vm/object_store.h"
#include "vm/port.h"
#include "vm/resolver.h"
#include "vm/service.h"
#include "vm/snapshot.h"
#include "vm/symbols.h"
namespace dart {
DEFINE_NATIVE_ENTRY(Capability_factory, 0, 1) {
ASSERT(
TypeArguments::CheckedHandle(zone, arguments->NativeArgAt(0)).IsNull());
// Keep capability IDs less than 2^53 so web clients of the service
// protocol can process it properly.
//
// See https://github.com/dart-lang/sdk/issues/53081.
uint64_t id = isolate->random()->NextJSInt();
return Capability::New(id);
}
DEFINE_NATIVE_ENTRY(Capability_equals, 0, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(Capability, recv, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Capability, other, arguments->NativeArgAt(1));
return (recv.Id() == other.Id()) ? Bool::True().ptr() : Bool::False().ptr();
}
DEFINE_NATIVE_ENTRY(Capability_get_hashcode, 0, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(Capability, cap, arguments->NativeArgAt(0));
int64_t id = cap.Id();
int32_t hi = static_cast<int32_t>(id >> 32);
int32_t lo = static_cast<int32_t>(id);
int32_t hash = (hi ^ lo) & kSmiMax;
return Smi::New(hash);
}
DEFINE_NATIVE_ENTRY(RawReceivePort_factory, 0, 2) {
ASSERT(
TypeArguments::CheckedHandle(zone, arguments->NativeArgAt(0)).IsNull());
GET_NON_NULL_NATIVE_ARGUMENT(String, debug_name, arguments->NativeArgAt(1));
return isolate->CreateReceivePort(debug_name);
}
DEFINE_NATIVE_ENTRY(RawReceivePort_get_id, 0, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(ReceivePort, port, arguments->NativeArgAt(0));
return Integer::New(port.Id());
}
DEFINE_NATIVE_ENTRY(RawReceivePort_closeInternal, 0, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(ReceivePort, port, arguments->NativeArgAt(0));
Dart_Port id = port.Id();
isolate->CloseReceivePort(port);
return Integer::New(id);
}
DEFINE_NATIVE_ENTRY(RawReceivePort_setActive, 0, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(ReceivePort, port, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Bool, active, arguments->NativeArgAt(1));
isolate->SetReceivePortKeepAliveState(port, active.value());
return Object::null();
}
DEFINE_NATIVE_ENTRY(RawReceivePort_getActive, 0, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(ReceivePort, port, arguments->NativeArgAt(0));
return Bool::Get(port.keep_isolate_alive()).ptr();
}
DEFINE_NATIVE_ENTRY(SendPort_get_id, 0, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(SendPort, port, arguments->NativeArgAt(0));
return Integer::New(port.Id());
}
DEFINE_NATIVE_ENTRY(SendPort_get_hashcode, 0, 1) {
GET_NON_NULL_NATIVE_ARGUMENT(SendPort, port, arguments->NativeArgAt(0));
int64_t id = port.Id();
int32_t hi = static_cast<int32_t>(id >> 32);
int32_t lo = static_cast<int32_t>(id);
int32_t hash = (hi ^ lo) & kSmiMax;
return Smi::New(hash);
}
static bool InSameGroup(Isolate* sender, const SendPort& receiver) {
// Cannot determine whether sender is in same group (yet).
if (sender->origin_id() == ILLEGAL_PORT) return false;
// Only allow arbitrary messages between isolates of the same IG.
return sender->origin_id() == receiver.origin_id();
}
DEFINE_NATIVE_ENTRY(SendPort_sendInternal_, 0, 2) {
GET_NON_NULL_NATIVE_ARGUMENT(SendPort, port, arguments->NativeArgAt(0));
GET_NON_NULL_NATIVE_ARGUMENT(Instance, obj, arguments->NativeArgAt(1));
const Dart_Port destination_port_id = port.Id();
const bool same_group = InSameGroup(isolate, port);
#if defined(DEBUG)
if (same_group) {
ASSERT(PortMap::IsReceiverInThisIsolateGroupOrClosed(destination_port_id,
isolate->group()));
}
#endif
// TODO(turnidge): Throw an exception when the return value is false?
PortMap::PostMessage(WriteMessage(same_group, obj, destination_port_id,
Message::kNormalPriority));
return Object::null();
}
class UntaggedObjectPtrSetTraits {
public:
static bool ReportStats() { return false; }
static const char* Name() { return "UntaggedObjectPtrSetTraits"; }
static bool IsMatch(const ObjectPtr a, const ObjectPtr b) { return a == b; }
static uword Hash(const ObjectPtr obj) { return static_cast<uword>(obj); }
};
#if defined(HASH_IN_OBJECT_HEADER)
// Written to avoid O(elements) pauses that block safepoints. Compare
// object_graph_copy.cc's IdentityMap, which implements something similar
// but with enough differents to make shared code less readable.
class WorkSet {
public:
explicit WorkSet(Thread* thread)
: thread_(thread), list_(GrowableObjectArray::Handle()) {
hash_table_used_ = 0;
hash_table_capacity_ = 32;
hash_table_ = reinterpret_cast<uint32_t*>(
malloc(hash_table_capacity_ * sizeof(uint32_t)));
memset(hash_table_, 0, hash_table_capacity_ * sizeof(uint32_t));
list_ = GrowableObjectArray::New(256);
list_.Add(Object::null_object()); // Id 0 is sentinel.
cursor_ = 1;
}
~WorkSet() { free(hash_table_); }
void Push(const Object& obj) {
intptr_t mask = hash_table_capacity_ - 1;
intptr_t probe = GetHeaderHash(obj.ptr()) & mask;
for (;;) {
intptr_t index = hash_table_[probe];
if (index == 0) {
intptr_t id = list_.Length();
list_.Add(obj);
hash_table_[probe] = id;
break;
}
if (list_.At(index) == obj.ptr()) {
break; // Already present.
}
probe = (probe + 1) & mask;
}
hash_table_used_++;
if (hash_table_used_ * 2 > hash_table_capacity_) {
Rehash(hash_table_capacity_ * 2);
}
}
bool Pop(Object* obj) {
if (cursor_ < list_.Length()) {
*obj = list_.At(cursor_);
cursor_++;
return true;
}
return false;
}
private:
DART_FORCE_INLINE
uint32_t GetHeaderHash(ObjectPtr object) {
uint32_t hash = Object::GetCachedHash(object);
if (hash == 0) {
switch (object->GetClassIdOfHeapObject()) {
case kMintCid:
hash = Mint::Value(static_cast<MintPtr>(object));
// Don't write back: doesn't agree with dart:core's identityHash.
break;
case kDoubleCid:
hash =
bit_cast<uint64_t>(Double::Value(static_cast<DoublePtr>(object)));
// Don't write back: doesn't agree with dart:core's identityHash.
break;
case kOneByteStringCid:
case kTwoByteStringCid:
hash = String::Hash(static_cast<StringPtr>(object));
hash = Object::SetCachedHashIfNotSet(object, hash);
break;
default:
do {
hash = thread_->random()->NextUInt32();
} while (hash == 0 || !Smi::IsValid(hash));
hash = Object::SetCachedHashIfNotSet(object, hash);
break;
}
}
return hash;
}
void Rehash(intptr_t new_capacity) {
hash_table_capacity_ = new_capacity;
hash_table_used_ = 0;
free(hash_table_);
hash_table_ = reinterpret_cast<uint32_t*>(
malloc(hash_table_capacity_ * sizeof(uint32_t)));
for (intptr_t i = 0; i < hash_table_capacity_; i++) {
hash_table_[i] = 0;
if (((i + 1) % kSlotsPerInterruptCheck) == 0) {
thread_->CheckForSafepoint();
}
}
for (intptr_t id = 1; id < list_.Length(); id++) {
ObjectPtr obj = list_.At(id);
intptr_t mask = hash_table_capacity_ - 1;
intptr_t probe = GetHeaderHash(obj) & mask;
for (;;) {
if (hash_table_[probe] == 0) {
hash_table_[probe] = id;
hash_table_used_++;
break;
}
probe = (probe + 1) & mask;
}
if (((id + 1) % kSlotsPerInterruptCheck) == 0) {
thread_->CheckForSafepoint();
}
}
}
Thread* thread_;
uint32_t* hash_table_;
uint32_t hash_table_capacity_;
uint32_t hash_table_used_;
GrowableObjectArray& list_;
intptr_t cursor_;
};
#else // defined(HASH_IN_OBJECT_HEADER)
class WorkSet {
public:
explicit WorkSet(Thread* thread)
: isolate_(thread->isolate()), list_(GrowableObjectArray::Handle()) {
isolate_->set_forward_table_new(new WeakTable());
isolate_->set_forward_table_old(new WeakTable());
list_ = GrowableObjectArray::New(256);
cursor_ = 0;
}
~WorkSet() {
isolate_->set_forward_table_new(nullptr);
isolate_->set_forward_table_old(nullptr);
}
void Push(const Object& obj) {
ASSERT(WeakTable::kNoValue == 0);
if (GetObjectId(obj.ptr()) == 0) {
SetObjectId(obj.ptr(), 1);
list_.Add(obj);
}
}
bool Pop(Object* obj) {
if (cursor_ < list_.Length()) {
*obj = list_.At(cursor_);
cursor_++;
return true;
}
return false;
}
private:
DART_FORCE_INLINE
intptr_t GetObjectId(ObjectPtr object) {
if (object->IsNewObject()) {
return isolate_->forward_table_new()->GetValueExclusive(object);
} else {
return isolate_->forward_table_old()->GetValueExclusive(object);
}
}
DART_FORCE_INLINE
void SetObjectId(ObjectPtr object, intptr_t id) {
if (object->IsNewObject()) {
isolate_->forward_table_new()->SetValueExclusive(object, id);
} else {
isolate_->forward_table_old()->SetValueExclusive(object, id);
}
}
Isolate* isolate_;
GrowableObjectArray& list_;
intptr_t cursor_;
};
#endif // defined(HASH_IN_OBJECT_HEADER)
class MessageValidator : private WorkSet {
public:
explicit MessageValidator(Thread* thread)
: WorkSet(thread),
value_(PassiveObject::Handle()),
class_table_(thread->isolate()->group()->class_table()) {}
ObjectPtr Validate(Thread* thread, const Object& root) {
TIMELINE_DURATION(thread, Isolate, "ValidateMessageObject");
Visit(root.ptr());
Object& current = Object::Handle();
Class& klass = Class::Handle();
while (Pop(¤t)) {
const intptr_t cid = current.GetClassId();
switch (cid) {
case kArrayCid:
case kImmutableArrayCid:
VisitArrayPointers(thread, Array::Cast(current));
break;
case kClosureCid:
VisitClosurePointers(Closure::Cast(current));
break;
case kContextCid:
VisitContextPointers(Context::Cast(current));
break;
case kGrowableObjectArrayCid:
VisitGrowableObjectArrayPointers(GrowableObjectArray::Cast(current));
break;
case kSetCid:
case kConstSetCid:
case kMapCid:
case kConstMapCid:
VisitLinkedHashBasePointers(LinkedHashBase::Cast(current));
break;
case kRecordCid:
VisitRecordPointers(Record::Cast(current));
break;
case kWeakPropertyCid:
VisitWeakPropertyPointers(WeakProperty::Cast(current));
break;
case kWeakReferenceCid:
VisitWeakReferencePointers(WeakReference::Cast(current));
break;
#define MESSAGE_SNAPSHOT_ILLEGAL(type) \
case k##type##Cid: \
return Error(current, "is a " #type, root);
MESSAGE_SNAPSHOT_ILLEGAL(DynamicLibrary)
// TODO(http://dartbug.com/47777): Send and exit support: remove this.
MESSAGE_SNAPSHOT_ILLEGAL(Finalizer)
MESSAGE_SNAPSHOT_ILLEGAL(NativeFinalizer)
MESSAGE_SNAPSHOT_ILLEGAL(MirrorReference)
MESSAGE_SNAPSHOT_ILLEGAL(Pointer)
MESSAGE_SNAPSHOT_ILLEGAL(ReceivePort)
MESSAGE_SNAPSHOT_ILLEGAL(UserTag)
MESSAGE_SNAPSHOT_ILLEGAL(SuspendState)
default:
klass = class_table_->At(cid);
if (klass.is_isolate_unsendable()) {
return Error(
current,
"is unsendable object (see restrictions listed at"
"`SendPort.send()` documentation for more information)",
root);
}
VisitInstancePointers(Instance::Cast(current), cid);
}
thread->CheckForSafepoint();
}
return root.ptr();
}
private:
void VisitArrayPointers(Thread* thread, const Array& array) {
for (intptr_t i = 0, n = array.Length(); i < n; i++) {
Visit(array.At(i));
if (((i + 1) % kSlotsPerInterruptCheck) == 0) {
thread->CheckForSafepoint();
}
}
}
void VisitGrowableObjectArrayPointers(const GrowableObjectArray& list) {
Visit(list.data());
}
void VisitRecordPointers(const Record& record) {
for (intptr_t i = 0, n = record.num_fields(); i < n; i++) {
Visit(record.FieldAt(i));
}
}
void VisitContextPointers(const Context& context) {
Visit(context.parent());
for (intptr_t i = 0, n = context.num_variables(); i < n; i++) {
Visit(context.At(i));
}
}
void VisitLinkedHashBasePointers(const LinkedHashBase& hash) {
Visit(hash.data());
}
void VisitClosurePointers(const Closure& closure) {
Visit(closure.RawContext());
}
void VisitWeakPropertyPointers(const WeakProperty& weak) {
Visit(weak.key());
Visit(weak.value());
}
void VisitWeakReferencePointers(const WeakReference& weak) {
Visit(weak.target());
}
void VisitInstancePointers(const Instance& instance, intptr_t cid) {
ASSERT(cid == kInstanceCid || cid >= kNumPredefinedCids);
const auto bitmap = class_table_->GetUnboxedFieldsMapAt(cid);
intptr_t size = instance.ptr()->untag()->HeapSize();
uword heap_base = instance.ptr()->heap_base();
intptr_t offset = kWordSize;
intptr_t bit = offset >> kCompressedWordSizeLog2;
for (; offset < size; offset += kCompressedWordSize) {
if (!bitmap.Get(bit++)) {
Visit(reinterpret_cast<CompressedObjectPtr*>(
reinterpret_cast<uword>(instance.ptr()->untag()) + offset)
->Decompress(heap_base));
}
}
}
void Visit(ObjectPtr obj) {
if (!obj->IsHeapObject() || obj->untag()->IsCanonical() ||
obj->untag()->IsImmutable()) {
return;
}
switch (obj->untag()->GetClassId()) {
case kTransferableTypedDataCid:
#define CASE(clazz) \
case kTypedData##clazz##Cid: \
case kTypedData##clazz##ViewCid: \
case kExternalTypedData##clazz##Cid: \
case kUnmodifiableTypedData##clazz##ViewCid:
CLASS_LIST_TYPED_DATA(CASE)
#undef CASE
case kByteDataViewCid:
case kUnmodifiableByteDataViewCid:
case kByteBufferCid:
return;
}
value_ = obj;
Push(value_);
}
ObjectPtr Error(const Object& illegal_object,
const char* exception_message,
const Object& root) {
Thread* thread = Thread::Current();
Isolate* isolate = thread->isolate();
Zone* zone = thread->zone();
const Array& args = Array::Handle(zone, Array::New(3));
args.SetAt(0, illegal_object);
args.SetAt(2, String::Handle(
zone, String::NewFormatted(
"%s%s",
FindRetainingPath(
zone, isolate, root, illegal_object,
TraversalRules::kInternalToIsolateGroup),
exception_message)));
const Object& exception = Object::Handle(
zone, Exceptions::Create(Exceptions::kArgumentValue, args));
return UnhandledException::New(Instance::Cast(exception),
StackTrace::Handle(zone));
}
private:
PassiveObject& value_;
ClassTable* class_table_;
};
// TODO(http://dartbug.com/47777): Add support for Finalizers.
DEFINE_NATIVE_ENTRY(Isolate_exit_, 0, 2) {
GET_NATIVE_ARGUMENT(SendPort, port, arguments->NativeArgAt(0));
if (!port.IsNull()) {
GET_NATIVE_ARGUMENT(Instance, obj, arguments->NativeArgAt(1));
const bool same_group = InSameGroup(isolate, port);
#if defined(DEBUG)
if (same_group) {
ASSERT(PortMap::IsReceiverInThisIsolateGroupOrClosed(port.Id(),
isolate->group()));
}
#endif
if (!same_group) {
const auto& error =
String::Handle(String::New("exit with final message is only allowed "
"for isolates in one isolate group."));
Exceptions::ThrowArgumentError(error);
UNREACHABLE();
}
Object& validated_result = Object::Handle(zone);
const Object& msg_obj = Object::Handle(zone, obj.ptr());
{
MessageValidator validator(thread);
validated_result = validator.Validate(thread, obj);
}
// msg_array = [
// <message>,
// <collection-lib-objects-to-rehash>,
// <core-lib-objects-to-rehash>,
// ]
const Array& msg_array = Array::Handle(zone, Array::New(3));
msg_array.SetAt(0, msg_obj);
if (validated_result.IsUnhandledException()) {
Exceptions::PropagateError(Error::Cast(validated_result));
UNREACHABLE();
}
PersistentHandle* handle =
isolate->group()->api_state()->AllocatePersistentHandle();
handle->set_ptr(msg_array);
isolate->bequeath(std::unique_ptr<Bequest>(new Bequest(handle, port.Id())));
}
Thread::Current()->StartUnwindError();
const String& msg =
String::Handle(String::New("isolate terminated by Isolate.exit"));
const UnwindError& error = UnwindError::Handle(UnwindError::New(msg));
error.set_is_user_initiated(true);
Exceptions::PropagateError(error);
UNREACHABLE();
// We will never execute dart code again in this isolate.
return Object::null();
}
class IsolateSpawnState {
public:
IsolateSpawnState(Dart_Port parent_port,
Dart_Port origin_id,
const char* script_url,
PersistentHandle* closure_tuple_handle,
SerializedObjectBuffer* message_buffer,
const char* package_config,
bool paused,
bool errorsAreFatal,
Dart_Port onExit,
Dart_Port onError,
const char* debug_name,
IsolateGroup* group);
IsolateSpawnState(Dart_Port parent_port,
const char* script_url,
const char* package_config,
SerializedObjectBuffer* args_buffer,
SerializedObjectBuffer* message_buffer,
bool paused,
bool errorsAreFatal,
Dart_Port onExit,
Dart_Port onError,
const char* debug_name,
IsolateGroup* group);
~IsolateSpawnState();
Isolate* isolate() const { return isolate_; }
void set_isolate(Isolate* value) { isolate_ = value; }
Dart_Port parent_port() const { return parent_port_; }
Dart_Port origin_id() const { return origin_id_; }
Dart_Port on_exit_port() const { return on_exit_port_; }
Dart_Port on_error_port() const { return on_error_port_; }
const char* script_url() const { return script_url_; }
const char* package_config() const { return package_config_; }
const char* debug_name() const { return debug_name_; }
bool is_spawn_uri() const {
return closure_tuple_handle_ == nullptr; // No closure entrypoint.
}
bool paused() const { return paused_; }
bool errors_are_fatal() const { return errors_are_fatal_; }
Dart_IsolateFlags* isolate_flags() { return &isolate_flags_; }
PersistentHandle* closure_tuple_handle() const {
return closure_tuple_handle_;
}
ObjectPtr ResolveFunction();
ObjectPtr BuildArgs(Thread* thread);
ObjectPtr BuildMessage(Thread* thread);
IsolateGroup* isolate_group() const { return isolate_group_; }
private:
Isolate* isolate_ = nullptr;
Dart_Port parent_port_;
Dart_Port origin_id_ = ILLEGAL_PORT;
Dart_Port on_exit_port_;
Dart_Port on_error_port_;
const char* script_url_;
const char* package_config_;
const char* debug_name_;
PersistentHandle* closure_tuple_handle_ = nullptr;
IsolateGroup* isolate_group_;
std::unique_ptr<Message> serialized_args_;
std::unique_ptr<Message> serialized_message_;
Dart_IsolateFlags isolate_flags_;
bool paused_;
bool errors_are_fatal_;
};
static const char* NewConstChar(const char* chars) {
size_t len = strlen(chars);
char* mem = new char[len + 1];
memmove(mem, chars, len + 1);
return mem;
}
IsolateSpawnState::IsolateSpawnState(Dart_Port parent_port,
Dart_Port origin_id,
const char* script_url,
PersistentHandle* closure_tuple_handle,
SerializedObjectBuffer* message_buffer,
const char* package_config,
bool paused,
bool errors_are_fatal,
Dart_Port on_exit_port,
Dart_Port on_error_port,
const char* debug_name,
IsolateGroup* isolate_group)
: parent_port_(parent_port),
origin_id_(origin_id),
on_exit_port_(on_exit_port),
on_error_port_(on_error_port),
script_url_(script_url),
package_config_(package_config),
debug_name_(debug_name),
closure_tuple_handle_(closure_tuple_handle),
isolate_group_(isolate_group),
serialized_args_(nullptr),
serialized_message_(message_buffer->StealMessage()),
paused_(paused),
errors_are_fatal_(errors_are_fatal) {
ASSERT(closure_tuple_handle_ != nullptr);
auto thread = Thread::Current();
auto isolate = thread->isolate();
// Inherit flags from spawning isolate.
isolate->FlagsCopyTo(isolate_flags());
}
IsolateSpawnState::IsolateSpawnState(Dart_Port parent_port,
const char* script_url,
const char* package_config,
SerializedObjectBuffer* args_buffer,
SerializedObjectBuffer* message_buffer,
bool paused,
bool errors_are_fatal,
Dart_Port on_exit_port,
Dart_Port on_error_port,
const char* debug_name,
IsolateGroup* isolate_group)
: parent_port_(parent_port),
on_exit_port_(on_exit_port),
on_error_port_(on_error_port),
script_url_(script_url),
package_config_(package_config),
debug_name_(debug_name),
isolate_group_(isolate_group),
serialized_args_(args_buffer->StealMessage()),
serialized_message_(message_buffer->StealMessage()),
isolate_flags_(),
paused_(paused),
errors_are_fatal_(errors_are_fatal) {
if (debug_name_ == nullptr) {
debug_name_ = NewConstChar("main");
}
// By default inherit flags from spawning isolate. These can be overridden
// from the calling code.
Isolate::Current()->FlagsCopyTo(isolate_flags());
}
IsolateSpawnState::~IsolateSpawnState() {
delete[] script_url_;
delete[] package_config_;
delete[] debug_name_;
}
ObjectPtr IsolateSpawnState::ResolveFunction() {
Thread* thread = Thread::Current();
auto IG = thread->isolate_group();
Zone* zone = thread->zone();
// Handle spawnUri lookup rules.
// Check whether the root library defines a main function.
const Library& lib =
Library::Handle(zone, IG->object_store()->root_library());
const String& main = String::Handle(zone, String::New("main"));
Function& func = Function::Handle(zone, lib.LookupFunctionAllowPrivate(main));
if (func.IsNull()) {
// Check whether main is reexported from the root library.
const Object& obj = Object::Handle(zone, lib.LookupReExport(main));
if (obj.IsFunction()) {
func ^= obj.ptr();
}
}
if (func.IsNull()) {
const String& msg = String::Handle(
zone,
String::NewFormatted(
"Unable to resolve function 'main' in script '%s'.", script_url()));
return LanguageError::New(msg);
}
return func.ptr();
}
static ObjectPtr DeserializeMessage(Thread* thread, Message* message) {
if (message == nullptr) {
return Object::null();
}
if (message->IsRaw()) {
return Object::RawCast(message->raw_obj());
} else {
return ReadMessage(thread, message);
}
}
ObjectPtr IsolateSpawnState::BuildArgs(Thread* thread) {
const Object& result =
Object::Handle(DeserializeMessage(thread, serialized_args_.get()));
serialized_args_.reset();
return result.ptr();
}
ObjectPtr IsolateSpawnState::BuildMessage(Thread* thread) {
const Object& result =
Object::Handle(DeserializeMessage(thread, serialized_message_.get()));
serialized_message_.reset();
return result.ptr();
}
static void ThrowIsolateSpawnException(const String& message) {
const Array& args = Array::Handle(Array::New(1));
args.SetAt(0, message);
Exceptions::ThrowByType(Exceptions::kIsolateSpawn, args);
}
class SpawnIsolateTask : public ThreadPool::Task {
public:
SpawnIsolateTask(Isolate* parent_isolate,
std::unique_ptr<IsolateSpawnState> state)
: parent_isolate_(parent_isolate), state_(std::move(state)) {
parent_isolate->IncrementSpawnCount();
}
~SpawnIsolateTask() override {
if (parent_isolate_ != nullptr) {
parent_isolate_->DecrementSpawnCount();
}
}
void Run() override {
const char* name = state_->debug_name();
ASSERT(name != nullptr);
auto group = state_->isolate_group();
if (group == nullptr) {
RunHeavyweight(name);
} else {
RunLightweight(name);
}
}
void RunHeavyweight(const char* name) {
// The create isolate group callback is mandatory. If not provided we
// cannot spawn isolates.
auto create_group_callback = Isolate::CreateGroupCallback();
if (create_group_callback == nullptr) {
FailedSpawn("Isolate spawn is not supported by this Dart embedder\n");
return;
}
char* error = nullptr;
// Make a copy of the state's isolate flags and hand it to the callback.
Dart_IsolateFlags api_flags = *(state_->isolate_flags());
// Inherit the system isolate property to work around issues with
// --pause-isolates-on-start and --pause-isolates-on-exit impacting macro
// generation isolates which are spawned by the kernel-service
// (see https://github.com/dart-lang/sdk/issues/54729 for details).
//
// This flag isn't inherited in the case that the main isolate is marked as
// a system isolate in the standalone VM using the
// --mark-main-isolate-as-system-isolate flag as it's currently used to
// hide test runner implementation details and spawns isolates that should
// be debuggable as non-system isolates.
//
// TODO(bkonyi): revisit this decision, see
// https://github.com/dart-lang/sdk/issues/54736 for the tracking issue.
const bool is_parent_main_isolate =
strcmp(parent_isolate_->name(), "main") == 0;
api_flags.is_system_isolate =
api_flags.is_system_isolate && !is_parent_main_isolate;
Dart_Isolate isolate =
(create_group_callback)(state_->script_url(), name, nullptr,
state_->package_config(), &api_flags,
parent_isolate_->init_callback_data(), &error);
parent_isolate_->DecrementSpawnCount();
parent_isolate_ = nullptr;
if (isolate == nullptr) {
FailedSpawn(error, /*has_current_isolate=*/false);
free(error);
return;
}
Dart_EnterIsolate(isolate);
Run(reinterpret_cast<Isolate*>(isolate));
}
void RunLightweight(const char* name) {
// The create isolate initialize callback is mandatory.
auto initialize_callback = Isolate::InitializeCallback();
if (initialize_callback == nullptr) {
FailedSpawn(
"Lightweight isolate spawn is not supported by this Dart embedder\n",
/*has_current_isolate=*/false);
return;
}
char* error = nullptr;
auto group = state_->isolate_group();
Isolate* isolate = CreateWithinExistingIsolateGroup(group, name, &error);
parent_isolate_->DecrementSpawnCount();
parent_isolate_ = nullptr;
if (isolate == nullptr) {
FailedSpawn(error, /*has_current_isolate=*/false);
free(error);
return;
}
void* child_isolate_data = nullptr;
const bool success = initialize_callback(&child_isolate_data, &error);
if (!success) {
FailedSpawn(error);
Dart_ShutdownIsolate();
free(error);
return;
}
isolate->set_init_callback_data(child_isolate_data);
Run(isolate);
}
private:
void Run(Isolate* child) {
if (!EnsureIsRunnable(child)) {
Dart_ShutdownIsolate();
return;
}
state_->set_isolate(child);
if (state_->origin_id() != ILLEGAL_PORT) {
// origin_id is set to parent isolate main port id when spawning via
// spawnFunction.
child->set_origin_id(state_->origin_id());
}
bool success = true;
{
auto thread = Thread::Current();
TransitionNativeToVM transition(thread);
StackZone zone(thread);
HandleScope hs(thread);
success = EnqueueEntrypointInvocationAndNotifySpawner(thread);
}
if (!success) {
state_ = nullptr;
Dart_ShutdownIsolate();
return;
}
// All preconditions are met for this to always succeed.
char* error = nullptr;
if (!Dart_RunLoopAsync(state_->errors_are_fatal(), state_->on_error_port(),
state_->on_exit_port(), &error)) {
FATAL("Dart_RunLoopAsync() failed: %s. Please file a Dart VM bug report.",
error);
}
}
bool EnsureIsRunnable(Isolate* child) {
// We called out to the embedder to create/initialize a new isolate. The
// embedder callback successfully did so. It is now our responsibility to
// run the isolate.
// If the isolate was not marked as runnable, we'll do so here and run it.
if (!child->is_runnable()) {
const char* error = child->MakeRunnable();
if (error != nullptr) {
FailedSpawn(error);
return false;
}
}
ASSERT(child->is_runnable());
return true;
}
bool EnqueueEntrypointInvocationAndNotifySpawner(Thread* thread) {
auto isolate = thread->isolate();
auto zone = thread->zone();
const bool is_spawn_uri = state_->is_spawn_uri();
// Step 1) Resolve the entrypoint function.
auto& entrypoint_closure = Closure::Handle(zone);
if (state_->closure_tuple_handle() != nullptr) {
const auto& result = Object::Handle(
zone,
ReadObjectGraphCopyMessage(thread, state_->closure_tuple_handle()));
if (result.IsError()) {
ReportError(
"Failed to deserialize the passed entrypoint to the new isolate.");
return false;
}
entrypoint_closure = Closure::RawCast(result.ptr());
} else {
const auto& result = Object::Handle(zone, state_->ResolveFunction());
if (result.IsError()) {
ASSERT(is_spawn_uri);
ReportError("Failed to resolve entrypoint function.");
return false;
}
ASSERT(result.IsFunction());
auto& func = Function::Handle(zone, Function::Cast(result).ptr());
func = func.ImplicitClosureFunction();
entrypoint_closure = func.ImplicitStaticClosure();
}
// Step 2) Enqueue delayed invocation of entrypoint callback.
const auto& args_obj = Object::Handle(zone, state_->BuildArgs(thread));
if (args_obj.IsError()) {
ReportError(
"Failed to deserialize the passed arguments to the new isolate.");
return false;
}
ASSERT(args_obj.IsNull() || args_obj.IsInstance());
const auto& message_obj =
Object::Handle(zone, state_->BuildMessage(thread));
if (message_obj.IsError()) {
ReportError(
"Failed to deserialize the passed arguments to the new isolate.");
return false;
}
ASSERT(message_obj.IsNull() || message_obj.IsInstance());
const Array& args = Array::Handle(zone, Array::New(4));
args.SetAt(0, entrypoint_closure);
args.SetAt(1, args_obj);
args.SetAt(2, message_obj);
args.SetAt(3, is_spawn_uri ? Bool::True() : Bool::False());
const auto& lib = Library::Handle(zone, Library::IsolateLibrary());
const auto& entry_name = String::Handle(zone, String::New("_startIsolate"));
const auto& entry_point =
Function::Handle(zone, lib.LookupFunctionAllowPrivate(entry_name));
ASSERT(entry_point.IsFunction() && !entry_point.IsNull());
const auto& result =
Object::Handle(zone, DartEntry::InvokeFunction(entry_point, args));
if (result.IsError()) {
ReportError("Failed to enqueue delayed entrypoint invocation.");
return false;
}
// Step 3) Pause the isolate if required & Notify parent isolate about
// isolate creation.
const auto& capabilities = Array::Handle(zone, Array::New(2));
auto& capability = Capability::Handle(zone);
capability = Capability::New(isolate->pause_capability());
capabilities.SetAt(0, capability);