forked from chakra-core/ChakraCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadContext.cpp
More file actions
4772 lines (4116 loc) · 156 KB
/
Copy pathThreadContext.cpp
File metadata and controls
4772 lines (4116 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
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) Microsoft Corporation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeBasePch.h"
#include "ThreadServiceWrapper.h"
#include "Types/TypePropertyCache.h"
#ifdef ENABLE_SCRIPT_DEBUGGING
#include "Debug/DebuggingFlags.h"
#include "Debug/DiagProbe.h"
#include "Debug/DebugManager.h"
#endif
#include "Chars.h"
#include "CaseInsensitive.h"
#include "CharSet.h"
#include "CharMap.h"
#include "StandardChars.h"
#include "Base/ThreadContextTlsEntry.h"
#include "Base/ThreadBoundThreadContextManager.h"
#include "Language/SourceDynamicProfileManager.h"
#include "Language/CodeGenRecyclableData.h"
#include "Language/InterpreterStackFrame.h"
#include "Language/JavascriptStackWalker.h"
#include "Base/ScriptMemoryDumper.h"
#if DBG
#include "Memory/StressTest.h"
#endif
#ifdef DYNAMIC_PROFILE_MUTATOR
#include "Language/DynamicProfileMutator.h"
#endif
#ifdef ENABLE_BASIC_TELEMETRY
#include "Telemetry.h"
#include "Recycler/RecyclerTelemetryTransmitter.h"
#endif // ENABLE_BASIC_TELEMETRY
const int TotalNumberOfBuiltInProperties = Js::PropertyIds::_countJSOnlyProperty;
/*
* When we aren't adding any additional properties
*/
void DefaultInitializeAdditionalProperties(ThreadContext *threadContext)
{
}
/*
*
*/
void (*InitializeAdditionalProperties)(ThreadContext *threadContext) = DefaultInitializeAdditionalProperties;
CriticalSection ThreadContext::s_csThreadContext;
size_t ThreadContext::processNativeCodeSize = 0;
ThreadContext * ThreadContext::globalListFirst = nullptr;
ThreadContext * ThreadContext::globalListLast = nullptr;
THREAD_LOCAL uint ThreadContext::activeScriptSiteCount = 0;
const Js::PropertyRecord * const ThreadContext::builtInPropertyRecords[] =
{
Js::BuiltInPropertyRecords::EMPTY,
#define ENTRY_INTERNAL_SYMBOL(n) Js::BuiltInPropertyRecords::n,
#define ENTRY_SYMBOL(n, d) Js::BuiltInPropertyRecords::n,
#define ENTRY(n) Js::BuiltInPropertyRecords::n,
#define ENTRY2(n, s) ENTRY(n)
#include "Base/JnDirectFields.h"
};
ThreadContext::RecyclableData::RecyclableData(Recycler *const recycler) :
pendingFinallyException(nullptr),
soErrorObject(nullptr, nullptr, nullptr, true),
oomErrorObject(nullptr, nullptr, nullptr, true),
terminatedErrorObject(nullptr, nullptr, nullptr),
typesWithProtoPropertyCache(recycler),
#if ENABLE_NATIVE_CODEGEN
propertyGuards(recycler, 128),
#endif
oldEntryPointInfo(nullptr),
#ifdef ENABLE_SCRIPT_DEBUGGING
returnedValueList(nullptr),
#endif
constructorCacheInvalidationCount(0)
{
}
ThreadContext::ThreadContext(AllocationPolicyManager * allocationPolicyManager, JsUtil::ThreadService::ThreadServiceCallback threadServiceCallback, bool enableExperimentalFeatures) :
currentThreadId(::GetCurrentThreadId()),
stackLimitForCurrentThread(0),
stackProber(nullptr),
isThreadBound(false),
hasThrownPendingException(false),
hasBailedOutBitPtr(nullptr),
noScriptScope(false),
heapEnum(nullptr),
threadContextFlags(ThreadContextFlagNoFlag),
JsUtil::DoublyLinkedListElement<ThreadContext>(),
allocationPolicyManager(allocationPolicyManager),
threadService(threadServiceCallback),
isOptimizedForManyInstances(Js::Configuration::Global.flags.OptimizeForManyInstances),
bgJit(Js::Configuration::Global.flags.BgJit),
pageAllocator(allocationPolicyManager, PageAllocatorType_Thread, Js::Configuration::Global.flags, 0, RecyclerHeuristic::Instance.DefaultMaxFreePageCount,
false
#if ENABLE_BACKGROUND_PAGE_FREEING
, &backgroundPageQueue
#endif
),
recycler(nullptr),
hasCollectionCallBack(false),
callDispose(true),
#if ENABLE_NATIVE_CODEGEN
jobProcessor(nullptr),
#endif
interruptPoller(nullptr),
expirableCollectModeGcCount(-1),
expirableObjectList(nullptr),
expirableObjectDisposeList(nullptr),
numExpirableObjects(0),
disableExpiration(false),
callRootLevel(0),
nextTypeId((Js::TypeId)Js::Constants::ReservedTypeIds),
entryExitRecord(nullptr),
leafInterpreterFrame(nullptr),
threadServiceWrapper(nullptr),
tryHandlerAddrOfReturnAddr(nullptr),
temporaryArenaAllocatorCount(0),
temporaryGuestArenaAllocatorCount(0),
crefSContextForDiag(0),
m_prereservedRegionAddr(0),
scriptContextList(nullptr),
scriptContextEverRegistered(false),
#if DBG_DUMP || defined(PROFILE_EXEC)
topLevelScriptSite(nullptr),
#endif
polymorphicCacheState(0),
stackProbeCount(0),
#ifdef BAILOUT_INJECTION
bailOutByteCodeLocationCount(0),
#endif
sourceCodeSize(0),
nativeCodeSize(0),
threadAlloc(_u("TC"), GetPageAllocator(), Js::Throw::OutOfMemory),
inlineCacheThreadInfoAllocator(_u("TC-InlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
isInstInlineCacheThreadInfoAllocator(_u("TC-IsInstInlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
equivalentTypeCacheInfoAllocator(_u("TC-EquivalentTypeCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
protoInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 521),
storeFieldInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 293),
isInstInlineCacheByFunction(&isInstInlineCacheThreadInfoAllocator, 131),
registeredInlineCacheCount(0),
unregisteredInlineCacheCount(0),
noSpecialPropertyRegistry(this->GetPageAllocator()),
onlyWritablePropertyRegistry(this->GetPageAllocator()),
standardUTF8Chars(0),
standardUnicodeChars(0),
hasUnhandledException(FALSE),
hasCatchHandler(FALSE),
disableImplicitFlags(DisableImplicitNoFlag),
hasCatchHandlerToUserCode(false),
caseInvariantPropertySet(nullptr),
entryPointToBuiltInOperationIdCache(&threadAlloc, 0),
#if ENABLE_NATIVE_CODEGEN
preReservedVirtualAllocator(),
#if !FLOATVAR
codeGenNumberThreadAllocator(nullptr),
xProcNumberPageSegmentManager(nullptr),
#endif
m_jitNumericProperties(nullptr),
m_jitNeedsPropertyUpdate(false),
#if DYNAMIC_INTERPRETER_THUNK || defined(ASMJS_PLAT)
thunkPageAllocators(allocationPolicyManager, /* allocXData */ false, /* virtualAllocator */ nullptr, GetCurrentProcess()),
#endif
codePageAllocators(allocationPolicyManager, ALLOC_XDATA, GetPreReservedVirtualAllocator(), GetCurrentProcess()),
#if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
jitThunkEmitter(this, &VirtualAllocWrapper::Instance , GetCurrentProcess()),
#endif
#endif
dynamicObjectEnumeratorCacheMap(&HeapAllocator::Instance, 16),
//threadContextFlags(ThreadContextFlagNoFlag),
#ifdef NTBUILD
telemetryBlock(&localTelemetryBlock),
#endif
configuration(enableExperimentalFeatures),
jsrtRuntime(nullptr),
propertyMap(nullptr),
rootPendingClose(nullptr),
exceptionCode(0),
isProfilingUserCode(true),
loopDepth(0),
redeferralState(InitialRedeferralState),
gcSinceLastRedeferral(0),
gcSinceCallCountsCollected(0),
tridentLoadAddress(nullptr),
m_remoteThreadContextInfo(nullptr)
#ifdef ENABLE_SCRIPT_DEBUGGING
, debugManager(nullptr)
#endif
#if ENABLE_TTD
, TTDContext(nullptr)
, TTDExecutionInfo(nullptr)
, TTDLog(nullptr)
, TTDRootNestingCount(0)
#endif
#ifdef ENABLE_DIRECTCALL_TELEMETRY
, directCallTelemetry(this)
#endif
#if ENABLE_JS_REENTRANCY_CHECK
, noJsReentrancy(false)
#endif
, emptyStringPropertyRecord(nullptr)
, recyclerTelemetryHostInterface(this)
, reentrancySafeOrHandled(false)
, isInReentrancySafeRegion(false)
, closedScriptContextCount(0)
, visibilityState(VisibilityState::Undefined)
{
hostScriptContextStack = Anew(GetThreadAlloc(), JsUtil::Stack<HostScriptContext*>, GetThreadAlloc());
functionCount = 0;
sourceInfoCount = 0;
#if DBG || defined(RUNTIME_DATA_COLLECTION)
scriptContextCount = 0;
#endif
isScriptActive = false;
#ifdef ENABLE_CUSTOM_ENTROPY
entropy.Initialize();
#endif
#if ENABLE_NATIVE_CODEGEN
this->bailOutRegisterSaveSpace = AnewArrayZ(this->GetThreadAlloc(), Js::Var, GetBailOutRegisterSaveSlotCount());
#endif
#if DBG_DUMP
scriptSiteCount = 0;
pageAllocator.debugName = _u("Thread");
#endif
#ifdef DYNAMIC_PROFILE_MUTATOR
this->dynamicProfileMutator = DynamicProfileMutator::GetMutator();
#endif
PERF_COUNTER_INC(Basic, ThreadContext);
#ifdef LEAK_REPORT
this->rootTrackerScriptContext = nullptr;
this->threadId = ::GetCurrentThreadId();
#endif
#ifdef NTBUILD
memset(&localTelemetryBlock, 0, sizeof(localTelemetryBlock));
#endif
AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
ThreadContext::LinkToBeginning(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast);
#if DBG
// Since we created our page allocator while we were constructing this thread context
// it will pick up the thread context id that is current on the thread. We need to update
// that now.
pageAllocator.UpdateThreadContextHandle((ThreadContextId)this);
#endif
#if DBG
arrayMutationSeed = (Js::Configuration::Global.flags.ArrayMutationTestSeed != 0) ? (uint)Js::Configuration::Global.flags.ArrayMutationTestSeed : (uint)time(NULL);
srand(arrayMutationSeed);
#endif
this->InitAvailableCommit();
}
void ThreadContext::InitAvailableCommit()
{
// Once per process: get the available commit for the process from the OS and push it to the AutoSystemInfo.
// (This must be done lazily, outside DllMain. And it must be done from the Runtime, since the common lib
// doesn't have access to the DelayLoadLibrary stuff.)
ULONG64 commit;
BOOL success = AutoSystemInfo::Data.GetAvailableCommit(&commit);
if (!success)
{
commit = (ULONG64)-1;
#ifdef NTBUILD
APP_MEMORY_INFORMATION AppMemInfo;
success = GetWinCoreProcessThreads()->GetProcessInformation(
GetCurrentProcess(),
ProcessAppMemoryInfo,
&AppMemInfo,
sizeof(AppMemInfo));
if (success)
{
commit = AppMemInfo.AvailableCommit;
}
#endif
AutoSystemInfo::Data.SetAvailableCommit(commit);
}
}
void ThreadContext::SetStackProber(StackProber * stackProber)
{
this->stackProber = stackProber;
if (stackProber != NULL && this->stackLimitForCurrentThread != Js::Constants::StackLimitForScriptInterrupt)
{
this->stackLimitForCurrentThread = stackProber->GetScriptStackLimit();
}
}
size_t ThreadContext::GetScriptStackLimit() const
{
return stackProber->GetScriptStackLimit();
}
HANDLE
ThreadContext::GetProcessHandle() const
{
return GetCurrentProcess();
}
intptr_t
ThreadContext::GetThreadStackLimitAddr() const
{
return (intptr_t)GetAddressOfStackLimitForCurrentThread();
}
#if ENABLE_NATIVE_CODEGEN && defined(ENABLE_WASM_SIMD)
intptr_t
ThreadContext::GetSimdTempAreaAddr(uint8 tempIndex) const
{
return (intptr_t)&X86_TEMP_SIMD[tempIndex];
}
#endif
intptr_t
ThreadContext::GetDisableImplicitFlagsAddr() const
{
return (intptr_t)&disableImplicitFlags;
}
intptr_t
ThreadContext::GetImplicitCallFlagsAddr() const
{
return (intptr_t)&implicitCallFlags;
}
ptrdiff_t
ThreadContext::GetChakraBaseAddressDifference() const
{
return 0;
}
ptrdiff_t
ThreadContext::GetCRTBaseAddressDifference() const
{
return 0;
}
IActiveScriptProfilerHeapEnum* ThreadContext::GetHeapEnum()
{
return heapEnum;
}
void ThreadContext::SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum)
{
Assert((newHeapEnum != nullptr && heapEnum == nullptr) || (newHeapEnum == nullptr && heapEnum != nullptr));
heapEnum = newHeapEnum;
}
void ThreadContext::ClearHeapEnum()
{
Assert(heapEnum != nullptr);
heapEnum = nullptr;
}
void ThreadContext::GlobalInitialize()
{
for (int i = 0; i < _countof(builtInPropertyRecords); i++)
{
builtInPropertyRecords[i]->SetHash(JsUtil::CharacterBuffer<WCHAR>::StaticGetHashCode(builtInPropertyRecords[i]->GetBuffer(), builtInPropertyRecords[i]->GetLength()));
}
}
ThreadContext::~ThreadContext()
{
{
AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
ThreadContext::Unlink(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast);
}
#if ENABLE_TTD
if(this->TTDContext != nullptr)
{
TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDContext);
this->TTDContext = nullptr;
}
if(this->TTDExecutionInfo != nullptr)
{
TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDExecutionInfo);
this->TTDExecutionInfo = nullptr;
}
if(this->TTDLog != nullptr)
{
TT_HEAP_DELETE(TTD::EventLog, this->TTDLog);
this->TTDLog = nullptr;
}
#endif
#ifdef LEAK_REPORT
if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
{
AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): %s (TID: %d)"), this,
this->GetRecycler()->IsInDllCanUnloadNow()? _u("DllCanUnloadNow") :
this->GetRecycler()->IsInDetachProcess()? _u("DetachProcess") : _u("Destructor"), this->threadId);
LeakReport::DumpUrl(this->threadId);
}
#endif
if (interruptPoller)
{
HeapDelete(interruptPoller);
interruptPoller = nullptr;
}
#if DBG
// ThreadContext dtor may be running on a different thread.
// Recycler may call finalizer that free temp Arenas, which will free pages back to
// the page Allocator, which will try to suspend idle on a different thread.
// So we need to disable idle decommit asserts.
pageAllocator.ShutdownIdleDecommit();
#endif
// Allocating memory during the shutdown codepath is not preferred
// so we'll close the page allocator before we release the GC
// If any dispose is allocating memory during shutdown, that is a bug
pageAllocator.Close();
// The recycler need to delete before the background code gen thread
// because that might run finalizer which need access to the background code gen thread.
if (recycler != nullptr)
{
for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
{
if (!scriptContext->IsActuallyClosed())
{
// We close ScriptContext here because anyhow HeapDelete(recycler) when disposing the
// JavaScriptLibrary will close ScriptContext. Explicit close gives us chance to clear
// other things to which ScriptContext holds reference to
AssertMsg(!IsInScript(), "Can we be in script here?");
scriptContext->MarkForClose();
}
}
// If all scriptContext's have been closed, then the sourceProfileManagersByUrl
// should have been released
AssertMsg(this->recyclableData->sourceProfileManagersByUrl == nullptr ||
this->recyclableData->sourceProfileManagersByUrl->Count() == 0, "There seems to have been a refcounting imbalance.");
this->recyclableData->sourceProfileManagersByUrl = nullptr;
this->recyclableData->oldEntryPointInfo = nullptr;
if (this->recyclableData->symbolRegistrationMap != nullptr)
{
this->recyclableData->symbolRegistrationMap->Clear();
this->recyclableData->symbolRegistrationMap = nullptr;
}
#ifdef ENABLE_SCRIPT_DEBUGGING
if (this->recyclableData->returnedValueList != nullptr)
{
this->recyclableData->returnedValueList->Clear();
this->recyclableData->returnedValueList = nullptr;
}
#endif
if (this->propertyMap != nullptr)
{
HeapDelete(this->propertyMap);
this->propertyMap = nullptr;
}
#if ENABLE_NATIVE_CODEGEN
if (this->m_jitNumericProperties != nullptr)
{
HeapDelete(this->m_jitNumericProperties);
this->m_jitNumericProperties = nullptr;
}
#endif
// Unpin the memory for leak report so we don't report this as a leak.
recyclableData.Unroot(recycler);
#if defined(LEAK_REPORT) || defined(CHECK_MEMORY_LEAK)
for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
{
scriptContext->ClearSourceContextInfoMaps();
scriptContext->ShutdownClearSourceLists();
}
#ifdef LEAK_REPORT
// heuristically figure out which one is the root tracker script engine
// and force close on it
if (this->rootTrackerScriptContext != nullptr)
{
this->rootTrackerScriptContext->Close(false);
}
#endif
#endif
#if ENABLE_NATIVE_CODEGEN
#if !FLOATVAR
if (this->codeGenNumberThreadAllocator)
{
HeapDelete(this->codeGenNumberThreadAllocator);
this->codeGenNumberThreadAllocator = nullptr;
}
if (this->xProcNumberPageSegmentManager)
{
HeapDelete(this->xProcNumberPageSegmentManager);
this->xProcNumberPageSegmentManager = nullptr;
}
#endif
#endif
#ifdef ENABLE_SCRIPT_DEBUGGING
Assert(this->debugManager == nullptr);
#endif
#if ENABLE_CONCURRENT_GC && defined(_WIN32)
AssertOrFailFastMsg(recycler->concurrentThread == NULL, "Recycler background thread should have been shutdown before destroying Recycler.");
AssertOrFailFastMsg((recycler->parallelThread1.concurrentThread == NULL) && (recycler->parallelThread2.concurrentThread == NULL), "Recycler parallelThread(s) should have been shutdown before destroying Recycler.");
#endif
HeapDelete(recycler);
}
#if ENABLE_NATIVE_CODEGEN
if(jobProcessor)
{
if(this->bgJit)
{
HeapDelete(static_cast<JsUtil::BackgroundJobProcessor *>(jobProcessor));
}
else
{
HeapDelete(static_cast<JsUtil::ForegroundJobProcessor *>(jobProcessor));
}
jobProcessor = nullptr;
}
#endif
// Do not require all GC callbacks to be revoked, because Trident may not revoke if there
// is a leak, and we don't want the leak to be masked by an assert
this->collectCallBackList.Clear(&HeapAllocator::Instance);
this->protoInlineCacheByPropId.Reset();
this->storeFieldInlineCacheByPropId.Reset();
this->isInstInlineCacheByFunction.Reset();
this->equivalentTypeCacheEntryPoints.Reset();
this->noSpecialPropertyRegistry.Reset();
this->onlyWritablePropertyRegistry.Reset();
this->registeredInlineCacheCount = 0;
this->unregisteredInlineCacheCount = 0;
AssertMsg(this->GetHeapEnum() == nullptr, "Heap enumeration should have been cleared/closed by the ScriptSite.");
if (this->GetHeapEnum() != nullptr)
{
this->ClearHeapEnum();
}
#ifdef BAILOUT_INJECTION
if (Js::Configuration::Global.flags.IsEnabled(Js::BailOutByteCodeFlag)
&& Js::Configuration::Global.flags.BailOutByteCode.Empty())
{
Output::Print(_u("Bail out byte code location count: %d"), this->bailOutByteCodeLocationCount);
}
#endif
Assert(processNativeCodeSize >= nativeCodeSize);
::InterlockedExchangeSubtract(&processNativeCodeSize, nativeCodeSize);
PERF_COUNTER_DEC(Basic, ThreadContext);
#ifdef DYNAMIC_PROFILE_MUTATOR
if (this->dynamicProfileMutator != nullptr)
{
this->dynamicProfileMutator->Delete();
}
#endif
}
void
ThreadContext::SetJSRTRuntime(void* runtime)
{
Assert(jsrtRuntime == nullptr);
jsrtRuntime = runtime;
#ifdef ENABLE_BASIC_TELEMETRY
Telemetry::EnsureInitializeForJSRT();
#endif
}
void ThreadContext::CloseForJSRT()
{
// This is used for JSRT APIs only.
Assert(this->jsrtRuntime);
#ifdef ENABLE_BASIC_TELEMETRY
// log any relevant telemetry before disposing the current thread for cases which are properly shutdown
Telemetry::OnJSRTThreadContextClose();
#endif
ShutdownThreads();
}
ThreadContext* ThreadContext::GetContextForCurrentThread()
{
ThreadContextTLSEntry * tlsEntry = ThreadContextTLSEntry::GetEntryForCurrentThread();
if (tlsEntry != nullptr)
{
return static_cast<ThreadContext *>(tlsEntry->GetThreadContext());
}
return nullptr;
}
void ThreadContext::ValidateThreadContext()
{
#if DBG
// verify the runtime pointer is valid.
{
BOOL found = FALSE;
AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
ThreadContext* currentThreadContext = GetThreadContextList();
while (currentThreadContext)
{
if (currentThreadContext == this)
{
return;
}
currentThreadContext = currentThreadContext->Next();
}
AssertMsg(found, "invalid thread context");
}
#endif
}
class AutoRecyclerPtr : public AutoPtr<Recycler>
{
public:
AutoRecyclerPtr(Recycler * ptr) : AutoPtr<Recycler>(ptr) {}
~AutoRecyclerPtr()
{
#if ENABLE_CONCURRENT_GC
if (ptr != nullptr)
{
ptr->ShutdownThread();
}
#endif
}
};
LPFILETIME ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetLastScriptExecutionEndTime() const
{
#if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
return &(tc->telemetryBlock->lastScriptEndTime);
#else
return nullptr;
#endif
}
bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitGCTelemetryStats(RecyclerTelemetryInfo& rti)
{
#if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
return Js::TransmitRecyclerTelemetryStats(rti);
#else
return false;
#endif
}
bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitHeapUsage(size_t totalHeapBytes, size_t usedHeapBytes, double heapUsedRatio)
{
#if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
return Js::TransmitRecyclerHeapUsage(totalHeapBytes, usedHeapBytes, heapUsedRatio);
#else
return false;
#endif
}
bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::IsTelemetryProviderEnabled() const
{
#if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
return Js::IsTelemetryProviderEnabled();
#else
return false;
#endif
}
bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitTelemetryError(const RecyclerTelemetryInfo& rti, const char * msg)
{
#if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
return Js::TransmitRecyclerTelemetryError(rti, msg);
#else
return false;
#endif
}
bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::IsThreadBound() const
{
return this->tc->IsThreadBound();
}
DWORD ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetCurrentScriptThreadID() const
{
return this->tc->GetCurrentThreadId();
}
uint ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetClosedContextCount() const
{
return this->tc->closedScriptContextCount;
}
Recycler* ThreadContext::EnsureRecycler()
{
if (recycler == NULL)
{
AutoRecyclerPtr newRecycler(HeapNew(Recycler, GetAllocationPolicyManager(), &pageAllocator, Js::Throw::OutOfMemory, Js::Configuration::Global.flags, &recyclerTelemetryHostInterface));
newRecycler->Initialize(isOptimizedForManyInstances, &threadService); // use in-thread GC when optimizing for many instances
newRecycler->SetCollectionWrapper(this);
#if ENABLE_NATIVE_CODEGEN
// This may throw, so it needs to be after the recycler is initialized,
// otherwise, the recycler dtor may encounter problems
#if !FLOATVAR
// TODO: we only need one of the following, one for OOP jit and one for in-proc BG JIT
AutoPtr<CodeGenNumberThreadAllocator> localCodeGenNumberThreadAllocator(
HeapNew(CodeGenNumberThreadAllocator, newRecycler));
AutoPtr<XProcNumberPageSegmentManager> localXProcNumberPageSegmentManager(
HeapNew(XProcNumberPageSegmentManager, newRecycler));
#endif
#endif
this->recyclableData.Root(RecyclerNewZ(newRecycler, RecyclableData, newRecycler), newRecycler);
if (this->IsThreadBound())
{
newRecycler->SetIsThreadBound();
}
// Assign the recycler to the ThreadContext after everything is initialized, because an OOM during initialization would
// result in only partial initialization, so the 'recycler' member variable should remain null to cause full
// reinitialization when requested later. Anything that happens after the Detach must have special cleanup code.
this->recycler = newRecycler.Detach();
try
{
#ifdef RECYCLER_WRITE_BARRIER
#ifdef TARGET_64
if (!RecyclerWriteBarrierManager::OnThreadInit())
{
Js::Throw::OutOfMemory();
}
#endif
#endif
this->expirableObjectList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc);
this->expirableObjectDisposeList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc);
InitializePropertyMaps(); // has many dependencies on the recycler and other members of the thread context
#if ENABLE_NATIVE_CODEGEN
#if !FLOATVAR
this->codeGenNumberThreadAllocator = localCodeGenNumberThreadAllocator.Detach();
this->xProcNumberPageSegmentManager = localXProcNumberPageSegmentManager.Detach();
#endif
#endif
}
catch(...)
{
// Initialization failed, undo what was done above. Callees that throw must clean up after themselves.
if (this->recyclableData != nullptr)
{
this->recyclableData.Unroot(this->recycler);
}
{
// AutoRecyclerPtr's destructor takes care of shutting down the background thread and deleting the recycler
AutoRecyclerPtr recyclerToDelete(this->recycler);
this->recycler = nullptr;
}
throw;
}
JS_ETW(EventWriteJSCRIPT_GC_INIT(this->recycler, this->GetHiResTimer()->Now()));
}
#if DBG
if (CONFIG_FLAG(RecyclerTest))
{
StressTester test(recycler);
test.Run();
}
#endif
return recycler;
}
Js::PropertyRecord const *
ThreadContext::GetPropertyName(Js::PropertyId propertyId)
{
// This API should only be use on the main thread
Assert(GetCurrentThreadContextId() == (ThreadContextId)this);
return this->GetPropertyNameImpl<false>(propertyId);
}
Js::PropertyRecord const *
ThreadContext::GetPropertyNameLocked(Js::PropertyId propertyId)
{
return GetPropertyNameImpl<true>(propertyId);
}
template <bool locked>
Js::PropertyRecord const *
ThreadContext::GetPropertyNameImpl(Js::PropertyId propertyId)
{
//TODO: Remove this when completely transformed to use PropertyRecord*. Currently this is only partially done,
// and there are calls to GetPropertyName with InternalPropertyId.
if (propertyId >= 0 && Js::IsInternalPropertyId(propertyId))
{
return Js::InternalPropertyRecords::GetInternalPropertyName(propertyId);
}
int propertyIndex = propertyId - Js::PropertyIds::_none;
if (propertyIndex < 0 || propertyIndex > propertyMap->GetLastIndex())
{
propertyIndex = 0;
}
const Js::PropertyRecord * propertyRecord = nullptr;
if (locked) { propertyMap->LockResize(); }
bool found = propertyMap->TryGetValueAt(propertyIndex, &propertyRecord);
if (locked) { propertyMap->UnlockResize(); }
AssertMsg(found && propertyRecord != nullptr, "using invalid propertyid");
return propertyRecord;
}
void
ThreadContext::FindPropertyRecord(Js::JavascriptString *pstName, Js::PropertyRecord const ** propertyRecord)
{
pstName->GetPropertyRecord(propertyRecord, true);
if (*propertyRecord != nullptr)
{
return;
}
// GetString is not guaranteed to be null-terminated, but we explicitly pass length to the next step
LPCWCH propertyName = pstName->GetString();
FindPropertyRecord(propertyName, pstName->GetLength(), propertyRecord);
if (*propertyRecord)
{
pstName->CachePropertyRecord(*propertyRecord);
}
}
void
ThreadContext::FindPropertyRecord(__in LPCWCH propertyName, __in int propertyNameLength, Js::PropertyRecord const ** propertyRecord)
{
EnterPinnedScope((volatile void **)propertyRecord);
*propertyRecord = FindPropertyRecord(propertyName, propertyNameLength);
LeavePinnedScope();
}
Js::PropertyRecord const *
ThreadContext::GetPropertyRecord(Js::PropertyId propertyId)
{
return GetPropertyNameLocked(propertyId);
}
bool
ThreadContext::IsNumericProperty(Js::PropertyId propertyId)
{
return GetPropertyRecord(propertyId)->IsNumeric();
}
const Js::PropertyRecord *
ThreadContext::FindPropertyRecord(const char16 * propertyName, int propertyNameLength)
{
// IsDirectPropertyName == 1 char properties && GetEmptyStringPropertyRecord == 0 length
if (propertyNameLength < 2)
{
if (propertyNameLength == 0)
{
return this->GetEmptyStringPropertyRecord();
}
if (IsDirectPropertyName(propertyName, propertyNameLength))
{
Js::PropertyRecord const * propertyRecord = propertyNamesDirect[propertyName[0]];
Assert(propertyRecord == propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength)));
return propertyRecord;
}
}
return propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength));
}
Js::PropertyRecord const *
ThreadContext::UncheckedAddPropertyId(__in LPCWSTR propertyName, __in int propertyNameLength, bool bind, bool isSymbol)
{
return UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), bind, isSymbol);
}
void ThreadContext::InitializePropertyMaps()
{
Assert(this->recycler != nullptr);
Assert(this->recyclableData != nullptr);
Assert(this->propertyMap == nullptr);
Assert(this->caseInvariantPropertySet == nullptr);
try
{
this->propertyMap = HeapNew(PropertyMap, &HeapAllocator::Instance, TotalNumberOfBuiltInProperties + 700);
this->recyclableData->boundPropertyStrings = RecyclerNew(this->recycler, JsUtil::List<Js::PropertyRecord const*>, this->recycler);
memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *));
Js::JavascriptLibrary::InitializeProperties(this);
InitializeAdditionalProperties(this);
//Js::JavascriptLibrary::InitializeDOMProperties(this);
}
catch(...)
{
// Initialization failed, undo what was done above. Callees that throw must clean up after themselves. The recycler will
// be trashed, so clear members that point to recyclable memory. Stuff in 'recyclableData' will be taken care of by the
// recycler, and the 'recyclableData' instance will be trashed as well.
if (this->propertyMap != nullptr)
{
HeapDelete(this->propertyMap);
}
this->propertyMap = nullptr;
this->caseInvariantPropertySet = nullptr;
memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *));
throw;
}
}
void ThreadContext::UncheckedAddBuiltInPropertyId()
{
for (int i = 0; i < _countof(builtInPropertyRecords); i++)
{
AddPropertyRecordInternal(builtInPropertyRecords[i]);
}
}
bool
ThreadContext::IsDirectPropertyName(const char16 * propertyName, int propertyNameLength)
{
return ((propertyNameLength == 1) && ((propertyName[0] & 0xFF80) == 0));
}
RecyclerWeakReference<const Js::PropertyRecord> *
ThreadContext::CreatePropertyRecordWeakRef(const Js::PropertyRecord * propertyRecord)
{
RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef;
if (propertyRecord->IsBound())
{
// Create a fake weak ref
propertyRecordWeakRef = RecyclerNewLeaf(this->recycler, StaticPropertyRecordReference, propertyRecord);
}
else
{
propertyRecordWeakRef = recycler->CreateWeakReferenceHandle(propertyRecord);
}
return propertyRecordWeakRef;
}
Js::PropertyRecord const *
ThreadContext::UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR> const& propertyName, bool bind, bool isSymbol)
{
#if ENABLE_TTD
if(isSymbol & this->IsRuntimeInTTDMode())
{
if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformReplayAction())
{
//We reload all properties that occur in the trace so they only way we get here in TTD mode is:
//(1) if the program is creating a new symbol (which always gets a fresh id) and we should recreate it or
//(2) if it is forcing arguments in debug parse mode (instead of regular which we recorded in)
Js::PropertyId propertyId = Js::Constants::NoProperty;
this->TTDLog->ReplaySymbolCreationEvent(&propertyId);
//Don't recreate the symbol below, instead return the known symbol by looking up on the pid
const Js::PropertyRecord* res = this->GetPropertyName(propertyId);
AssertMsg(res != nullptr, "This should never happen!!!");
return res;
}
}
#endif