-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathisolate.cc
3944 lines (3523 loc) · 134 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) 2013, 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 <utility>
#include "vm/isolate.h"
#include "include/dart_api.h"
#include "include/dart_native_api.h"
#include "platform/assert.h"
#include "platform/atomic.h"
#include "platform/growable_array.h"
#include "platform/text_buffer.h"
#include "vm/canonical_tables.h"
#include "vm/class_finalizer.h"
#include "vm/code_observers.h"
#include "vm/compiler/jit/compiler.h"
#include "vm/dart_api_message.h"
#include "vm/dart_api_state.h"
#include "vm/dart_entry.h"
#include "vm/debugger.h"
#include "vm/deopt_instructions.h"
#include "vm/dispatch_table.h"
#include "vm/ffi_callback_metadata.h"
#include "vm/flags.h"
#include "vm/heap/heap.h"
#include "vm/heap/pointer_block.h"
#include "vm/heap/safepoint.h"
#include "vm/heap/verifier.h"
#include "vm/image_snapshot.h"
#include "vm/isolate_reload.h"
#include "vm/kernel_isolate.h"
#include "vm/lockers.h"
#include "vm/log.h"
#include "vm/message_handler.h"
#include "vm/message_snapshot.h"
#include "vm/object.h"
#include "vm/object_id_ring.h"
#include "vm/object_store.h"
#include "vm/os_thread.h"
#include "vm/profiler.h"
#include "vm/reusable_handles.h"
#include "vm/reverse_pc_lookup_cache.h"
#include "vm/service.h"
#include "vm/service_event.h"
#include "vm/service_isolate.h"
#include "vm/simulator.h"
#include "vm/stack_frame.h"
#include "vm/stub_code.h"
#include "vm/symbols.h"
#include "vm/tags.h"
#include "vm/thread.h"
#include "vm/thread_interrupter.h"
#include "vm/thread_registry.h"
#include "vm/timeline.h"
#include "vm/visitor.h"
#if !defined(DART_PRECOMPILED_RUNTIME)
#include "vm/compiler/assembler/assembler.h"
#include "vm/compiler/stub_code_compiler.h"
#endif
namespace dart {
DECLARE_FLAG(bool, print_metrics);
DECLARE_FLAG(bool, trace_service);
DECLARE_FLAG(bool, trace_shutdown);
DECLARE_FLAG(bool, warn_on_pause_with_no_debugger);
DECLARE_FLAG(int, old_gen_growth_time_ratio);
// Reload flags.
DECLARE_FLAG(int, reload_every);
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
DECLARE_FLAG(bool, check_reloaded);
DECLARE_FLAG(bool, reload_every_back_off);
DECLARE_FLAG(bool, trace_reload);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
static void DeterministicModeHandler(bool value) {
if (value) {
FLAG_background_compilation = false; // Timing dependent.
FLAG_concurrent_mark = false; // Timing dependent.
FLAG_concurrent_sweep = false; // Timing dependent.
FLAG_scavenger_tasks = 0; // Timing dependent.
FLAG_old_gen_growth_time_ratio = 0; // Timing dependent.
FLAG_random_seed = 0x44617274; // "Dart"
}
}
DEFINE_FLAG_HANDLER(DeterministicModeHandler,
deterministic,
"Enable deterministic mode.");
DEFINE_FLAG(bool,
disable_thread_pool_limit,
false,
"Disables the limit of the thread pool (simulates custom embedder "
"with custom message handler on unlimited number of threads).");
// Quick access to the locally defined thread() and isolate() methods.
#define T (thread())
#define I (isolate())
#define IG (isolate_group())
#if defined(DEBUG)
// Helper class to ensure that a live origin_id is never reused
// and assigned to an isolate.
class VerifyOriginId : public IsolateVisitor {
public:
explicit VerifyOriginId(Dart_Port id) : id_(id) {}
void VisitIsolate(Isolate* isolate) { ASSERT(isolate->group()->id() != id_); }
private:
Dart_Port id_;
DISALLOW_COPY_AND_ASSIGN(VerifyOriginId);
};
#endif
static std::unique_ptr<Message> SerializeMessage(Dart_Port dest_port,
const Instance& obj) {
return WriteMessage(/* same_group */ false, obj, dest_port,
Message::kNormalPriority);
}
static std::unique_ptr<Message> SerializeMessage(Zone* zone,
Dart_Port dest_port,
Dart_CObject* obj) {
return WriteApiMessage(zone, obj, dest_port, Message::kNormalPriority);
}
void IsolateGroupSource::add_loaded_blob(
Zone* zone,
const ExternalTypedData& external_typed_data) {
Array& loaded_blobs = Array::Handle();
bool saved_external_typed_data = false;
if (loaded_blobs_ != nullptr) {
loaded_blobs = loaded_blobs_;
// Walk the array, and (if stuff was removed) compact and reuse the space.
// Note that the space has to be compacted as the ordering is important.
WeakProperty& weak_property = WeakProperty::Handle();
WeakProperty& weak_property_tmp = WeakProperty::Handle();
ExternalTypedData& existing_entry = ExternalTypedData::Handle(zone);
intptr_t next_entry_index = 0;
for (intptr_t i = 0; i < loaded_blobs.Length(); i++) {
weak_property ^= loaded_blobs.At(i);
if (weak_property.key() != ExternalTypedData::null()) {
if (i != next_entry_index) {
existing_entry = ExternalTypedData::RawCast(weak_property.key());
weak_property_tmp ^= loaded_blobs.At(next_entry_index);
weak_property_tmp.set_key(existing_entry);
}
next_entry_index++;
}
}
if (next_entry_index < loaded_blobs.Length()) {
// There's now space to re-use.
weak_property ^= loaded_blobs.At(next_entry_index);
weak_property.set_key(external_typed_data);
next_entry_index++;
saved_external_typed_data = true;
}
if (next_entry_index < loaded_blobs.Length()) {
ExternalTypedData& nullExternalTypedData =
ExternalTypedData::Handle(zone);
while (next_entry_index < loaded_blobs.Length()) {
// Null out any extra spaces.
weak_property ^= loaded_blobs.At(next_entry_index);
weak_property.set_key(nullExternalTypedData);
next_entry_index++;
}
}
}
if (!saved_external_typed_data) {
const WeakProperty& weak_property =
WeakProperty::Handle(WeakProperty::New(Heap::kOld));
weak_property.set_key(external_typed_data);
intptr_t length = loaded_blobs.IsNull() ? 0 : loaded_blobs.Length();
Array& new_array =
Array::Handle(Array::Grow(loaded_blobs, length + 1, Heap::kOld));
new_array.SetAt(length, weak_property);
loaded_blobs_ = new_array.ptr();
}
num_blob_loads_++;
}
void IdleTimeHandler::InitializeWithHeap(Heap* heap) {
MutexLocker ml(&mutex_);
ASSERT(heap_ == nullptr && heap != nullptr);
heap_ = heap;
}
bool IdleTimeHandler::ShouldCheckForIdle() {
MutexLocker ml(&mutex_);
return idle_start_time_ > 0 && FLAG_idle_timeout_micros != 0 &&
disabled_counter_ == 0;
}
void IdleTimeHandler::UpdateStartIdleTime() {
MutexLocker ml(&mutex_);
if (disabled_counter_ == 0) {
idle_start_time_ = OS::GetCurrentMonotonicMicros();
}
}
bool IdleTimeHandler::ShouldNotifyIdle(int64_t* expiry) {
const int64_t now = OS::GetCurrentMonotonicMicros();
MutexLocker ml(&mutex_);
if (idle_start_time_ > 0 && disabled_counter_ == 0) {
const int64_t expiry_time = idle_start_time_ + FLAG_idle_timeout_micros;
if (expiry_time < now) {
idle_start_time_ = 0;
return true;
}
}
*expiry = now + FLAG_idle_timeout_micros;
return false;
}
void IdleTimeHandler::NotifyIdle(int64_t deadline) {
{
MutexLocker ml(&mutex_);
disabled_counter_++;
}
if (heap_ != nullptr) {
heap_->NotifyIdle(deadline);
}
{
MutexLocker ml(&mutex_);
disabled_counter_--;
idle_start_time_ = 0;
}
}
void IdleTimeHandler::NotifyIdleUsingDefaultDeadline() {
const int64_t now = OS::GetCurrentMonotonicMicros();
NotifyIdle(now + FLAG_idle_duration_micros);
}
DisableIdleTimerScope::DisableIdleTimerScope(IdleTimeHandler* handler)
: handler_(handler) {
if (handler_ != nullptr) {
MutexLocker ml(&handler_->mutex_);
++handler_->disabled_counter_;
handler_->idle_start_time_ = 0;
}
}
DisableIdleTimerScope::~DisableIdleTimerScope() {
if (handler_ != nullptr) {
MutexLocker ml(&handler_->mutex_);
--handler_->disabled_counter_;
ASSERT(handler_->disabled_counter_ >= 0);
}
}
class FinalizeWeakPersistentHandlesVisitor : public HandleVisitor {
public:
explicit FinalizeWeakPersistentHandlesVisitor(IsolateGroup* isolate_group)
: HandleVisitor(Thread::Current()), isolate_group_(isolate_group) {}
void VisitHandle(uword addr) override {
auto handle = reinterpret_cast<FinalizablePersistentHandle*>(addr);
handle->UpdateUnreachable(isolate_group_);
}
private:
IsolateGroup* isolate_group_;
DISALLOW_COPY_AND_ASSIGN(FinalizeWeakPersistentHandlesVisitor);
};
void MutatorThreadPool::OnEnterIdleLocked(MutexLocker* ml, Worker* worker) {
if (FLAG_idle_timeout_micros == 0) return;
// If the isolate has not started running application code yet, we ignore the
// idle time.
if (!isolate_group_->initial_spawn_successful()) return;
int64_t idle_expiry = 0;
// Obtain the idle time we should wait.
if (isolate_group_->idle_time_handler()->ShouldNotifyIdle(&idle_expiry)) {
MutexUnlocker mls(ml);
NotifyIdle();
return;
}
// Avoid shutdown having to wait for the timeout to expire.
if (ShuttingDownLocked()) return;
// Wait for the recommended idle timeout.
// We can be woken up because of a), b) or c)
const auto result =
worker->Sleep(idle_expiry - OS::GetCurrentMonotonicMicros());
// a) If there are new tasks we have to run them.
if (TasksWaitingToRunLocked()) return;
// b) If the thread pool is shutting down we're done.
if (ShuttingDownLocked()) return;
// c) We timed out and should run the idle notifier.
if (result == Monitor::kTimedOut &&
isolate_group_->idle_time_handler()->ShouldNotifyIdle(&idle_expiry)) {
MutexUnlocker mls(ml);
NotifyIdle();
return;
}
// There must've been another thread doing active work in the meantime.
// If that thread becomes idle and is the last idle thread it will run this
// code again.
}
void MutatorThreadPool::NotifyIdle() {
EnterIsolateGroupScope isolate_group_scope(isolate_group_);
isolate_group_->idle_time_handler()->NotifyIdleUsingDefaultDeadline();
}
IsolateGroup::IsolateGroup(std::shared_ptr<IsolateGroupSource> source,
void* embedder_data,
ObjectStore* object_store,
Dart_IsolateFlags api_flags,
bool is_vm_isolate)
: class_table_(nullptr),
cached_class_table_table_(nullptr),
object_store_(object_store),
class_table_allocator_(),
is_vm_isolate_(is_vm_isolate),
embedder_data_(embedder_data),
thread_pool_(),
isolates_lock_(new SafepointRwLock()),
isolates_(),
start_time_micros_(OS::GetCurrentMonotonicMicros()),
is_system_isolate_group_(source->flags.is_system_isolate),
random_(),
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
last_reload_timestamp_(OS::GetCurrentTimeMillis()),
reload_every_n_stack_overflow_checks_(FLAG_reload_every),
#endif
source_(std::move(source)),
api_state_(new ApiState()),
thread_registry_(new ThreadRegistry()),
safepoint_handler_(new SafepointHandler(this)),
store_buffer_(new StoreBuffer()),
heap_(nullptr),
saved_unlinked_calls_(Array::null()),
initial_field_table_(new FieldTable(/*isolate=*/nullptr)),
shared_initial_field_table_(new FieldTable(/*isolate=*/nullptr,
/*isolate_group=*/nullptr)),
shared_field_table_(new FieldTable(/*isolate=*/nullptr, this)),
isolate_group_flags_(),
#if !defined(DART_PRECOMPILED_RUNTIME)
background_compiler_(new BackgroundCompiler(this)),
#endif
symbols_mutex_(),
type_canonicalization_mutex_(),
type_arguments_canonicalization_mutex_(),
subtype_test_cache_mutex_(),
megamorphic_table_mutex_(),
type_feedback_mutex_(),
patchable_call_mutex_(),
constant_canonicalization_mutex_(),
kernel_data_lib_cache_mutex_(),
kernel_data_class_cache_mutex_(),
kernel_constants_mutex_(),
field_list_mutex_(),
boxed_field_list_(GrowableObjectArray::null()),
program_lock_(new SafepointRwLock(SafepointLevel::kGCAndDeopt)),
active_mutators_monitor_(new Monitor()),
max_active_mutators_(Scavenger::MaxMutatorThreadCount()),
#if !defined(PRODUCT)
debugger_(new GroupDebugger(this)),
#endif
cache_mutex_(),
handler_info_cache_(),
catch_entry_moves_cache_() {
FlagsCopyFrom(api_flags);
if (!is_vm_isolate) {
intptr_t max_worker_threads;
if (FLAG_disable_thread_pool_limit) {
max_worker_threads = 0;
} else {
// There needs to be at least one more thread than active mutators slots
// so that there is a thread waiting in IncreaseMutatorCount (instead of
// unscheduled task sitting in the thread pool's queue) to eventually
// timeout and trigger StealActiveMutators.
max_worker_threads = Scavenger::MaxMutatorThreadCount() + 2;
}
thread_pool_.reset(new MutatorThreadPool(this, max_worker_threads));
}
{
WriteRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
// Keep isolate 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.
id_ = isolate_group_random_->NextJSInt();
}
heap_walk_class_table_ = class_table_ =
new ClassTable(&class_table_allocator_);
cached_class_table_table_.store(class_table_->table());
memset(&native_assets_api_, 0, sizeof(NativeAssetsApi));
}
IsolateGroup::IsolateGroup(std::shared_ptr<IsolateGroupSource> source,
void* embedder_data,
Dart_IsolateFlags api_flags,
bool is_vm_isolate)
: IsolateGroup(source,
embedder_data,
new ObjectStore(),
api_flags,
is_vm_isolate) {
if (object_store() != nullptr) {
object_store()->InitStubs();
}
}
IsolateGroup::~IsolateGroup() {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
RELEASE_ASSERT(group_reload_context_ == nullptr);
RELEASE_ASSERT(program_reload_context_ == nullptr);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
// Ensure we destroy the heap before the other members.
heap_ = nullptr;
ASSERT(old_marking_stack_ == nullptr);
ASSERT(new_marking_stack_ == nullptr);
ASSERT(deferred_marking_stack_ == nullptr);
if (obfuscation_map_ != nullptr) {
for (intptr_t i = 0; obfuscation_map_[i] != nullptr; i++) {
delete[] obfuscation_map_[i];
}
delete[] obfuscation_map_;
}
class_table_allocator_.Free(class_table_);
if (heap_walk_class_table_ != class_table_) {
class_table_allocator_.Free(heap_walk_class_table_);
}
#if !defined(PRODUCT)
delete debugger_;
debugger_ = nullptr;
#endif
}
void IsolateGroup::RegisterIsolate(Isolate* isolate) {
SafepointWriteRwLocker ml(Thread::Current(), isolates_lock_.get());
ASSERT(isolates_lock_->IsCurrentThreadWriter());
if (isolates_.IsEmpty()) {
interrupt_port_ = isolate->main_port();
}
isolates_.Append(isolate);
isolate_count_++;
}
bool IsolateGroup::ContainsOnlyOneIsolate() {
SafepointReadRwLocker ml(Thread::Current(), isolates_lock_.get());
// We do allow 0 here as well, because the background compiler might call
// this method while the mutator thread is in shutdown procedure and
// unregistered itself already.
return isolate_count_ == 0 || isolate_count_ == 1;
}
void IsolateGroup::UnregisterIsolate(Isolate* isolate) {
SafepointWriteRwLocker ml(Thread::Current(), isolates_lock_.get());
isolates_.Remove(isolate);
if (isolates_.IsEmpty()) {
interrupt_port_ = ILLEGAL_PORT;
} else {
interrupt_port_ = isolates_.First()->main_port();
}
}
bool IsolateGroup::UnregisterIsolateDecrementCount() {
SafepointWriteRwLocker ml(Thread::Current(), isolates_lock_.get());
isolate_count_--;
return isolate_count_ == 0;
}
void IsolateGroup::CreateHeap(bool is_vm_isolate,
bool is_service_or_kernel_isolate) {
Heap::Init(this, is_vm_isolate,
is_vm_isolate
? 0 // New gen size 0; VM isolate should only allocate in old.
: FLAG_new_gen_semi_max_size * MBInWords,
(is_service_or_kernel_isolate ? kDefaultMaxOldGenHeapSize
: FLAG_old_gen_heap_size) *
MBInWords);
#define ISOLATE_GROUP_METRIC_CONSTRUCTORS(type, variable, name, unit) \
metric_##variable##_.InitInstance(this, name, nullptr, Metric::unit);
ISOLATE_GROUP_METRIC_LIST(ISOLATE_GROUP_METRIC_CONSTRUCTORS)
#undef ISOLATE_GROUP_METRIC_CONSTRUCTORS
}
void IsolateGroup::Shutdown() {
char* name = nullptr;
// We retrieve the flag value once to avoid the compiler complaining about the
// possibly uninitialized value of name, as the compiler is unaware that when
// the flag variable is non-const, it is set once during VM initialization and
// never changed after, and that modification never runs concurrently with
// this method.
const bool trace_shutdown = FLAG_trace_shutdown;
if (trace_shutdown) {
name = Utils::StrDup(source()->name);
OS::PrintErr("[+%" Pd64 "ms] SHUTDOWN: Shutdown starting for group %s\n",
Dart::UptimeMillis(), name);
}
// Ensure to join all threads before waiting for pending GC tasks (the thread
// pool can trigger idle notification, which can start new GC tasks).
//
// (The vm-isolate doesn't have a thread pool.)
if (!is_vm_isolate_) {
ASSERT(thread_pool_ != nullptr);
thread_pool_->Shutdown();
thread_pool_.reset();
}
{
MonitorLocker ml(Isolate::isolate_creation_monitor_);
Isolate::pending_shutdowns_++;
}
// Needs to happen before starting to destroy the heap so helper tasks like
// the SampleBlockProcessor don't try to enter the group during this
// tear-down.
UnregisterIsolateGroup(this);
// Wait for any pending GC tasks.
if (heap_ != nullptr) {
// Wait for any concurrent GC tasks to finish before shutting down.
// TODO(rmacnak): Interrupt tasks for faster shutdown.
PageSpace* old_space = heap_->old_space();
MonitorLocker ml(old_space->tasks_lock());
while (old_space->tasks() > 0) {
ml.Wait();
}
// Needs to happen before ~PageSpace so TLS and the thread registry are
// still valid.
old_space->AbandonMarkingForShutdown();
}
// If the creation of the isolate group (or the first isolate within the
// isolate group) failed, we do not invoke the cleanup callback (the
// embedder is responsible for handling the creation error).
if (initial_spawn_successful_ && !is_vm_isolate_) {
auto group_shutdown_callback = Isolate::GroupCleanupCallback();
if (group_shutdown_callback != nullptr) {
group_shutdown_callback(embedder_data());
}
}
delete this;
// After this isolate group has died we might need to notify a pending
// `Dart_Cleanup()` call.
{
if (trace_shutdown) {
OS::PrintErr("[+%" Pd64
"ms] SHUTDOWN: Notifying "
"isolate group shutdown (%s)\n",
Dart::UptimeMillis(), name);
}
MonitorLocker ml(Isolate::isolate_creation_monitor_);
Isolate::pending_shutdowns_--;
if (Isolate::pending_shutdowns_ == 0) {
ml.Notify();
}
if (trace_shutdown) {
OS::PrintErr("[+%" Pd64
"ms] SHUTDOWN: Done Notifying "
"isolate group shutdown (%s)\n",
Dart::UptimeMillis(), name);
}
}
if (trace_shutdown) {
OS::PrintErr("[+%" Pd64 "ms] SHUTDOWN: Done shutdown for group %s\n",
Dart::UptimeMillis(), name);
free(name);
}
}
void IsolateGroup::set_heap(std::unique_ptr<Heap> heap) {
idle_time_handler_.InitializeWithHeap(heap.get());
heap_ = std::move(heap);
}
void IsolateGroup::set_saved_unlinked_calls(const Array& saved_unlinked_calls) {
saved_unlinked_calls_ = saved_unlinked_calls.ptr();
}
static constexpr intptr_t kActiveMutatorPreemptionTimeout = 120;
void IsolateGroup::IncreaseMutatorCount(Thread* thread,
bool is_nested_reenter,
bool was_stolen) {
// If the mutator was temporarily blocked on a worker thread, we have to
// unblock the worker thread again.
if (is_nested_reenter || was_stolen) {
thread_pool()->MarkCurrentWorkerAsUnBlocked();
}
// Prevent too many mutators from entering the isolate group to avoid
// pathological behavior where many threads are fighting for obtaining TLABs.
{
// NOTE: This is performance critical code, we should avoid monitors and use
// std::atomics in the fast case (where active_mutators <
// max_active_mutators) and only use monitors in the uncommon case.
MonitorLocker ml(active_mutators_monitor_.get());
ASSERT(active_mutators_ <= max_active_mutators_);
while (active_mutators_ == max_active_mutators_) {
waiting_mutators_++;
bool timed_out = false;
if (has_timeout_waiter_) {
if (was_stolen) {
ml.WaitWithSafepointCheck(thread);
} else {
ml.Wait();
}
} else {
has_timeout_waiter_ = true;
if (was_stolen) {
timed_out = ml.WaitWithSafepointCheck(
thread, kActiveMutatorPreemptionTimeout) ==
Monitor::kTimedOut;
} else {
timed_out =
ml.Wait(kActiveMutatorPreemptionTimeout) == Monitor::kTimedOut;
}
has_timeout_waiter_ = false;
}
waiting_mutators_--;
if (timed_out) {
active_mutators_ -=
thread_registry()->StealActiveMutators(thread_pool());
ASSERT(active_mutators_ >= 0);
}
}
active_mutators_++;
// StealActiveMutators may cause multiple slots to become available, but
// does not do a NotifyAll to prevent the case of thousands of threads
// waking up to claim a ~dozen slots, so we keep notifying while there are
// both available slots and waiters.
if ((active_mutators_ != max_active_mutators_) && (waiting_mutators_ > 0)) {
ml.Notify();
}
}
}
void IsolateGroup::DecreaseMutatorCount(Isolate* mutator, bool is_nested_exit) {
ASSERT(mutator->group() == this);
// If the mutator thread has an active stack and runs on our thread pool we
// will mark the worker as blocked, thereby possibly spawning a new worker for
// pending tasks (if there are any).
if (is_nested_exit) {
ASSERT(mutator->mutator_thread() != nullptr);
thread_pool()->MarkCurrentWorkerAsBlocked();
}
{
// NOTE: This is performance critical code, we should avoid monitors and use
// std::atomics in the fast case (where active_mutators <
// max_active_mutators) and only use monitors in the uncommon case.
MonitorLocker ml(active_mutators_monitor_.get());
ASSERT(active_mutators_ <= max_active_mutators_);
ASSERT(active_mutators_ > 0);
active_mutators_--;
if (waiting_mutators_ > 0) {
ml.Notify();
}
}
}
#ifndef PRODUCT
void IsolateGroup::PrintJSON(JSONStream* stream, bool ref) {
JSONObject jsobj(stream);
PrintToJSONObject(&jsobj, ref);
}
void IsolateGroup::PrintToJSONObject(JSONObject* jsobj, bool ref) {
jsobj->AddProperty("type", (ref ? "@IsolateGroup" : "IsolateGroup"));
jsobj->AddServiceId(ISOLATE_GROUP_SERVICE_ID_FORMAT_STRING, id());
jsobj->AddProperty("name", source()->script_uri);
jsobj->AddPropertyF("number", "%" Pu64 "", id());
jsobj->AddProperty("isSystemIsolateGroup", is_system_isolate_group());
if (ref) {
return;
}
{
JSONArray isolate_array(jsobj, "isolates");
for (auto it = isolates_.Begin(); it != isolates_.End(); ++it) {
Isolate* isolate = *it;
isolate_array.AddValue(isolate, /*ref=*/true);
}
}
}
void IsolateGroup::PrintMemoryUsageJSON(JSONStream* stream) {
int64_t used = heap()->TotalUsedInWords();
int64_t capacity = heap()->TotalCapacityInWords();
int64_t external_used = heap()->TotalExternalInWords();
JSONObject jsobj(stream);
// This is the same "MemoryUsage" that the isolate-specific "getMemoryUsage"
// rpc method returns.
jsobj.AddProperty("type", "MemoryUsage");
jsobj.AddProperty64("heapUsage", used * kWordSize);
jsobj.AddProperty64("heapCapacity", capacity * kWordSize);
jsobj.AddProperty64("externalUsage", external_used * kWordSize);
}
#endif
void IsolateGroup::ForEach(std::function<void(IsolateGroup*)> action) {
ReadRwLocker wl(Thread::Current(), isolate_groups_rwlock_);
for (auto isolate_group : *isolate_groups_) {
action(isolate_group);
}
}
void IsolateGroup::RunWithIsolateGroup(
Dart_Port id,
std::function<void(IsolateGroup*)> action,
std::function<void()> not_found) {
ReadRwLocker wl(Thread::Current(), isolate_groups_rwlock_);
for (auto isolate_group : *isolate_groups_) {
if (isolate_group->id() == id) {
action(isolate_group);
return;
}
}
not_found();
}
void IsolateGroup::RegisterIsolateGroup(IsolateGroup* isolate_group) {
WriteRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
isolate_groups_->Append(isolate_group);
}
void IsolateGroup::UnregisterIsolateGroup(IsolateGroup* isolate_group) {
WriteRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
isolate_groups_->Remove(isolate_group);
}
bool IsolateGroup::HasApplicationIsolateGroups() {
ReadRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
for (auto group : *isolate_groups_) {
if (!IsolateGroup::IsSystemIsolateGroup(group)) {
return true;
}
}
return false;
}
bool IsolateGroup::HasOnlyVMIsolateGroup() {
ReadRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
for (auto group : *isolate_groups_) {
if (!group->is_vm_isolate()) {
return false;
}
}
return true;
}
void IsolateGroup::Init() {
ASSERT(isolate_groups_rwlock_ == nullptr);
isolate_groups_rwlock_ = new RwLock();
ASSERT(isolate_groups_ == nullptr);
isolate_groups_ = new IntrusiveDList<IsolateGroup>();
isolate_group_random_ = new Random();
}
void IsolateGroup::Cleanup() {
delete isolate_group_random_;
isolate_group_random_ = nullptr;
delete isolate_groups_rwlock_;
isolate_groups_rwlock_ = nullptr;
ASSERT(isolate_groups_->IsEmpty());
delete isolate_groups_;
isolate_groups_ = nullptr;
}
bool IsolateVisitor::IsSystemIsolate(Isolate* isolate) const {
return Isolate::IsSystemIsolate(isolate);
}
Bequest::~Bequest() {
if (handle_ == nullptr) {
return;
}
IsolateGroup* isolate_group = IsolateGroup::Current();
CHECK_ISOLATE_GROUP(isolate_group);
NoSafepointScope no_safepoint_scope;
ApiState* state = isolate_group->api_state();
ASSERT(state != nullptr);
state->FreePersistentHandle(handle_);
}
void IsolateGroup::RegisterClass(const Class& cls) {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
if (IsReloading()) {
program_reload_context()->RegisterClass(cls);
return;
}
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
if (cls.IsTopLevel()) {
class_table()->RegisterTopLevel(cls);
} else {
class_table()->Register(cls);
}
}
#if defined(DEBUG)
void IsolateGroup::ValidateClassTable() {
class_table()->Validate();
}
#endif // DEBUG
void IsolateGroup::RegisterSharedStaticField(const Field& field,
const Object& initial_value) {
const bool need_to_grow_backing_store =
shared_initial_field_table()->Register(field);
const intptr_t field_id = field.field_id();
shared_initial_field_table()->SetAt(field_id, initial_value.ptr());
if (need_to_grow_backing_store) {
// We have to stop other isolates from accessing shared isolate group
// field state, since we'll have to grow the backing store.
GcSafepointOperationScope scope(Thread::Current());
const bool need_to_grow_other_backing_store =
shared_field_table()->Register(field, field_id);
ASSERT(need_to_grow_other_backing_store);
} else {
const bool need_to_grow_other_backing_store =
shared_field_table()->Register(field, field_id);
ASSERT(!need_to_grow_other_backing_store);
}
shared_field_table()->SetAt(field_id, initial_value.ptr());
}
void IsolateGroup::RegisterStaticField(const Field& field,
const Object& initial_value) {
ASSERT(program_lock()->IsCurrentThreadWriter());
ASSERT(field.is_static());
if (field.is_shared()) {
RegisterSharedStaticField(field, initial_value);
return;
}
const bool need_to_grow_backing_store =
initial_field_table()->Register(field);
const intptr_t field_id = field.field_id();
initial_field_table()->SetAt(field_id, initial_value.ptr());
SafepointReadRwLocker ml(Thread::Current(), isolates_lock_.get());
if (need_to_grow_backing_store) {
// We have to stop other isolates from accessing their field state, since
// we'll have to grow the backing store.
GcSafepointOperationScope scope(Thread::Current());
for (auto isolate : isolates_) {
auto field_table = isolate->field_table();
if (field_table->IsReadyToUse()) {
field_table->Register(field, field_id);
field_table->SetAt(field_id, initial_value.ptr());
}
}
} else {
for (auto isolate : isolates_) {
auto field_table = isolate->field_table();
if (field_table->IsReadyToUse()) {
field_table->Register(field, field_id);
field_table->SetAt(field_id, initial_value.ptr());
}
}
}
}
void IsolateGroup::FreeStaticField(const Field& field) {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
// This can only be called during hot-reload.
ASSERT(program_reload_context() != nullptr);
#endif
const intptr_t field_id = field.field_id();
if (field.is_shared()) {
shared_field_table()->Free(field_id);
} else {
initial_field_table()->Free(field_id);
ForEachIsolate([&](Isolate* isolate) {
auto field_table = isolate->field_table();
// The isolate might've just been created and is now participating in
// the reload request inside `IsolateGroup::RegisterIsolate()`.
// At that point it doesn't have the field table setup yet.
if (field_table->IsReadyToUse()) {
field_table->Free(field_id);
}
});
}
}
Isolate* IsolateGroup::EnterTemporaryIsolate() {
Dart_IsolateFlags flags;
Isolate::FlagsInitialize(&flags);
Isolate* const isolate = Isolate::InitIsolate("temp", this, flags);
RELEASE_ASSERT(isolate != nullptr);
ASSERT(Isolate::Current() == isolate);
return isolate;
}
void IsolateGroup::ExitTemporaryIsolate() {
Thread* thread = Thread::Current();
ASSERT(thread != nullptr);
thread->set_execution_state(Thread::kThreadInVM);
Dart::ShutdownIsolate(thread);
}
void IsolateGroup::RunWithCachedCatchEntryMoves(
const Code& code,
intptr_t pc,
std::function<void(const CatchEntryMoves&)> action) {
SafepointMutexLocker ml(&cache_mutex_);
const CatchEntryMovesRefPtr* ref = catch_entry_moves_cache_.Lookup(pc);
if (ref != nullptr) {
action(ref->moves());
} else {
const intptr_t pc_offset = pc - code.PayloadStart();
const auto& td = TypedData::Handle(code.catch_entry_moves_maps());
CatchEntryMovesMapReader reader(td);
const CatchEntryMoves* moves = reader.ReadMovesForPcOffset(pc_offset);
catch_entry_moves_cache_.Insert(pc, CatchEntryMovesRefPtr(moves));
action(*moves);
}
}
void IsolateGroup::ClearCatchEntryMovesCacheLocked() {
auto thread = Thread::Current();
ASSERT(thread->OwnsSafepoint() ||
(thread->task_kind() == Thread::kMutatorTask) ||
(thread->task_kind() == Thread::kMarkerTask) ||
(thread->task_kind() == Thread::kCompactorTask) ||
(thread->task_kind() == Thread::kScavengerTask) ||
(thread->task_kind() == Thread::kIncrementalCompactorTask));
catch_entry_moves_cache_.Clear();
}
void IsolateGroup::RehashConstants(Become* become) {
// Even though no individual constant contains a cycle, there can be "cycles"
// between the canonical tables if some const instances of A have fields that
// are const instance of B and vice versa. So set all the old tables to the
// side and clear all the tables attached to the classes before rehashing
// instead of resetting and rehash one class at a time.
Thread* thread = Thread::Current();
StackZone stack_zone(thread);
Zone* zone = stack_zone.GetZone();
intptr_t num_cids = class_table()->NumCids();
Array** old_constant_tables = zone->Alloc<Array*>(num_cids);
for (intptr_t i = 0; i < num_cids; i++) {
old_constant_tables[i] = nullptr;
}
Class& cls = Class::Handle(zone);
for (intptr_t cid = kInstanceCid; cid < num_cids; cid++) {
if (!class_table()->IsValidIndex(cid) ||
!class_table()->HasValidClassAt(cid)) {
continue;
}
if ((cid == kTypeArgumentsCid) || IsStringClassId(cid)) {
// TypeArguments and Symbols have special tables for canonical objects
// that aren't based on address.
continue;
}
if ((cid == kMintCid) || (cid == kDoubleCid)) {
// Constants stored as a plain list or in a hashset with a stable
// hashcode, which only depends on the actual value of the constant.
continue;
}
cls = class_table()->At(cid);
if (cls.constants() == Array::null()) continue;
old_constant_tables[cid] = &Array::Handle(zone, cls.constants());
cls.set_constants(Object::null_array());
}