forked from chakra-core/ChakraCore
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScriptContext.cpp
More file actions
6262 lines (5400 loc) · 236 KB
/
ScriptContext.cpp
File metadata and controls
6262 lines (5400 loc) · 236 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. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeBasePch.h"
// Parser Includes
#include "RegexCommon.h"
#include "DebugWriter.h"
#include "RegexStats.h"
#include "ByteCode/ByteCodeApi.h"
#include "Library/ProfileString.h"
#include "Debug/DiagHelperMethodWrapper.h"
#include "BackendApi.h"
#if PROFILE_DICTIONARY
#include "DictionaryStats.h"
#endif
#include "Base/ScriptContextProfiler.h"
#include "Base/EtwTrace.h"
#include "Language/InterpreterStackFrame.h"
#include "Language/SourceDynamicProfileManager.h"
#include "Language/JavascriptStackWalker.h"
#include "Language/AsmJsTypes.h"
#include "Language/AsmJsModule.h"
#ifdef ASMJS_PLAT
#include "Language/AsmJsEncoder.h"
#include "Language/AsmJsCodeGenerator.h"
#include "Language/AsmJsUtils.h"
#endif
#ifdef ENABLE_BASIC_TELEMETRY
#include "ScriptContextTelemetry.h"
#endif
namespace Js
{
ScriptContext * ScriptContext::New(ThreadContext * threadContext)
{
AutoPtr<ScriptContext> scriptContext(HeapNew(ScriptContext, threadContext));
scriptContext->InitializeAllocations();
return scriptContext.Detach();
}
CriticalSection JITPageAddrToFuncRangeCache::cs;
ScriptContext::ScriptContext(ThreadContext* threadContext) :
ScriptContextBase(),
prev(nullptr),
next(nullptr),
interpreterArena(nullptr),
moduleSrcInfoCount(0),
// Regex globals
#if ENABLE_REGEX_CONFIG_OPTIONS
regexStatsDatabase(0),
regexDebugWriter(0),
#endif
trigramAlphabet(nullptr),
regexStacks(nullptr),
arrayMatchInit(false),
config(threadContext->GetConfig(), threadContext->IsOptimizedForManyInstances()),
#if ENABLE_BACKGROUND_PARSING
backgroundParser(nullptr),
#endif
#if ENABLE_NATIVE_CODEGEN
nativeCodeGen(nullptr),
m_domFastPathHelperMap(nullptr),
#endif
threadContext(threadContext),
scriptStartEventHandler(nullptr),
scriptEndEventHandler(nullptr),
#ifdef FAULT_INJECTION
disposeScriptByFaultInjectionEventHandler(nullptr),
#endif
integerStringMap(this->GeneralAllocator()),
guestArena(nullptr),
raiseMessageToDebuggerFunctionType(nullptr),
transitionToDebugModeIfFirstSourceFn(nullptr),
sourceSize(0),
deferredBody(false),
isScriptContextActuallyClosed(false),
isFinalized(false),
isEvalRestricted(false),
isInvalidatedForHostObjects(false),
fastDOMenabled(false),
directHostTypeId(TypeIds_GlobalObject),
isPerformingNonreentrantWork(false),
isDiagnosticsScriptContext(false),
m_enumerateNonUserFunctionsOnly(false),
recycler(threadContext->EnsureRecycler()),
CurrentThunk(DefaultEntryThunk),
CurrentCrossSiteThunk(CrossSite::DefaultThunk),
DeferredParsingThunk(DefaultDeferredParsingThunk),
DeferredDeserializationThunk(DefaultDeferredDeserializeThunk),
DispatchDefaultInvoke(nullptr),
DispatchProfileInvoke(nullptr),
m_pBuiltinFunctionIdMap(nullptr),
diagnosticArena(nullptr),
hostScriptContext(nullptr),
scriptEngineHaltCallback(nullptr),
#if DYNAMIC_INTERPRETER_THUNK
interpreterThunkEmitter(nullptr),
#endif
#ifdef ASMJS_PLAT
asmJsInterpreterThunkEmitter(nullptr),
asmJsCodeGenerator(nullptr),
#endif
generalAllocator(_u("SC-General"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
#ifdef ENABLE_BASIC_TELEMETRY
telemetryAllocator(_u("SC-Telemetry"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
#endif
dynamicProfileInfoAllocator(_u("SC-DynProfileInfo"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
#ifdef SEPARATE_ARENA
sourceCodeAllocator(_u("SC-Code"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
regexAllocator(_u("SC-Regex"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
#endif
#ifdef NEED_MISC_ALLOCATOR
miscAllocator(_u("GC-Misc"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
#endif
inlineCacheAllocator(_u("SC-InlineCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
isInstInlineCacheAllocator(_u("SC-IsInstInlineCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
forInCacheAllocator(_u("SC-ForInCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
hasUsedInlineCache(false),
hasProtoOrStoreFieldInlineCache(false),
hasIsInstInlineCache(false),
registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(nullptr),
firstInterpreterFrameReturnAddress(nullptr),
builtInLibraryFunctions(nullptr),
m_remoteScriptContextAddr(nullptr),
isWeakReferenceDictionaryListCleared(false),
isDebugContextInitialized(false)
#if ENABLE_PROFILE_INFO
, referencesSharedDynamicSourceContextInfo(false)
#endif
#if DBG
, isInitialized(false)
, isCloningGlobal(false)
, bindRef(MiscAllocator())
#endif
#if ENABLE_TTD
, TTDHostCallbackFunctor()
, ScriptContextLogTag(TTD_INVALID_LOG_PTR_ID)
, TTDWellKnownInfo(nullptr)
, TTDContextInfo(nullptr)
, TTDSnapshotOrInflateInProgress(false)
, TTDRecordOrReplayModeEnabled(false)
, TTDRecordModeEnabled(false)
, TTDReplayModeEnabled(false)
, TTDShouldPerformRecordOrReplayAction(false)
, TTDShouldPerformRecordAction(false)
, TTDShouldPerformReplayAction(false)
, TTDShouldPerformDebuggerAction(false)
, TTDShouldSuppressGetterInvocationForDebuggerEvaluation(false)
#endif
#ifdef REJIT_STATS
, rejitStatsMap(nullptr)
, bailoutReasonCounts(nullptr)
, bailoutReasonCountsCap(nullptr)
, rejitReasonCounts(nullptr)
, rejitReasonCountsCap(nullptr)
#endif
#ifdef ENABLE_BASIC_TELEMETRY
, telemetry(nullptr)
#endif
#ifdef INLINE_CACHE_STATS
, cacheDataMap(nullptr)
#endif
#ifdef FIELD_ACCESS_STATS
, fieldAccessStatsByFunctionNumber(nullptr)
#endif
, webWorkerId(Js::Constants::NonWebWorkerContextId)
, url(_u(""))
, startupComplete(false)
, isEnumeratingRecyclerObjects(false)
#ifdef EDIT_AND_CONTINUE
, activeScriptEditQuery(nullptr)
#endif
#ifdef ENABLE_SCRIPT_PROFILING
, heapEnum(nullptr)
#endif
#ifdef RECYCLER_PERF_COUNTERS
, bindReferenceCount(0)
#endif
, nextPendingClose(nullptr)
#ifdef ENABLE_SCRIPT_PROFILING
, m_fTraceDomCall(FALSE)
#endif
, intConstPropsOnGlobalObject(nullptr)
, intConstPropsOnGlobalUserObject(nullptr)
#ifdef PROFILE_STRINGS
, stringProfiler(nullptr)
#endif
#ifdef PROFILE_BAILOUT_RECORD_MEMORY
, codeSize(0)
, bailOutRecordBytes(0)
, bailOutOffsetBytes(0)
#endif
, debugContext(nullptr)
, jitFuncRangeCache(nullptr)
{
// This may allocate memory and cause exception, but it is ok, as we all we have done so far
// are field init and those dtor will be called if exception occurs
threadContext->EnsureDebugManager();
// Don't use throwing memory allocation in ctor, as exception in ctor doesn't cause the dtor to be called
// potentially causing memory leaks
BEGIN_NO_EXCEPTION;
#ifdef RUNTIME_DATA_COLLECTION
createTime = time(nullptr);
#endif
#ifdef BGJIT_STATS
interpretedCount = maxFuncInterpret = funcJITCount = bytecodeJITCount = interpretedCallsHighPri = jitCodeUsed = funcJitCodeUsed = loopJITCount = speculativeJitCount = 0;
#endif
#ifdef PROFILE_TYPES
convertNullToSimpleCount = 0;
convertNullToSimpleDictionaryCount = 0;
convertNullToDictionaryCount = 0;
convertDeferredToDictionaryCount = 0;
convertDeferredToSimpleDictionaryCount = 0;
convertSimpleToDictionaryCount = 0;
convertSimpleToSimpleDictionaryCount = 0;
convertPathToDictionaryCount1 = 0;
convertPathToDictionaryCount2 = 0;
convertPathToDictionaryCount3 = 0;
convertPathToDictionaryCount4 = 0;
convertPathToSimpleDictionaryCount = 0;
convertSimplePathToPathCount = 0;
convertSimpleDictionaryToDictionaryCount = 0;
convertSimpleSharedDictionaryToNonSharedCount = 0;
convertSimpleSharedToNonSharedCount = 0;
simplePathTypeHandlerCount = 0;
pathTypeHandlerCount = 0;
promoteCount = 0;
cacheCount = 0;
branchCount = 0;
maxPathLength = 0;
memset(typeCount, 0, sizeof(typeCount));
memset(instanceCount, 0, sizeof(instanceCount));
#endif
#ifdef PROFILE_OBJECT_LITERALS
objectLiteralInstanceCount = 0;
objectLiteralPathCount = 0;
memset(objectLiteralCount, 0, sizeof(objectLiteralCount));
objectLiteralSimpleDictionaryCount = 0;
objectLiteralMaxLength = 0;
objectLiteralPromoteCount = 0;
objectLiteralCacheCount = 0;
objectLiteralBranchCount = 0;
#endif
#if DBG_DUMP
byteCodeDataSize = 0;
byteCodeAuxiliaryDataSize = 0;
byteCodeAuxiliaryContextDataSize = 0;
memset(byteCodeHistogram, 0, sizeof(byteCodeHistogram));
#endif
#if DBG || defined(RUNTIME_DATA_COLLECTION)
this->allocId = threadContext->GetScriptContextCount();
#endif
#if DBG
this->hadProfiled = false;
#endif
#if DBG_DUMP
forinCache = 0;
forinNoCache = 0;
#endif
callCount = 0;
threadContext->GetHiResTimer()->Reset();
#ifdef PROFILE_EXEC
profiler = nullptr;
isProfilerCreated = false;
disableProfiler = false;
ensureParentInfo = false;
#endif
#ifdef PROFILE_MEM
profileMemoryDump = true;
#endif
#ifdef ENABLE_SCRIPT_PROFILING
m_pProfileCallback = nullptr;
m_pProfileCallback2 = nullptr;
m_inProfileCallback = FALSE;
CleanupDocumentContext = nullptr;
#endif
// Do this after all operations that may cause potential exceptions. Note: InitialAllocations may still throw!
numberAllocator.Initialize(this->GetRecycler());
#if DEBUG
m_iProfileSession = -1;
#endif
#ifdef LEAK_REPORT
this->urlRecord = nullptr;
this->isRootTrackerScriptContext = false;
#endif
PERF_COUNTER_INC(Basic, ScriptContext);
PERF_COUNTER_INC(Basic, ScriptContextActive);
END_NO_EXCEPTION;
}
void ScriptContext::InitializeAllocations()
{
this->charClassifier = Anew(GeneralAllocator(), CharClassifier, this);
this->valueOfInlineCache = AllocatorNewZ(InlineCacheAllocator, GetInlineCacheAllocator(), InlineCache);
this->toStringInlineCache = AllocatorNewZ(InlineCacheAllocator, GetInlineCacheAllocator(), InlineCache);
#ifdef REJIT_STATS
rejitReasonCounts = AnewArrayZ(GeneralAllocator(), uint, NumRejitReasons);
rejitReasonCountsCap = AnewArrayZ(GeneralAllocator(), uint, NumRejitReasons);
bailoutReasonCounts = Anew(GeneralAllocator(), BailoutStatsMap, GeneralAllocator());
bailoutReasonCountsCap = Anew(GeneralAllocator(), BailoutStatsMap, GeneralAllocator());
#endif
#ifdef ENABLE_BASIC_TELEMETRY
this->telemetry = Anew(this->TelemetryAllocator(), ScriptContextTelemetry, *this);
#endif
#ifdef PROFILE_STRINGS
if (Js::Configuration::Global.flags.ProfileStrings)
{
stringProfiler = Anew(MiscAllocator(), StringProfiler, threadContext->GetPageAllocator());
}
#endif
intConstPropsOnGlobalObject = Anew(GeneralAllocator(), PropIdSetForConstProp, GeneralAllocator());
intConstPropsOnGlobalUserObject = Anew(GeneralAllocator(), PropIdSetForConstProp, GeneralAllocator());
#if ENABLE_NATIVE_CODEGEN
m_domFastPathHelperMap = HeapNew(JITDOMFastPathHelperMap, &HeapAllocator::Instance, 17);
#endif
this->debugContext = HeapNew(DebugContext, this);
}
void ScriptContext::EnsureClearDebugDocument()
{
if (this->sourceList)
{
this->sourceList->Map([=](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef) {
Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
if (sourceInfo)
{
sourceInfo->ClearDebugDocument();
}
});
}
}
void ScriptContext::ShutdownClearSourceLists()
{
if (this->sourceList)
{
// In the unclean shutdown case, we might not have destroyed the script context when
// this is called- in which case, skip doing this work and simply release the source list
// so that it doesn't show up as a leak. Since we're doing unclean shutdown, it's ok to
// skip cleanup here for expediency.
if (this->isClosed)
{
this->MapFunction([this](Js::FunctionBody* functionBody) {
Assert(functionBody->GetScriptContext() == this);
functionBody->CleanupSourceInfo(true);
});
}
EnsureClearDebugDocument();
// Don't need the source list any more so ok to release
this->sourceList.Unroot(this->GetRecycler());
}
if (this->calleeUtf8SourceInfoList)
{
this->calleeUtf8SourceInfoList.Unroot(this->GetRecycler());
}
}
ScriptContext::~ScriptContext()
{
// Take etw rundown lock on this thread context. We are going to change/destroy this scriptContext.
AutoCriticalSection autocs(GetThreadContext()->GetFunctionBodyLock());
#if ENABLE_NATIVE_CODEGEN
if (m_domFastPathHelperMap != nullptr)
{
HeapDelete(m_domFastPathHelperMap);
}
#endif
// TODO: Can we move this on Close()?
ClearHostScriptContext();
if (this->hasProtoOrStoreFieldInlineCache)
{
// TODO (PersistentInlineCaches): It really isn't necessary to clear inline caches in all script contexts.
// Since this script context is being destroyed, the inline cache arena will also go away and release its
// memory back to the page allocator. Thus, we cannot leave this script context's inline caches on the
// thread context's invalidation lists. However, it should suffice to remove this script context's caches
// without touching other script contexts' caches. We could call some form of RemoveInlineCachesFromInvalidationLists()
// on the inline cache allocator, which would walk all inline caches and zap values pointed to by strongRef.
// clear out all inline caches to remove our proto inline caches from the thread context
threadContext->ClearInlineCaches();
ClearInlineCaches();
Assert(!this->hasProtoOrStoreFieldInlineCache);
}
if (this->hasIsInstInlineCache)
{
// clear out all inline caches to remove our proto inline caches from the thread context
threadContext->ClearIsInstInlineCaches();
ClearIsInstInlineCaches();
Assert(!this->hasIsInstInlineCache);
}
// Only call RemoveFromPendingClose if we are in a pending close state.
if (isClosed && !isScriptContextActuallyClosed)
{
threadContext->RemoveFromPendingClose(this);
}
SetIsClosed();
bool closed = Close(true);
// JIT may access number allocator. Need to close the script context first,
// which will close the native code generator and abort any current job on this generator.
numberAllocator.Uninitialize();
ShutdownClearSourceLists();
if (regexStacks)
{
Adelete(RegexAllocator(), regexStacks);
regexStacks = nullptr;
}
if (javascriptLibrary != nullptr)
{
javascriptLibrary->scriptContext = nullptr;
javascriptLibrary = nullptr;
if (closed)
{
// if we just closed, we haven't unpin the object yet.
// We need to null out the script context in the global object first
// before we unpin the global object so that script context dtor doesn't get called twice
#if ENABLE_NATIVE_CODEGEN
Assert(this->IsClosedNativeCodeGenerator());
#endif
if (!GetThreadContext()->IsJSRT())
{
this->recycler->RootRelease(globalObject);
}
}
}
// Normally the JavascriptLibraryBase will unregister the scriptContext from the threadContext.
// In cases where we don't finish initialization e.g. OOM, manually unregister the scriptContext.
if (this->IsRegistered())
{
threadContext->UnregisterScriptContext(this);
}
#if ENABLE_BACKGROUND_PARSING
if (this->backgroundParser != nullptr)
{
BackgroundParser::Delete(this->backgroundParser);
this->backgroundParser = nullptr;
}
#endif
#if ENABLE_NATIVE_CODEGEN
if (this->nativeCodeGen != nullptr)
{
DeleteNativeCodeGenerator(this->nativeCodeGen);
nativeCodeGen = NULL;
}
if (jitFuncRangeCache != nullptr)
{
HeapDelete(jitFuncRangeCache);
jitFuncRangeCache = nullptr;
}
#endif
#if DYNAMIC_INTERPRETER_THUNK
if (this->interpreterThunkEmitter != nullptr)
{
HeapDelete(interpreterThunkEmitter);
this->interpreterThunkEmitter = NULL;
}
#endif
#ifdef ASMJS_PLAT
if (this->asmJsInterpreterThunkEmitter != nullptr)
{
HeapDelete(asmJsInterpreterThunkEmitter);
this->asmJsInterpreterThunkEmitter = nullptr;
}
if (this->asmJsCodeGenerator != nullptr)
{
HeapDelete(asmJsCodeGenerator);
this->asmJsCodeGenerator = NULL;
}
#endif
// In case there is something added to the list between close and dtor, just reset the list again
this->weakReferenceDictionaryList.Reset();
#if ENABLE_NATIVE_CODEGEN
if (m_remoteScriptContextAddr)
{
Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
if (JITManager::GetJITManager()->CleanupScriptContext(&m_remoteScriptContextAddr) == S_OK)
{
Assert(m_remoteScriptContextAddr == nullptr);
}
m_remoteScriptContextAddr = nullptr;
}
#endif
PERF_COUNTER_DEC(Basic, ScriptContext);
}
void ScriptContext::SetUrl(BSTR bstrUrl)
{
// Assumption: this method is never called multiple times
Assert(this->url != nullptr && wcslen(this->url) == 0);
charcount_t length = SysStringLen(bstrUrl) + 1; // Add 1 for the NULL.
char16* urlCopy = AnewArray(this->GeneralAllocator(), char16, length);
js_memcpy_s(urlCopy, (length - 1) * sizeof(char16), bstrUrl, (length - 1) * sizeof(char16));
urlCopy[length - 1] = _u('\0');
this->url = urlCopy;
#ifdef LEAK_REPORT
if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
{
this->urlRecord = LeakReport::LogUrl(urlCopy, this->globalObject);
}
#endif
}
uint ScriptContext::GetNextSourceContextId()
{
Assert(this->Cache()->sourceContextInfoMap ||
this->Cache()->dynamicSourceContextInfoMap);
uint nextSourceContextId = 0;
if (this->Cache()->sourceContextInfoMap)
{
nextSourceContextId = this->Cache()->sourceContextInfoMap->Count();
}
if (this->Cache()->dynamicSourceContextInfoMap)
{
nextSourceContextId += this->Cache()->dynamicSourceContextInfoMap->Count();
}
return nextSourceContextId + 1;
}
// Do most of the Close() work except the final release which could delete the scriptContext.
void ScriptContext::InternalClose()
{
isScriptContextActuallyClosed = true;
PERF_COUNTER_DEC(Basic, ScriptContextActive);
#if DBG_DUMP
if (Js::Configuration::Global.flags.TraceWin8Allocations)
{
Output::Print(_u("MemoryTrace: ScriptContext Close\n"));
Output::Flush();
}
#endif
JS_ETW_INTERNAL(EventWriteJSCRIPT_HOST_SCRIPT_CONTEXT_CLOSE(this));
#if ENABLE_TTD
if(this->TTDWellKnownInfo != nullptr)
{
TT_HEAP_DELETE(TTD::RuntimeContextInfo, this->TTDWellKnownInfo);
this->TTDWellKnownInfo = nullptr;
}
if(this->TTDContextInfo != nullptr)
{
TT_HEAP_DELETE(TTD::ScriptContextTTD, this->TTDContextInfo);
this->TTDContextInfo = nullptr;
}
#endif
#if ENABLE_NATIVE_CODEGEN
if (nativeCodeGen != nullptr)
{
Assert(!isInitialized || this->globalObject != nullptr);
CloseNativeCodeGenerator(this->nativeCodeGen);
}
#endif
{
// Take lock on the function bodies to sync with the etw source rundown if any.
AutoCriticalSection autocs(GetThreadContext()->GetFunctionBodyLock());
if (this->sourceList)
{
bool hasFunctions = false;
this->sourceList->MapUntil([&hasFunctions](int, RecyclerWeakReference<Utf8SourceInfo>* sourceInfoWeakRef) -> bool
{
Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
if (sourceInfo)
{
hasFunctions = sourceInfo->HasFunctions();
}
return hasFunctions;
});
if (hasFunctions)
{
// We still need to walk through all the function bodies and call cleanup
// because otherwise ETW events might not get fired if a GC doesn't happen
// and the thread context isn't shut down cleanly (process detach case)
this->MapFunction([this](Js::FunctionBody* functionBody) {
Assert(functionBody->GetScriptContext() == nullptr || functionBody->GetScriptContext() == this);
functionBody->Cleanup(/* isScriptContextClosing */ true);
});
}
}
}
this->GetThreadContext()->SubSourceSize(this->GetSourceSize());
#if DYNAMIC_INTERPRETER_THUNK
if (this->interpreterThunkEmitter != nullptr)
{
this->interpreterThunkEmitter->Close();
}
#endif
#ifdef ASMJS_PLAT
if (this->asmJsInterpreterThunkEmitter != nullptr)
{
this->asmJsInterpreterThunkEmitter->Close();
}
#endif
#ifdef ENABLE_SCRIPT_PROFILING
// Stop profiling if present
DeRegisterProfileProbe(S_OK, nullptr);
#endif
this->EnsureClearDebugDocument();
if (this->debugContext != nullptr)
{
if(this->debugContext->GetProbeContainer())
{
this->debugContext->GetProbeContainer()->UninstallInlineBreakpointProbe(NULL);
this->debugContext->GetProbeContainer()->UninstallDebuggerScriptOptionCallback();
}
// Guard the closing and deleting of DebugContext as in meantime PDM might
// call OnBreakFlagChange
AutoCriticalSection autoDebugContextCloseCS(&debugContextCloseCS);
DebugContext* tempDebugContext = this->debugContext;
this->debugContext = nullptr;
tempDebugContext->Close();
HeapDelete(tempDebugContext);
}
if (this->diagnosticArena != nullptr)
{
HeapDelete(this->diagnosticArena);
this->diagnosticArena = nullptr;
}
// Need to print this out before the native code gen is deleted
// which will delete the codegenProfiler
#ifdef PROFILE_EXEC
if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
{
if (isProfilerCreated)
{
this->ProfilePrint();
}
if (profiler != nullptr)
{
profiler->Release();
profiler = nullptr;
}
}
#endif
#if ENABLE_PROFILE_INFO
// Release this only after native code gen is shut down, as there may be
// profile info allocated from the SourceDynamicProfileManager arena.
// The first condition might not be true if the dynamic functions have already been freed by the time
// ScriptContext closes
if (referencesSharedDynamicSourceContextInfo)
{
// For the host provided dynamic code, we may not have added any dynamic context to the dynamicSourceContextInfoMap
Assert(this->GetDynamicSourceContextInfoMap() != nullptr);
this->GetThreadContext()->ReleaseSourceDynamicProfileManagers(this->GetUrl());
}
#endif
RECYCLER_PERF_COUNTER_SUB(BindReference, bindReferenceCount);
if (this->interpreterArena)
{
ReleaseInterpreterArena();
interpreterArena = nullptr;
}
if (this->guestArena)
{
ReleaseGuestArena();
guestArena = nullptr;
}
builtInLibraryFunctions = nullptr;
pActiveScriptDirect = nullptr;
isWeakReferenceDictionaryListCleared = true;
this->weakReferenceDictionaryList.Clear(this->GeneralAllocator());
if (registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext != nullptr)
{
// UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext may throw, set up the correct state first
ScriptContext ** registeredScriptContext = registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext;
ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches();
Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr);
threadContext->UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(registeredScriptContext);
}
threadContext->ReleaseDebugManager();
// This can be null if the script context initialization threw
// and InternalClose gets called in the destructor code path
if (javascriptLibrary != nullptr)
{
javascriptLibrary->CleanupForClose();
javascriptLibrary->Uninitialize();
this->ClearScriptContextCaches();
}
}
bool ScriptContext::Close(bool inDestructor)
{
if (isScriptContextActuallyClosed)
return false;
InternalClose();
if (!inDestructor && globalObject != nullptr)
{
//A side effect of releasing globalObject that this script context could be deleted, so the release call here
//must be the last thing in close.
#if ENABLE_NATIVE_CODEGEN
Assert(this->IsClosedNativeCodeGenerator());
#endif
if (!GetThreadContext()->IsJSRT())
{
GetRecycler()->RootRelease(globalObject);
}
globalObject = nullptr;
}
// A script context closing is a signal to the thread context that it
// needs to do an idle GC independent of what the heuristics are
this->threadContext->SetForceOneIdleCollection();
return true;
}
PropertyString* ScriptContext::GetPropertyString2(char16 ch1, char16 ch2)
{
if (ch1 < '0' || ch1 > 'z' || ch2 < '0' || ch2 > 'z')
{
return NULL;
}
const uint i = PropertyStringMap::PStrMapIndex(ch1);
if (this->Cache()->propertyStrings[i] == NULL)
{
return NULL;
}
const uint j = PropertyStringMap::PStrMapIndex(ch2);
return this->Cache()->propertyStrings[i]->strLen2[j];
}
void ScriptContext::FindPropertyRecord(JavascriptString *pstName, PropertyRecord const ** propertyRecord)
{
threadContext->FindPropertyRecord(pstName, propertyRecord);
}
void ScriptContext::FindPropertyRecord(__in LPCWSTR propertyName, __in int propertyNameLength, PropertyRecord const ** propertyRecord)
{
threadContext->FindPropertyRecord(propertyName, propertyNameLength, propertyRecord);
}
JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* ScriptContext::FindPropertyIdNoCase(__in LPCWSTR propertyName, __in int propertyNameLength)
{
return threadContext->FindPropertyIdNoCase(this, propertyName, propertyNameLength);
}
PropertyId ScriptContext::GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName)
{
Js::PropertyRecord const * propertyRecord;
threadContext->GetOrAddPropertyId(propName, &propertyRecord);
this->TrackPid(propertyRecord);
return propertyRecord->GetPropertyId();
}
void ScriptContext::GetOrAddPropertyRecord(JsUtil::CharacterBuffer<WCHAR> const& propertyName, PropertyRecord const ** propertyRecord)
{
threadContext->GetOrAddPropertyId(propertyName, propertyRecord);
}
PropertyId ScriptContext::GetOrAddPropertyIdTracked(__in_ecount(propertyNameLength) LPCWSTR propertyName, __in int propertyNameLength)
{
Js::PropertyRecord const * propertyRecord;
threadContext->GetOrAddPropertyId(propertyName, propertyNameLength, &propertyRecord);
if (propertyNameLength == 2)
{
CachePropertyString2(propertyRecord);
}
this->TrackPid(propertyRecord);
return propertyRecord->GetPropertyId();
}
void ScriptContext::GetOrAddPropertyRecord(__in_ecount(propertyNameLength) LPCWSTR propertyName, __in int propertyNameLength, PropertyRecord const ** propertyRecord)
{
threadContext->GetOrAddPropertyId(propertyName, propertyNameLength, propertyRecord);
if (propertyNameLength == 2)
{
CachePropertyString2(*propertyRecord);
}
}
BOOL ScriptContext::IsNumericPropertyId(PropertyId propertyId, uint32* value)
{
BOOL isNumericPropertyId = threadContext->IsNumericPropertyId(propertyId, value);
#if DEBUG
PropertyRecord const * name = this->GetPropertyName(propertyId);
if (name != nullptr)
{
// Symbol properties are not numeric - description should not be used.
if (name->IsSymbol())
{
return false;
}
uint32 index;
BOOL isIndex = JavascriptArray::GetIndex(name->GetBuffer(), &index);
if (isNumericPropertyId != isIndex)
{
// WOOB 1137798: JavascriptArray::GetIndex does not handle embedded NULLs. So if we have a property
// name "1234\0", JavascriptArray::GetIndex would incorrectly accepts it as an array index property
// name.
Assert((size_t)(name->GetLength()) != wcslen(name->GetBuffer()));
}
else if (isNumericPropertyId)
{
Assert((uint32)*value == index);
}
}
#endif
return isNumericPropertyId;
}
void ScriptContext::RegisterWeakReferenceDictionary(JsUtil::IWeakReferenceDictionary* weakReferenceDictionary)
{
this->weakReferenceDictionaryList.Prepend(this->GeneralAllocator(), weakReferenceDictionary);
}
RecyclableObject *ScriptContext::GetMissingPropertyResult()
{
return GetLibrary()->GetUndefined();
}
RecyclableObject *ScriptContext::GetMissingItemResult()
{
return GetLibrary()->GetUndefined();
}
SRCINFO *ScriptContext::AddHostSrcInfo(SRCINFO const *pSrcInfo)
{
Assert(pSrcInfo != nullptr);
return RecyclerNewZ(this->GetRecycler(), SRCINFO, *pSrcInfo);
}
#ifdef PROFILE_TYPES
void ScriptContext::ProfileTypes()
{
Output::Print(_u("===============================================================================\n"));
Output::Print(_u("Types Profile %s\n"), this->url);
Output::Print(_u("-------------------------------------------------------------------------------\n"));
Output::Print(_u("Dynamic Type Conversions:\n"));
Output::Print(_u(" Null to Simple %8d\n"), convertNullToSimpleCount);
Output::Print(_u(" Deferred to SimpleMap %8d\n"), convertDeferredToSimpleDictionaryCount);
Output::Print(_u(" Simple to Map %8d\n"), convertSimpleToDictionaryCount);
Output::Print(_u(" Simple to SimpleMap %8d\n"), convertSimpleToSimpleDictionaryCount);
Output::Print(_u(" Path to SimpleMap (set) %8d\n"), convertPathToDictionaryCount1);
Output::Print(_u(" Path to SimpleMap (delete) %8d\n"), convertPathToDictionaryCount2);
Output::Print(_u(" Path to SimpleMap (attribute) %8d\n"), convertPathToDictionaryCount3);
Output::Print(_u(" Path to SimpleMap %8d\n"), convertPathToSimpleDictionaryCount);
Output::Print(_u(" SimplePath to Path %8d\n"), convertSimplePathToPathCount);
Output::Print(_u(" Shared SimpleMap to non-shared %8d\n"), convertSimpleSharedDictionaryToNonSharedCount);
Output::Print(_u(" Deferred to Map %8d\n"), convertDeferredToDictionaryCount);
Output::Print(_u(" Path to Map (accessor) %8d\n"), convertPathToDictionaryCount4);
Output::Print(_u(" SimpleMap to Map %8d\n"), convertSimpleDictionaryToDictionaryCount);
Output::Print(_u(" Path Cache Hits %8d\n"), cacheCount);
Output::Print(_u(" Path Branches %8d\n"), branchCount);
Output::Print(_u(" Path Promotions %8d\n"), promoteCount);
Output::Print(_u(" Path Length (max) %8d\n"), maxPathLength);
Output::Print(_u(" SimplePathTypeHandlers %8d\n"), simplePathTypeHandlerCount);
Output::Print(_u(" PathTypeHandlers %8d\n"), pathTypeHandlerCount);
Output::Print(_u("\n"));
Output::Print(_u("Type Statistics: %8s %8s\n"), _u("Types"), _u("Instances"));
Output::Print(_u(" Undefined %8d %8d\n"), typeCount[TypeIds_Undefined], instanceCount[TypeIds_Undefined]);
Output::Print(_u(" Null %8d %8d\n"), typeCount[TypeIds_Null], instanceCount[TypeIds_Null]);
Output::Print(_u(" Boolean %8d %8d\n"), typeCount[TypeIds_Boolean], instanceCount[TypeIds_Boolean]);
Output::Print(_u(" Integer %8d %8d\n"), typeCount[TypeIds_Integer], instanceCount[TypeIds_Integer]);
Output::Print(_u(" Number %8d %8d\n"), typeCount[TypeIds_Number], instanceCount[TypeIds_Number]);
Output::Print(_u(" String %8d %8d\n"), typeCount[TypeIds_String], instanceCount[TypeIds_String]);
Output::Print(_u(" Object %8d %8d\n"), typeCount[TypeIds_Object], instanceCount[TypeIds_Object]);
Output::Print(_u(" Function %8d %8d\n"), typeCount[TypeIds_Function], instanceCount[TypeIds_Function]);
Output::Print(_u(" Array %8d %8d\n"), typeCount[TypeIds_Array], instanceCount[TypeIds_Array]);
Output::Print(_u(" Date %8d %8d\n"), typeCount[TypeIds_Date], instanceCount[TypeIds_Date] + instanceCount[TypeIds_WinRTDate]);
Output::Print(_u(" Symbol %8d %8d\n"), typeCount[TypeIds_Symbol], instanceCount[TypeIds_Symbol]);
Output::Print(_u(" RegEx %8d %8d\n"), typeCount[TypeIds_RegEx], instanceCount[TypeIds_RegEx]);
Output::Print(_u(" Error %8d %8d\n"), typeCount[TypeIds_Error], instanceCount[TypeIds_Error]);
Output::Print(_u(" Proxy %8d %8d\n"), typeCount[TypeIds_Proxy], instanceCount[TypeIds_Proxy]);
Output::Print(_u(" BooleanObject %8d %8d\n"), typeCount[TypeIds_BooleanObject], instanceCount[TypeIds_BooleanObject]);
Output::Print(_u(" NumberObject %8d %8d\n"), typeCount[TypeIds_NumberObject], instanceCount[TypeIds_NumberObject]);
Output::Print(_u(" StringObject %8d %8d\n"), typeCount[TypeIds_StringObject], instanceCount[TypeIds_StringObject]);
Output::Print(_u(" SymbolObject %8d %8d\n"), typeCount[TypeIds_SymbolObject], instanceCount[TypeIds_SymbolObject]);
Output::Print(_u(" GlobalObject %8d %8d\n"), typeCount[TypeIds_GlobalObject], instanceCount[TypeIds_GlobalObject]);
Output::Print(_u(" Enumerator %8d %8d\n"), typeCount[TypeIds_Enumerator], instanceCount[TypeIds_Enumerator]);
Output::Print(_u(" Int8Array %8d %8d\n"), typeCount[TypeIds_Int8Array], instanceCount[TypeIds_Int8Array]);
Output::Print(_u(" Uint8Array %8d %8d\n"), typeCount[TypeIds_Uint8Array], instanceCount[TypeIds_Uint8Array]);
Output::Print(_u(" Uint8ClampedArray %8d %8d\n"), typeCount[TypeIds_Uint8ClampedArray], instanceCount[TypeIds_Uint8ClampedArray]);
Output::Print(_u(" Int16Array %8d %8d\n"), typeCount[TypeIds_Int16Array], instanceCount[TypeIds_Int16Array]);
Output::Print(_u(" Int16Array %8d %8d\n"), typeCount[TypeIds_Uint16Array], instanceCount[TypeIds_Uint16Array]);
Output::Print(_u(" Int32Array %8d %8d\n"), typeCount[TypeIds_Int32Array], instanceCount[TypeIds_Int32Array]);
Output::Print(_u(" Uint32Array %8d %8d\n"), typeCount[TypeIds_Uint32Array], instanceCount[TypeIds_Uint32Array]);
Output::Print(_u(" Float32Array %8d %8d\n"), typeCount[TypeIds_Float32Array], instanceCount[TypeIds_Float32Array]);
Output::Print(_u(" Float64Array %8d %8d\n"), typeCount[TypeIds_Float64Array], instanceCount[TypeIds_Float64Array]);
Output::Print(_u(" DataView %8d %8d\n"), typeCount[TypeIds_DataView], instanceCount[TypeIds_DataView]);
Output::Print(_u(" ModuleRoot %8d %8d\n"), typeCount[TypeIds_ModuleRoot], instanceCount[TypeIds_ModuleRoot]);
Output::Print(_u(" HostObject %8d %8d\n"), typeCount[TypeIds_HostObject], instanceCount[TypeIds_HostObject]);
Output::Print(_u(" VariantDate %8d %8d\n"), typeCount[TypeIds_VariantDate], instanceCount[TypeIds_VariantDate]);
Output::Print(_u(" HostDispatch %8d %8d\n"), typeCount[TypeIds_HostDispatch], instanceCount[TypeIds_HostDispatch]);
Output::Print(_u(" Arguments %8d %8d\n"), typeCount[TypeIds_Arguments], instanceCount[TypeIds_Arguments]);
Output::Print(_u(" ActivationObject %8d %8d\n"), typeCount[TypeIds_ActivationObject], instanceCount[TypeIds_ActivationObject]);
Output::Print(_u(" Map %8d %8d\n"), typeCount[TypeIds_Map], instanceCount[TypeIds_Map]);
Output::Print(_u(" Set %8d %8d\n"), typeCount[TypeIds_Set], instanceCount[TypeIds_Set]);
Output::Print(_u(" WeakMap %8d %8d\n"), typeCount[TypeIds_WeakMap], instanceCount[TypeIds_WeakMap]);
Output::Print(_u(" WeakSet %8d %8d\n"), typeCount[TypeIds_WeakSet], instanceCount[TypeIds_WeakSet]);
Output::Print(_u(" ArrayIterator %8d %8d\n"), typeCount[TypeIds_ArrayIterator], instanceCount[TypeIds_ArrayIterator]);
Output::Print(_u(" MapIterator %8d %8d\n"), typeCount[TypeIds_MapIterator], instanceCount[TypeIds_MapIterator]);
Output::Print(_u(" SetIterator %8d %8d\n"), typeCount[TypeIds_SetIterator], instanceCount[TypeIds_SetIterator]);
Output::Print(_u(" StringIterator %8d %8d\n"), typeCount[TypeIds_StringIterator], instanceCount[TypeIds_StringIterator]);
Output::Print(_u(" Generator %8d %8d\n"), typeCount[TypeIds_Generator], instanceCount[TypeIds_Generator]);
#if !DBG
Output::Print(_u(" ** Instance statistics only available on debug builds...\n"));
#endif
Output::Flush();
}
#endif
#ifdef PROFILE_OBJECT_LITERALS
void ScriptContext::ProfileObjectLiteral()
{