-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathJavascriptFunction.cpp
3505 lines (3092 loc) · 136 KB
/
JavascriptFunction.cpp
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 "RuntimeLibraryPch.h"
#include "Library/StackScriptFunction.h"
#include "Types/SpreadArgument.h"
#include "Language/AsmJsTypes.h"
#ifdef _M_X64
#include "ByteCode/PropertyIdArray.h"
#include "Language/AsmJsModule.h"
#endif
#ifdef _M_IX86
#ifdef _CONTROL_FLOW_GUARD
extern "C" PVOID __guard_check_icall_fptr;
#endif
extern "C" void __cdecl _alloca_probe_16();
#endif
using namespace Js;
// The VS2013 linker treats this as a redefinition of an already
// defined constant and complains. So skip the declaration if we're compiling
// with VS2013 or below.
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const charcount_t JavascriptFunction::DIAG_MAX_FUNCTION_STRING;
#endif
DEFINE_RECYCLER_TRACKER_PERF_COUNTER(JavascriptFunction);
JavascriptFunction::JavascriptFunction(DynamicType * type)
: DynamicObject(type), functionInfo(nullptr), constructorCache(&ConstructorCache::DefaultInstance)
{
Assert(this->constructorCache != nullptr);
}
JavascriptFunction::JavascriptFunction(DynamicType * type, FunctionInfo * functionInfo)
: DynamicObject(type), functionInfo(functionInfo), constructorCache(&ConstructorCache::DefaultInstance)
{
Assert(this->constructorCache != nullptr);
this->GetTypeHandler()->ClearHasOnlyWritableDataProperties(); // length is non-writable
if (GetTypeHandler()->GetFlags() & DynamicTypeHandler::IsPrototypeFlag)
{
// No need to invalidate store field caches for non-writable properties here. Since this type is just being created, it cannot represent
// an object that is already a prototype. If it becomes a prototype and then we attempt to add a property to an object derived from this
// object, then we will check if this property is writable, and only if it is will we do the fast path for add property.
// GetScriptContext()->InvalidateStoreFieldCaches(PropertyIds::length);
GetLibrary()->GetTypesWithOnlyWritablePropertyProtoChainCache()->Clear();
}
}
JavascriptFunction::JavascriptFunction(DynamicType * type, FunctionInfo * functionInfo, ConstructorCache* cache)
: DynamicObject(type), functionInfo(functionInfo), constructorCache(cache)
{
Assert(this->constructorCache != nullptr);
this->GetTypeHandler()->ClearHasOnlyWritableDataProperties(); // length is non-writable
if (GetTypeHandler()->GetFlags() & DynamicTypeHandler::IsPrototypeFlag)
{
// No need to invalidate store field caches for non-writable properties here. Since this type is just being created, it cannot represent
// an object that is already a prototype. If it becomes a prototype and then we attempt to add a property to an object derived from this
// object, then we will check if this property is writable, and only if it is will we do the fast path for add property.
// GetScriptContext()->InvalidateStoreFieldCaches(PropertyIds::length);
GetLibrary()->GetTypesWithOnlyWritablePropertyProtoChainCache()->Clear();
}
}
FunctionProxy *JavascriptFunction::GetFunctionProxy() const
{
Assert(functionInfo != nullptr);
return functionInfo->GetFunctionProxy();
}
ParseableFunctionInfo *JavascriptFunction::GetParseableFunctionInfo() const
{
Assert(functionInfo != nullptr);
return functionInfo->GetParseableFunctionInfo();
}
DeferDeserializeFunctionInfo *JavascriptFunction::GetDeferDeserializeFunctionInfo() const
{
Assert(functionInfo != nullptr);
return functionInfo->GetDeferDeserializeFunctionInfo();
}
FunctionBody *JavascriptFunction::GetFunctionBody() const
{
Assert(functionInfo != nullptr);
return functionInfo->GetFunctionBody();
}
BOOL JavascriptFunction::IsScriptFunction() const
{
Assert(functionInfo != nullptr);
return functionInfo->HasBody();
}
template <> bool Js::VarIsImpl<JavascriptFunction>(RecyclableObject* obj)
{
return JavascriptOperators::GetTypeId(obj) == TypeIds_Function;
}
BOOL JavascriptFunction::IsStrictMode() const
{
FunctionProxy * proxy = this->GetFunctionProxy();
return proxy && proxy->EnsureDeserialized()->GetIsStrictMode();
}
BOOL JavascriptFunction::IsLambda() const
{
return this->GetFunctionInfo()->IsLambda();
}
BOOL JavascriptFunction::IsConstructor() const
{
return this->GetFunctionInfo()->IsConstructor();
}
#if DBG
/* static */
bool JavascriptFunction::IsBuiltinProperty(Var objectWithProperty, PropertyIds propertyId)
{
return VarIs<ScriptFunctionBase>(objectWithProperty)
&& (propertyId == PropertyIds::length || (VarTo<JavascriptFunction>(objectWithProperty)->HasRestrictedProperties() && (propertyId == PropertyIds::arguments || propertyId == PropertyIds::caller)));
}
#endif
Var JavascriptFunction::NewInstanceHelper(ScriptContext *scriptContext, RecyclableObject* function, CallInfo callInfo, Js::ArgumentReader& args, FunctionKind functionKind /* = FunctionKind::Normal */)
{
JavascriptLibrary* library = function->GetLibrary();
AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
bool isAsync = functionKind == FunctionKind::Async || functionKind == FunctionKind::AsyncGenerator;
bool isGenerator = functionKind == FunctionKind::Generator || functionKind == FunctionKind::AsyncGenerator;
// SkipDefaultNewObject function flag should have prevented the default object from
// being created, except when call true a host dispatch.
Var newTarget = args.GetNewTarget();
bool isCtorSuperCall = JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);
JavascriptString* separator = library->GetCommaDisplayString();
// Gather all the formals into a string like (fml1, fml2, fml3)
JavascriptString *formals = library->GetOpenRBracketString();
for (uint i = 1; i < args.Info.Count - 1; ++i)
{
if (i != 1)
{
formals = JavascriptString::Concat(formals, separator);
}
formals = JavascriptString::Concat(formals, JavascriptConversion::ToString(args.Values[i], scriptContext));
}
formals = JavascriptString::Concat(formals, library->GetNewLineCloseRBracketString());
// Function body, last argument to Function(...)
JavascriptString *fnBody = NULL;
if (args.Info.Count > 1)
{
fnBody = JavascriptConversion::ToString(args.Values[args.Info.Count - 1], scriptContext);
}
// Create a string representing the anonymous function
Assert(
0 + // "function anonymous" GetFunctionAnonymousString
0 + // "(" GetOpenRBracketString
1 + // "\n)" GetNewLineCloseRBracketString
0 // " {" GetSpaceOpenBracketString
== numberLinesPrependedToAnonymousFunction); // Be sure to add exactly one line to anonymous function
JavascriptString *bs = functionKind == FunctionKind::Async ?
library->GetAsyncFunctionAnonymousString() :
functionKind == FunctionKind::Generator ?
library->GetFunctionPTRAnonymousString() :
functionKind == FunctionKind::AsyncGenerator ?
library->GetAsyncGeneratorAnonymousString() :
library->GetFunctionAnonymousString();
bs = JavascriptString::Concat(bs, formals);
bs = JavascriptString::Concat(bs, library->GetSpaceOpenBracketString());
if (fnBody != NULL)
{
bs = JavascriptString::Concat(bs, fnBody);
}
bs = JavascriptString::Concat(bs, library->GetNewLineCloseBracketString());
// Bug 1105479. Get the module id from the caller
ModuleID moduleID = kmodGlobal;
BOOL strictMode = FALSE;
JavascriptFunction* pfuncScript;
FunctionInfo *pfuncInfoCache = NULL;
char16 const * sourceString = bs->GetSz();
charcount_t sourceLen = bs->GetLength();
EvalMapString key(bs, sourceString, sourceLen, moduleID, strictMode, /* isLibraryCode = */ false);
if (!scriptContext->IsInNewFunctionMap(key, &pfuncInfoCache))
{
// Validate formals here
scriptContext->GetGlobalObject()->ValidateSyntax(
scriptContext, formals->GetSz(), formals->GetLength(),
isGenerator, isAsync,
&Parser::ValidateFormals);
if (fnBody != NULL)
{
// Validate function body
scriptContext->GetGlobalObject()->ValidateSyntax(
scriptContext, fnBody->GetSz(), fnBody->GetLength(),
isGenerator, isAsync,
&Parser::ValidateSourceElementList);
}
pfuncScript = scriptContext->GetGlobalObject()->EvalHelper(scriptContext, sourceString, sourceLen, moduleID, fscrCanDeferFncParse, Constants::FunctionCode, TRUE, TRUE, strictMode);
// Indicate that this is a top-level function. We don't pass the fscrGlobalCode flag to the eval helper,
// or it will return the global function that wraps the declared function body, as though it were an eval.
// But we want, for instance, to be able to verify that we did the right amount of deferred parsing.
ParseableFunctionInfo *functionInfo = pfuncScript->GetParseableFunctionInfo();
Assert(functionInfo);
functionInfo->SetGrfscr(functionInfo->GetGrfscr() | fscrGlobalCode);
#if ENABLE_TTD
if(!scriptContext->IsTTDRecordOrReplayModeEnabled())
{
scriptContext->AddToNewFunctionMap(key, functionInfo->GetFunctionInfo());
}
#else
scriptContext->AddToNewFunctionMap(key, functionInfo->GetFunctionInfo());
#endif
}
else if (pfuncInfoCache->IsCoroutine())
{
pfuncScript = scriptContext->GetLibrary()->CreateGeneratorVirtualScriptFunction(pfuncInfoCache->GetFunctionProxy());
}
else
{
pfuncScript = scriptContext->GetLibrary()->CreateScriptFunction(pfuncInfoCache->GetFunctionProxy());
}
#if ENABLE_TTD
//
//TODO: We may (probably?) want to use the debugger source rundown functionality here instead
//
if(pfuncScript != nullptr && (scriptContext->IsTTDRecordModeEnabled() || scriptContext->ShouldPerformReplayAction()))
{
//Make sure we have the body and text information available
FunctionBody* globalBody = TTD::JsSupport::ForceAndGetFunctionBody(pfuncScript->GetParseableFunctionInfo());
if(!scriptContext->TTDContextInfo->IsBodyAlreadyLoadedAtTopLevel(globalBody))
{
uint32 bodyIdCtr = 0;
if(scriptContext->IsTTDRecordModeEnabled())
{
const TTD::NSSnapValues::TopLevelNewFunctionBodyResolveInfo* tbfi = scriptContext->GetThreadContext()->TTDLog->AddNewFunction(globalBody, moduleID, sourceString, sourceLen);
//We always want to register the top-level load but we don't always need to log the event
if(scriptContext->ShouldPerformRecordAction())
{
scriptContext->GetThreadContext()->TTDLog->RecordTopLevelCodeAction(tbfi->TopLevelBase.TopLevelBodyCtr);
}
bodyIdCtr = tbfi->TopLevelBase.TopLevelBodyCtr;
}
if(scriptContext->ShouldPerformReplayAction())
{
bodyIdCtr = scriptContext->GetThreadContext()->TTDLog->ReplayTopLevelCodeAction();
}
//walk global body to (1) add functions to pin set (2) build parent map
scriptContext->TTDContextInfo->ProcessFunctionBodyOnLoad(globalBody, nullptr);
scriptContext->TTDContextInfo->RegisterNewScript(globalBody, bodyIdCtr);
if(scriptContext->ShouldPerformRecordOrReplayAction())
{
globalBody->GetUtf8SourceInfo()->SetSourceInfoForDebugReplay_TTD(bodyIdCtr);
}
if(scriptContext->ShouldPerformReplayDebuggerAction())
{
scriptContext->GetThreadContext()->TTDExecutionInfo->ProcessScriptLoad(scriptContext, bodyIdCtr, globalBody, globalBody->GetUtf8SourceInfo(), nullptr);
}
}
}
#endif
JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_FUNCTION(pfuncScript, EtwTrace::GetFunctionId(pfuncScript->GetFunctionProxy())));
if (isGenerator || isAsync)
{
Assert(pfuncScript->GetFunctionInfo()->IsCoroutine());
auto pfuncVirt = static_cast<GeneratorVirtualScriptFunction*>(pfuncScript);
auto pfuncGen = functionKind == FunctionKind::Async ?
scriptContext->GetLibrary()->CreateAsyncFunction(JavascriptAsyncFunction::EntryAsyncFunctionImplementation, pfuncVirt) :
functionKind == FunctionKind::AsyncGenerator ?
scriptContext->GetLibrary()->CreateAsyncGeneratorFunction(JavascriptAsyncGeneratorFunction::EntryAsyncGeneratorFunctionImplementation, pfuncVirt) :
scriptContext->GetLibrary()->CreateGeneratorFunction(JavascriptGeneratorFunction::EntryGeneratorFunctionImplementation, pfuncVirt);
pfuncVirt->SetRealGeneratorFunction(pfuncGen);
pfuncScript = pfuncGen;
}
return isCtorSuperCall ?
JavascriptOperators::OrdinaryCreateFromConstructor(VarTo<RecyclableObject>(newTarget), pfuncScript, nullptr, scriptContext) :
pfuncScript;
}
Var JavascriptFunction::NewInstanceRestrictedMode(RecyclableObject* function, CallInfo callInfo, ...)
{
ScriptContext* scriptContext = function->GetScriptContext();
scriptContext->CheckEvalRestriction();
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
return NewInstanceHelper(scriptContext, function, callInfo, args);
}
Var JavascriptFunction::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
return NewInstanceHelper(scriptContext, function, callInfo, args);
}
Var JavascriptFunction::NewAsyncGeneratorFunctionInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
// Get called when creating a new async generator function through the constructor (e.g. agf.__proto__.constructor)
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
return JavascriptFunction::NewInstanceHelper(function->GetScriptContext(), function, callInfo, args, JavascriptFunction::FunctionKind::AsyncGenerator);
}
Var JavascriptFunction::NewAsyncGeneratorFunctionInstanceRestrictedMode(RecyclableObject* function, CallInfo callInfo, ...)
{
ScriptContext* scriptContext = function->GetScriptContext();
scriptContext->CheckEvalRestriction();
PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
return JavascriptFunction::NewInstanceHelper(scriptContext, function, callInfo, args, JavascriptFunction::FunctionKind::AsyncGenerator);
}
Var JavascriptFunction::NewAsyncFunctionInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
// Get called when creating a new async function through the constructor (e.g. af.__proto__.constructor)
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
return JavascriptFunction::NewInstanceHelper(function->GetScriptContext(), function, callInfo, args, JavascriptFunction::FunctionKind::Async);
}
Var JavascriptFunction::NewAsyncFunctionInstanceRestrictedMode(RecyclableObject* function, CallInfo callInfo, ...)
{
ScriptContext* scriptContext = function->GetScriptContext();
scriptContext->CheckEvalRestriction();
PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
return JavascriptFunction::NewInstanceHelper(scriptContext, function, callInfo, args, JavascriptFunction::FunctionKind::Async);
}
//
// Dummy EntryPoint for Function.prototype
//
Var JavascriptFunction::PrototypeEntryPoint(RecyclableObject* function, CallInfo callInfo, ...)
{
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
JavascriptLibrary* library = function->GetLibrary();
AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
if (callInfo.Flags & CallFlags_New)
{
JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
}
return library->GetUndefined();
}
enum : unsigned { STACK_ARGS_ALLOCA_THRESHOLD = 8 }; // Number of stack args we allow before using _alloca
// ES5 15.3.4.3
//When the apply method is called on an object func with arguments thisArg and argArray the following steps are taken:
// 1. If IsCallable(func) is false, then throw a TypeError exception.
// 2. If argArray is null or undefined, then
// a. Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and an empty list of arguments.
// 3. If Type(argArray) is not Object, then throw a TypeError exception.
// 4. Let len be the result of calling the [[Get]] internal method of argArray with argument "length".
//
// Steps 5 and 7 deleted from July 19 Errata of ES5 spec
//
// 5. If len is null or undefined, then throw a TypeError exception.
// 6. Len n be ToUint32(len).
// 7. If n is not equal to ToNumber(len), then throw a TypeError exception.
// 8. Let argList be an empty List.
// 9. Let index be 0.
// 10. Repeat while index < n
// a. Let indexName be ToString(index).
// b. Let nextArg be the result of calling the [[Get]] internal method of argArray with indexName as the argument.
// c. Append nextArg as the last element of argList.
// d. Set index to index + 1.
// 11. Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.
// The length property of the apply method is 2.
Var JavascriptFunction::EntryApply(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
// Ideally, we want to maintain CallFlags_Eval behavior and pass along the extra FrameDisplay parameter
// but that we would be a bigger change than what we want to do in this ship cycle. See WIN8: 915315.
// If eval is executed using apply it will not get the frame display and always execute in global scope.
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
///
/// Check Argument[0] has internal [[Call]] property
/// If not, throw TypeError
///
if (args.Info.Count == 0 || !JavascriptConversion::IsCallable(args[0]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.apply"));
}
Var thisVar = NULL;
Var argArray = NULL;
RecyclableObject* pFunc = VarTo<RecyclableObject>(args[0]);
if (args.Info.Count == 1)
{
thisVar = scriptContext->GetLibrary()->GetUndefined();
}
else if (args.Info.Count == 2)
{
thisVar = args.Values[1];
}
else if (args.Info.Count > 2)
{
thisVar = args.Values[1];
argArray = args.Values[2];
}
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
return CalloutHelper<false>(pFunc, thisVar, /* overridingNewTarget = */nullptr, argArray, scriptContext);
}
END_SAFE_REENTRANT_CALL
}
template <bool isConstruct>
Var JavascriptFunction::CalloutHelper(RecyclableObject* pFunc, Var thisVar, Var overridingNewTarget, Var argArray, ScriptContext* scriptContext)
{
CallFlags callFlag;
if (isConstruct)
{
callFlag = CallFlags_New;
}
else
{
callFlag = CallFlags_Value;
}
Arguments outArgs(CallInfo(callFlag, 0), nullptr);
Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
if (nullptr == argArray)
{
outArgs.Info.Count = 1;
outArgs.Values = &thisVar;
}
else
{
bool isArray = JavascriptArray::IsNonES5Array(argArray);
TypeId typeId = JavascriptOperators::GetTypeId(argArray);
bool isNullOrUndefined = typeId <= TypeIds_UndefinedOrNull;
if (!isNullOrUndefined && !JavascriptOperators::IsObject(argArray)) // ES5: throw if Type(argArray) is not Object
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Function.prototype.apply"));
}
int64 len;
JavascriptArray* arr = NULL;
RecyclableObject* dynamicObject = VarTo<RecyclableObject>(argArray);
if (isNullOrUndefined)
{
len = 0;
}
else if (isArray)
{
#if ENABLE_COPYONACCESS_ARRAY
JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(argArray);
#endif
arr = VarTo<JavascriptArray>(argArray);
len = arr->GetLength();
}
else
{
Var lenProp = JavascriptOperators::OP_GetLength(dynamicObject, scriptContext);
len = JavascriptConversion::ToLength(lenProp, scriptContext);
}
if (len >= CallInfo::kMaxCountArgs)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgListTooLarge);
}
outArgs.Info.Count = (uint)len + 1;
if (len == 0)
{
outArgs.Values = &thisVar;
}
else
{
if (outArgs.Info.Count > STACK_ARGS_ALLOCA_THRESHOLD)
{
PROBE_STACK(scriptContext, outArgs.Info.Count * sizeof(Var)+Js::Constants::MinStackDefault); // args + function call
outArgs.Values = (Var*)_alloca(outArgs.Info.Count * sizeof(Var));
}
else
{
outArgs.Values = stackArgs;
}
outArgs.Values[0] = thisVar;
Var undefined = pFunc->GetLibrary()->GetUndefined();
if (isArray && arr->GetScriptContext() == scriptContext)
{
arr->ForEachItemInRange<false>(0, (uint)len, undefined, scriptContext,
[&outArgs](uint index, Var element)
{
outArgs.Values[index + 1] = element;
});
}
else
{
for (uint i = 0; i < len; i++)
{
Var element = nullptr;
if (!JavascriptOperators::GetItem(dynamicObject, i, &element, scriptContext))
{
element = undefined;
}
outArgs.Values[i + 1] = element;
}
}
}
}
if (isConstruct)
{
return JavascriptFunction::CallAsConstructor(pFunc, overridingNewTarget, outArgs, scriptContext);
}
else
{
// Apply scenarios can have more than Constants::MaxAllowedArgs number of args. Need to use the large argCount logic here.
return JavascriptFunction::CallFunction<true>(pFunc, pFunc->GetEntryPoint(), outArgs, /* useLargeArgCount */true);
}
}
Var JavascriptFunction::ApplyHelper(RecyclableObject* function, Var thisArg, Var argArray, ScriptContext* scriptContext)
{
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
return CalloutHelper<false>(function, thisArg, /* overridingNewTarget = */nullptr, argArray, scriptContext);
}
END_SAFE_REENTRANT_CALL
}
Var JavascriptFunction::ConstructHelper(RecyclableObject* function, Var thisArg, Var overridingNewTarget, Var argArray, ScriptContext* scriptContext)
{
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
return CalloutHelper<true>(function, thisArg, overridingNewTarget, argArray, scriptContext);
}
END_SAFE_REENTRANT_CALL
}
Var JavascriptFunction::EntryBind(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Function_Prototype_bind);
Assert(!(callInfo.Flags & CallFlags_New));
///
/// Check Argument[0] has internal [[Call]] property
/// If not, throw TypeError
///
if (args.Info.Count == 0 || !JavascriptConversion::IsCallable(args[0]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.bind"));
}
BoundFunction* boundFunc = BoundFunction::New(scriptContext, args);
return boundFunc;
}
// ES5 15.3.4.4
// Function.prototype.call (thisArg [ , arg1 [ , arg2, ... ] ] )
// When the call method is called on an object func with argument thisArg and optional arguments arg1, arg2 etc, the following steps are taken:
// 1. If IsCallable(func) is false, then throw a TypeError exception.
// 2. Let argList be an empty List.
// 3. If this method was called with more than one argument then in left to right order starting with arg1 append each argument as the last element of argList
// 4. Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.
// The length property of the call method is 1.
Var JavascriptFunction::EntryCall(RecyclableObject* function, CallInfo callInfo, ...)
{
PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
RUNTIME_ARGUMENTS(args, callInfo);
ScriptContext* scriptContext = function->GetScriptContext();
Assert(!(callInfo.Flags & CallFlags_New));
///
/// Check Argument[0] has internal [[Call]] property
/// If not, throw TypeError
///
uint argCount = args.Info.Count;
if (argCount == 0 || !JavascriptConversion::IsCallable(args[0]))
{
JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.call"));
}
RecyclableObject *pFunc = VarTo<RecyclableObject>(args[0]);
if (argCount == 1)
{
args.Values[0] = scriptContext->GetLibrary()->GetUndefined();
}
else
{
///
/// Remove function object from the arguments and pass the rest
///
for (uint i = 0; i < args.Info.Count - 1; ++i)
{
args.Values[i] = args.Values[i + 1];
}
args.Info.Count = args.Info.Count - 1;
}
///
/// Call the [[Call]] method on the function object
///
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
return JavascriptFunction::CallFunction<true>(pFunc, pFunc->GetEntryPoint(), args, true /*useLargeArgCount*/);
}
END_SAFE_REENTRANT_CALL
}
Var JavascriptFunction::CallRootFunctionInScript(JavascriptFunction* func, Arguments args)
{
ScriptContext* scriptContext = func->GetScriptContext();
if (scriptContext->GetThreadContext()->HasPreviousHostScriptContext())
{
ScriptContext* requestContext = scriptContext->GetThreadContext()->
GetPreviousHostScriptContext()->GetScriptContext();
func = VarTo<JavascriptFunction>(CrossSite::MarshalVar(requestContext,
func, scriptContext));
}
return func->CallRootFunction(args, scriptContext, true);
}
Var JavascriptFunction::CallRootFunction(RecyclableObject* obj, Arguments args, ScriptContext * scriptContext, bool inScript)
{
Var ret = nullptr;
#ifdef FAULT_INJECTION
if (Js::Configuration::Global.flags.FaultInjection >= 0)
{
Js::FaultInjection::pfnHandleAV = JavascriptFunction::CallRootEventFilter;
__try
{
ret = JavascriptFunction::CallRootFunctionInternal(obj, args, scriptContext, inScript);
}
__finally
{
Js::FaultInjection::pfnHandleAV = nullptr;
}
//ret should never be null here
Assert(ret);
return ret;
}
#endif
#ifdef DISABLE_SEH
// xplat: JavascriptArrayBuffer::AllocWrapper is disabled on cross-platform
// (IsValidVirtualBufferLength always returns false).
// SEH and ResumeForOutOfBoundsArrayRefs are not needed.
ret = JavascriptFunction::CallRootFunctionInternal(obj, args, scriptContext, inScript);
#else
if (scriptContext->GetThreadContext()->GetAbnormalExceptionCode() != 0)
{
// ensure that hosts are not doing SEH across Chakra frames, as that can lead to bad state (e.g. destructors not being called)
UnexpectedExceptionHandling_fatal_error();
}
// mark volatile, because otherwise VC will incorrectly optimize away load in the finally block
volatile uint32 exceptionCode = 0;
EXCEPTION_POINTERS exceptionInfo = { 0 };
__try
{
__try
{
ret = JavascriptFunction::CallRootFunctionInternal(obj, args, scriptContext, inScript);
}
__except (
exceptionInfo = *GetExceptionInformation(),
exceptionCode = GetExceptionCode(),
CallRootEventFilter(exceptionCode, GetExceptionInformation()))
{
Assert(UNREACHED);
}
}
__finally
{
// 0xE06D7363 is C++ exception code
if (exceptionCode != 0 && exceptionCode != 0xE06D7363 && AbnormalTermination() && !IsDebuggerPresent())
{
scriptContext->GetThreadContext()->SetAbnormalExceptionCode(exceptionCode);
scriptContext->GetThreadContext()->SetAbnormalExceptionRecord(&exceptionInfo);
}
}
#endif
//ret should never be null here
Assert(ret);
return ret;
}
Var JavascriptFunction::CallRootFunctionInternal(RecyclableObject* obj, Arguments args, ScriptContext * scriptContext, bool inScript)
{
#if DBG
if (IsInAssert != 0)
{
// Just don't execute anything if we are in an assert
Js::Throw::FatalInternalError();
}
#endif
if (inScript)
{
Assert(!(args.Info.Flags & CallFlags_New));
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
return JavascriptFunction::CallFunction<true>(obj, obj->GetEntryPoint(), args);
}
END_SAFE_REENTRANT_CALL
}
#ifdef ENABLE_DEBUG_CONFIG_OPTIONS
Js::Var varThis;
if (PHASE_FORCE1(Js::EvalCompilePhase) && args.Info.Count == 0)
{
varThis = JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), kmodGlobal, scriptContext);
args.Info.Flags = (Js::CallFlags)(args.Info.Flags | CallFlags_Eval);
args.Info.Count = 1;
args.Values = &varThis;
}
#endif
Var varResult = nullptr;
ThreadContext *threadContext;
threadContext = scriptContext->GetThreadContext();
JavascriptExceptionObject* pExceptionObject = NULL;
bool hasCaller = scriptContext->GetHostScriptContext() ? !!scriptContext->GetHostScriptContext()->HasCaller() : false;
Assert(scriptContext == obj->GetScriptContext());
BEGIN_JS_RUNTIME_CALLROOT_EX(scriptContext, hasCaller)
{
scriptContext->VerifyAlive(true);
try
{
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
varResult = args.Info.Flags & CallFlags_New ?
JavascriptFunction::CallAsConstructor(obj, /* overridingNewTarget = */nullptr, args, scriptContext) :
JavascriptFunction::CallFunction<true>(obj, obj->GetEntryPoint(), args);
}
END_SAFE_REENTRANT_CALL
// A recent compiler bug 150148 can incorrectly eliminate catch block, temporary workaround
if (threadContext == NULL)
{
throw JavascriptException(nullptr);
}
}
catch (const JavascriptException& err)
{
pExceptionObject = err.GetAndClear();
}
if (pExceptionObject)
{
JavascriptExceptionOperators::DoThrowCheckClone(pExceptionObject, scriptContext);
}
}
END_JS_RUNTIME_CALL(scriptContext);
Assert(varResult != nullptr);
return varResult;
}
Var JavascriptFunction::CallRootFunction(Arguments args, ScriptContext * scriptContext, bool inScript)
{
return JavascriptFunction::CallRootFunction(this, args, scriptContext, inScript);
}
#if DBG
/*static*/
void JavascriptFunction::CheckValidDebugThunk(ScriptContext* scriptContext, RecyclableObject *function)
{
Assert(scriptContext != nullptr);
Assert(function != nullptr);
if (scriptContext->IsScriptContextInDebugMode()
&& !scriptContext->IsInterpreted() && !CONFIG_FLAG(ForceDiagnosticsMode) // Does not work nicely if we change the default settings.
&& function->GetEntryPoint() != scriptContext->CurrentThunk
&& !CrossSite::IsThunk(function->GetEntryPoint())
&& VarIs<JavascriptFunction>(function))
{
JavascriptFunction *jsFunction = VarTo<JavascriptFunction>(function);
if (!jsFunction->IsBoundFunction()
&& !jsFunction->GetFunctionInfo()->IsDeferred()
&& (jsFunction->GetFunctionInfo()->GetAttributes() & FunctionInfo::DoNotProfile) != FunctionInfo::DoNotProfile
&& jsFunction->GetFunctionInfo() != &JavascriptExternalFunction::EntryInfo::WrappedFunctionThunk)
{
Js::FunctionProxy *proxy = jsFunction->GetFunctionProxy();
if (proxy)
{
AssertMsg(proxy->HasValidEntryPoint(), "Function does not have valid entrypoint");
}
}
}
}
#endif
Var JavascriptFunction::CallAsConstructor(Var v, Var overridingNewTarget, Arguments args, ScriptContext* scriptContext, const Js::AuxArray<uint32> *spreadIndices)
{
Assert(v);
Assert(args.Info.Flags & CallFlags_New);
Assert(scriptContext);
// newCount is ushort.
if (args.Info.Count >= USHORT_MAX)
{
JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgListTooLarge);
}
AnalysisAssert(args.Info.Count < USHORT_MAX);
// Create the empty object if necessary:
// - Built-in constructor functions will return a new object of a specific type, so a new empty object does not need to
// be created
// - If the newTarget is specified and the function is base kind then the this object will be already created. So we can
// just use it instead of creating a new one.
// - For user-defined constructor functions, an empty object is created with the function's prototype
Var resultObject = nullptr;
if (overridingNewTarget != nullptr && args.Info.Count > 0)
{
resultObject = args.Values[0];
}
else
{
BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
{
resultObject = JavascriptOperators::NewScObjectNoCtor(v, scriptContext);
}
END_SAFE_REENTRANT_CALL
}
// JavascriptOperators::NewScObjectNoCtor should have thrown if 'v' is not a constructor
RecyclableObject* functionObj = UnsafeVarTo<RecyclableObject>(v);
const unsigned STACK_ARGS_ALLOCA_THRESHOLD = 8; // Number of stack args we allow before using _alloca
Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
Var* newValues = args.Values;
CallFlags newFlags = args.Info.Flags;
bool thisAlreadySpecified = false;
if (overridingNewTarget != nullptr)
{
ScriptFunction * scriptFunctionObj = JavascriptOperators::TryFromVar<ScriptFunction>(functionObj);
uint newCount = args.Info.Count;
if (scriptFunctionObj && scriptFunctionObj->GetFunctionInfo()->IsClassConstructor())
{
thisAlreadySpecified = true;
args.Values[0] = overridingNewTarget;
}
else
{
newCount++;
newFlags = (CallFlags)(newFlags | CallFlags_NewTarget | CallFlags_ExtraArg);
if (newCount > STACK_ARGS_ALLOCA_THRESHOLD)
{
PROBE_STACK(scriptContext, newCount * sizeof(Var) + Js::Constants::MinStackDefault); // args + function call
newValues = (Var*)_alloca(newCount * sizeof(Var));
}
else
{
newValues = stackArgs;
}
for (unsigned int i = 0; i < args.Info.Count; i++)
{
newValues[i] = args.Values[i];
}
#pragma prefast(suppress:6386, "The index is within the bounds")
newValues[args.Info.Count] = overridingNewTarget;
}
}
// Call the constructor function:
// - If this is not already specified as the overriding new target in Reflect.construct a class case, then
// - Pass in the new empty object as the 'this' parameter. This can be null if an empty object was not created.
if (!thisAlreadySpecified)
{
newValues[0] = resultObject;
}
CallInfo newCallInfo(newFlags, args.Info.Count);
Arguments newArgs(newCallInfo, newValues);
if (VarIs<JavascriptProxy>(v))
{
JavascriptProxy* proxy = VarTo<JavascriptProxy>(v);
return proxy->ConstructorTrap(newArgs, scriptContext, spreadIndices);
}
#if DBG
if (scriptContext->IsScriptContextInDebugMode())
{
CheckValidDebugThunk(scriptContext, functionObj);
}
#endif
Var functionResult;
if (spreadIndices != nullptr)
{
functionResult = CallSpreadFunction(functionObj, newArgs, spreadIndices);
}
else
{
functionResult = CallFunction<true>(functionObj, functionObj->GetEntryPoint(), newArgs, true /*useLargeArgCount*/);
}
return
FinishConstructor(
functionResult,
resultObject,
VarIs<JavascriptFunction>(functionObj) && functionObj->GetScriptContext() == scriptContext ?
VarTo<JavascriptFunction>(functionObj) :
nullptr,
overridingNewTarget != nullptr);
}
Var JavascriptFunction::FinishConstructor(
const Var constructorReturnValue,
Var newObject,
JavascriptFunction *const function,
bool hasOverridingNewTarget)
{
Assert(constructorReturnValue);
// CONSIDER: Using constructorCache->ctorHasNoExplicitReturnValue to speed up this interpreter code path.
if (JavascriptOperators::IsObject(constructorReturnValue))
{
newObject = constructorReturnValue;
}
// #3217: Cases with overriding newTarget are not what constructor cache is intended for;
// Bypass constructor cache to avoid prototype mismatch/confusion.