forked from tmbrbr/project-foxhound
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.cpp
5306 lines (4513 loc) · 159 KB
/
Interpreter.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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Modifications Copyright SAP SE. 2019-2021. All rights reserved.
*/
/*
* JavaScript bytecode interpreter.
*/
#include "vm/Interpreter-inl.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Maybe.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Sprintf.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/WrappingOperations.h"
#include <string.h>
#include "jsapi.h"
#include "jslibmath.h"
#include "jsmath.h"
#include "jsnum.h"
#include "builtin/Array.h"
#include "builtin/Eval.h"
#include "builtin/ModuleObject.h"
#include "builtin/Object.h"
#include "builtin/Promise.h"
#include "gc/GC.h"
#include "jit/AtomicOperations.h"
#include "jit/BaselineJIT.h"
#include "jit/Jit.h"
#include "jit/JitRuntime.h"
#include "js/experimental/JitInfo.h" // JSJitInfo
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
#include "js/friend/WindowProxy.h" // js::IsWindowProxy
#include "js/Printer.h"
#include "util/CheckedArithmetic.h"
#include "util/StringBuffer.h"
#include "vm/AsyncFunction.h"
#include "vm/AsyncIteration.h"
#include "vm/BigIntType.h"
#include "vm/BytecodeUtil.h" // JSDVG_SEARCH_STACK
#include "vm/EqualityOperations.h" // js::StrictlyEqual
#include "vm/GeneratorObject.h"
#include "vm/Iteration.h"
#include "vm/JSAtomUtils.h" // AtomToPrintableString
#include "vm/JSContext.h"
#include "vm/JSFunction.h"
#include "vm/JSObject.h"
#include "vm/JSScript.h"
#include "vm/Opcodes.h"
#include "vm/PIC.h"
#include "vm/PlainObject.h" // js::PlainObject
#include "vm/Scope.h"
#include "vm/Shape.h"
#include "vm/SharedStencil.h" // GCThingIndex
#include "vm/StringType.h"
#include "vm/ThrowMsgKind.h" // ThrowMsgKind
#include "vm/Time.h"
#ifdef ENABLE_RECORD_TUPLE
# include "vm/RecordType.h"
# include "vm/TupleType.h"
#endif
#include "builtin/Boolean-inl.h"
#include "debugger/DebugAPI-inl.h"
#include "vm/ArgumentsObject-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/GeckoProfiler-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/ObjectOperations-inl.h"
#include "vm/PlainObject-inl.h" // js::CopyInitializerObject, js::CreateThis
#include "vm/Probes-inl.h"
#include "vm/Stack-inl.h"
using namespace js;
using mozilla::DebugOnly;
using mozilla::NumberEqualsInt32;
using js::jit::JitScript;
template <bool Eq>
static MOZ_ALWAYS_INLINE bool LooseEqualityOp(JSContext* cx,
InterpreterRegs& regs) {
HandleValue rval = regs.stackHandleAt(-1);
HandleValue lval = regs.stackHandleAt(-2);
bool cond;
if (!LooselyEqual(cx, lval, rval, &cond)) {
return false;
}
cond = (cond == Eq);
regs.sp--;
regs.sp[-1].setBoolean(cond);
return true;
}
JSObject* js::BoxNonStrictThis(JSContext* cx, HandleValue thisv) {
MOZ_ASSERT(!thisv.isMagic());
if (thisv.isNullOrUndefined()) {
return cx->global()->lexicalEnvironment().thisObject();
}
if (thisv.isObject()) {
return &thisv.toObject();
}
return PrimitiveToObject(cx, thisv);
}
bool js::GetFunctionThis(JSContext* cx, AbstractFramePtr frame,
MutableHandleValue res) {
MOZ_ASSERT(frame.isFunctionFrame());
MOZ_ASSERT(!frame.callee()->isArrow());
if (frame.thisArgument().isObject() || frame.callee()->strict()) {
res.set(frame.thisArgument());
return true;
}
MOZ_ASSERT(!frame.callee()->isSelfHostedBuiltin(),
"Self-hosted builtins must be strict");
RootedValue thisv(cx, frame.thisArgument());
// If there is a NSVO on environment chain, use it as basis for fallback
// global |this|. This gives a consistent definition of global lexical
// |this| between function and global contexts.
//
// NOTE: If only non-syntactic WithEnvironments are on the chain, we use the
// global lexical |this| value. This is for compatibility with the Subscript
// Loader.
if (frame.script()->hasNonSyntacticScope() && thisv.isNullOrUndefined()) {
RootedObject env(cx, frame.environmentChain());
while (true) {
if (IsNSVOLexicalEnvironment(env) || IsGlobalLexicalEnvironment(env)) {
res.setObject(*GetThisObjectOfLexical(env));
return true;
}
if (!env->enclosingEnvironment()) {
// This can only happen in Debugger eval frames: in that case we
// don't always have a global lexical env, see EvaluateInEnv.
MOZ_ASSERT(env->is<GlobalObject>());
res.setObject(*GetThisObject(env));
return true;
}
env = env->enclosingEnvironment();
}
}
JSObject* obj = BoxNonStrictThis(cx, thisv);
if (!obj) {
return false;
}
res.setObject(*obj);
return true;
}
void js::GetNonSyntacticGlobalThis(JSContext* cx, HandleObject envChain,
MutableHandleValue res) {
RootedObject env(cx, envChain);
while (true) {
if (IsExtensibleLexicalEnvironment(env)) {
res.setObject(*GetThisObjectOfLexical(env));
return;
}
if (!env->enclosingEnvironment()) {
// This can only happen in Debugger eval frames: in that case we
// don't always have a global lexical env, see EvaluateInEnv.
MOZ_ASSERT(env->is<GlobalObject>());
res.setObject(*GetThisObject(env));
return;
}
env = env->enclosingEnvironment();
}
}
#ifdef DEBUG
static bool IsSelfHostedOrKnownBuiltinCtor(JSFunction* fun, JSContext* cx) {
if (fun->isSelfHostedOrIntrinsic()) {
return true;
}
// GetBuiltinConstructor in MapGroupBy
if (fun == cx->global()->maybeGetConstructor(JSProto_Map)) {
return true;
}
// GetBuiltinConstructor in intlFallbackSymbol
if (fun == cx->global()->maybeGetConstructor(JSProto_Symbol)) {
return true;
}
// ConstructorForTypedArray in MergeSortTypedArray
if (fun == cx->global()->maybeGetConstructor(JSProto_Int8Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Uint8Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Int16Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Uint16Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Int32Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Uint32Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Float32Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Float64Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_Uint8ClampedArray) ||
fun == cx->global()->maybeGetConstructor(JSProto_BigInt64Array) ||
fun == cx->global()->maybeGetConstructor(JSProto_BigUint64Array)) {
return true;
}
return false;
}
#endif // DEBUG
bool js::Debug_CheckSelfHosted(JSContext* cx, HandleValue funVal) {
#ifdef DEBUG
JSFunction* fun = &UncheckedUnwrap(&funVal.toObject())->as<JSFunction>();
MOZ_ASSERT(IsSelfHostedOrKnownBuiltinCtor(fun, cx),
"functions directly called inside self-hosted JS must be one of "
"selfhosted function, self-hosted intrinsic, or known built-in "
"constructor");
#else
MOZ_CRASH("self-hosted checks should only be done in Debug builds");
#endif
// This is purely to police self-hosted code. There is no actual operation.
return true;
}
static inline bool GetPropertyOperation(JSContext* cx,
Handle<PropertyName*> name,
HandleValue lval,
MutableHandleValue vp) {
if (name == cx->names().length && GetLengthProperty(lval, vp)) {
return true;
}
return GetProperty(cx, lval, name, vp);
}
static inline bool GetNameOperation(JSContext* cx, HandleObject envChain,
Handle<PropertyName*> name, JSOp nextOp,
MutableHandleValue vp) {
/* Kludge to allow (typeof foo == "undefined") tests. */
if (nextOp == JSOp::Typeof) {
return GetEnvironmentName<GetNameMode::TypeOf>(cx, envChain, name, vp);
}
return GetEnvironmentName<GetNameMode::Normal>(cx, envChain, name, vp);
}
bool js::GetImportOperation(JSContext* cx, HandleObject envChain,
HandleScript script, jsbytecode* pc,
MutableHandleValue vp) {
RootedObject env(cx), pobj(cx);
Rooted<PropertyName*> name(cx, script->getName(pc));
PropertyResult prop;
MOZ_ALWAYS_TRUE(LookupName(cx, name, envChain, &env, &pobj, &prop));
MOZ_ASSERT(env && env->is<ModuleEnvironmentObject>());
MOZ_ASSERT(env->as<ModuleEnvironmentObject>().hasImportBinding(name));
return FetchName<GetNameMode::Normal>(cx, env, pobj, name, prop, vp);
}
bool js::ReportIsNotFunction(JSContext* cx, HandleValue v, int numToSkip,
MaybeConstruct construct) {
unsigned error = construct ? JSMSG_NOT_CONSTRUCTOR : JSMSG_NOT_FUNCTION;
int spIndex = numToSkip >= 0 ? -(numToSkip + 1) : JSDVG_SEARCH_STACK;
ReportValueError(cx, error, spIndex, v, nullptr);
return false;
}
JSObject* js::ValueToCallable(JSContext* cx, HandleValue v, int numToSkip,
MaybeConstruct construct) {
if (v.isObject() && v.toObject().isCallable()) {
return &v.toObject();
}
ReportIsNotFunction(cx, v, numToSkip, construct);
return nullptr;
}
static bool MaybeCreateThisForConstructor(JSContext* cx, const CallArgs& args) {
if (args.thisv().isObject()) {
return true;
}
RootedFunction callee(cx, &args.callee().as<JSFunction>());
RootedObject newTarget(cx, &args.newTarget().toObject());
MOZ_ASSERT(callee->hasBytecode());
if (!CreateThis(cx, callee, newTarget, GenericObject, args.mutableThisv())) {
return false;
}
// Ensure the callee still has a non-lazy script. We normally don't relazify
// in active compartments, but the .prototype lookup might have called the
// relazifyFunctions testing function that doesn't have this restriction.
return JSFunction::getOrCreateScript(cx, callee);
}
#ifdef ENABLE_RECORD_TUPLE
static bool AddRecordSpreadOperation(JSContext* cx, HandleValue recHandle,
HandleValue spreadeeHandle) {
MOZ_ASSERT(recHandle.toExtendedPrimitive().is<RecordType>());
RecordType* rec = &recHandle.toExtendedPrimitive().as<RecordType>();
RootedObject obj(cx, ToObjectOrGetObjectPayload(cx, spreadeeHandle));
RootedIdVector keys(cx);
if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_SYMBOLS, &keys)) {
return false;
}
size_t len = keys.length();
RootedId propKey(cx);
RootedValue propValue(cx);
for (size_t i = 0; i < len; i++) {
propKey.set(keys[i]);
// Step 4.c.ii.1.
if (MOZ_UNLIKELY(!GetProperty(cx, obj, obj, propKey, &propValue))) {
return false;
}
if (MOZ_UNLIKELY(!rec->initializeNextProperty(cx, propKey, propValue))) {
return false;
}
}
return true;
}
#endif
InterpreterFrame* InvokeState::pushInterpreterFrame(JSContext* cx) {
return cx->interpreterStack().pushInvokeFrame(cx, args_, construct_);
}
InterpreterFrame* ExecuteState::pushInterpreterFrame(JSContext* cx) {
return cx->interpreterStack().pushExecuteFrame(cx, script_, envChain_,
evalInFrame_);
}
InterpreterFrame* RunState::pushInterpreterFrame(JSContext* cx) {
if (isInvoke()) {
return asInvoke()->pushInterpreterFrame(cx);
}
return asExecute()->pushInterpreterFrame(cx);
}
static MOZ_ALWAYS_INLINE bool MaybeEnterInterpreterTrampoline(JSContext* cx,
RunState& state) {
#ifdef NIGHTLY_BUILD
if (jit::JitOptions.emitInterpreterEntryTrampoline &&
cx->runtime()->hasJitRuntime()) {
js::jit::JitRuntime* jitRuntime = cx->runtime()->jitRuntime();
JSScript* script = state.script();
uint8_t* codeRaw = nullptr;
auto p = jitRuntime->getInterpreterEntryMap()->lookup(script);
if (p) {
codeRaw = p->value().raw();
} else if (js::jit::JitCode* code =
jitRuntime->generateEntryTrampolineForScript(cx, script)) {
js::jit::EntryTrampoline entry(cx, code);
if (!jitRuntime->getInterpreterEntryMap()->put(script, entry)) {
return false;
}
codeRaw = code->raw();
}
MOZ_ASSERT(codeRaw, "Should have a valid trampoline here.");
// The C++ entry thunk is located at the vmInterpreterEntryOffset offset.
codeRaw += jitRuntime->vmInterpreterEntryOffset();
return js::jit::EnterInterpreterEntryTrampoline(codeRaw, cx, &state);
}
#endif
return Interpret(cx, state);
}
// MSVC with PGO inlines a lot of functions in RunScript, resulting in large
// stack frames and stack overflow issues, see bug 1167883. Turn off PGO to
// avoid this.
#ifdef _MSC_VER
# pragma optimize("g", off)
#endif
bool js::RunScript(JSContext* cx, RunState& state) {
AutoCheckRecursionLimit recursion(cx);
if (!recursion.check(cx)) {
return false;
}
MOZ_ASSERT_IF(cx->runtime()->hasJitRuntime(),
!cx->runtime()->jitRuntime()->disallowArbitraryCode());
// Since any script can conceivably GC, make sure it's safe to do so.
cx->verifyIsSafeToGC();
MOZ_ASSERT(cx->realm() == state.script()->realm());
MOZ_DIAGNOSTIC_ASSERT(cx->realm()->isSystem() ||
cx->runtime()->allowContentJS());
if (!DebugAPI::checkNoExecute(cx, state.script())) {
return false;
}
GeckoProfilerEntryMarker marker(cx, state.script());
bool measuringTime = !cx->isMeasuringExecutionTime();
mozilla::TimeStamp startTime;
if (measuringTime) {
cx->setIsMeasuringExecutionTime(true);
cx->setIsExecuting(true);
startTime = mozilla::TimeStamp::Now();
}
auto timerEnd = mozilla::MakeScopeExit([&]() {
if (measuringTime) {
mozilla::TimeDuration delta = mozilla::TimeStamp::Now() - startTime;
cx->realm()->timers.executionTime += delta;
cx->setIsMeasuringExecutionTime(false);
cx->setIsExecuting(false);
}
});
jit::EnterJitStatus status = jit::MaybeEnterJit(cx, state);
switch (status) {
case jit::EnterJitStatus::Error:
return false;
case jit::EnterJitStatus::Ok:
return true;
case jit::EnterJitStatus::NotEntered:
break;
}
bool ok = MaybeEnterInterpreterTrampoline(cx, state);
return ok;
}
#ifdef _MSC_VER
# pragma optimize("", on)
#endif
STATIC_PRECONDITION_ASSUME(ubound(args.argv_) >= argc)
MOZ_ALWAYS_INLINE bool CallJSNative(JSContext* cx, Native native,
CallReason reason, const CallArgs& args) {
AutoCheckRecursionLimit recursion(cx);
if (!recursion.check(cx)) {
return false;
}
NativeResumeMode resumeMode = DebugAPI::onNativeCall(cx, args, reason);
if (resumeMode != NativeResumeMode::Continue) {
return resumeMode == NativeResumeMode::Override;
}
#ifdef DEBUG
bool alreadyThrowing = cx->isExceptionPending();
#endif
cx->check(args);
MOZ_ASSERT(!args.callee().is<ProxyObject>());
AutoRealm ar(cx, &args.callee());
bool ok = native(cx, args.length(), args.base());
if (ok) {
cx->check(args.rval());
MOZ_ASSERT_IF(!alreadyThrowing, !cx->isExceptionPending());
}
return ok;
}
STATIC_PRECONDITION(ubound(args.argv_) >= argc)
MOZ_ALWAYS_INLINE bool CallJSNativeConstructor(JSContext* cx, Native native,
const CallArgs& args) {
#ifdef DEBUG
RootedObject callee(cx, &args.callee());
#endif
MOZ_ASSERT(args.thisv().isMagic());
if (!CallJSNative(cx, native, CallReason::Call, args)) {
return false;
}
/*
* Native constructors must return non-primitive values on success.
* Although it is legal, if a constructor returns the callee, there is a
* 99.9999% chance it is a bug. If any valid code actually wants the
* constructor to return the callee, the assertion can be removed or
* (another) conjunct can be added to the antecedent.
*
* Exceptions:
* - (new Object(Object)) returns the callee.
* - The bound function construct hook can return an arbitrary object,
* including the callee.
*
* Also allow if this may be due to a debugger hook since fuzzing may let this
* happen.
*/
MOZ_ASSERT(args.rval().isObject());
MOZ_ASSERT_IF(!JS_IsNativeFunction(callee, obj_construct) &&
!callee->is<BoundFunctionObject>() &&
!cx->insideDebuggerEvaluationWithOnNativeCallHook,
args.rval() != ObjectValue(*callee));
return true;
}
/*
* Find a function reference and its 'this' value implicit first parameter
* under argc arguments on cx's stack, and call the function. Push missing
* required arguments, allocate declared local variables, and pop everything
* when done. Then push the return value.
*
* Note: This function DOES NOT call GetThisValue to munge |args.thisv()| if
* necessary. The caller (usually the interpreter) must have performed
* this step already!
*/
bool js::InternalCallOrConstruct(JSContext* cx, const CallArgs& args,
MaybeConstruct construct,
CallReason reason /* = CallReason::Call */) {
MOZ_ASSERT(args.length() <= ARGS_LENGTH_MAX);
unsigned skipForCallee = args.length() + 1 + (construct == CONSTRUCT);
if (args.calleev().isPrimitive()) {
return ReportIsNotFunction(cx, args.calleev(), skipForCallee, construct);
}
/* Invoke non-functions. */
if (MOZ_UNLIKELY(!args.callee().is<JSFunction>())) {
MOZ_ASSERT_IF(construct, !args.callee().isConstructor());
if (!args.callee().isCallable()) {
return ReportIsNotFunction(cx, args.calleev(), skipForCallee, construct);
}
if (args.callee().is<ProxyObject>()) {
RootedObject proxy(cx, &args.callee());
return Proxy::call(cx, proxy, args);
}
JSNative call = args.callee().callHook();
MOZ_ASSERT(call, "isCallable without a callHook?");
return CallJSNative(cx, call, reason, args);
}
/* Invoke native functions. */
RootedFunction fun(cx, &args.callee().as<JSFunction>());
// TaintFox: mark tainted function call arguments for tracing purposes.
if (!fun->isSelfHostedOrIntrinsic() && fun->isInterpreted())
MarkTaintedFunctionArguments(cx, fun, args);
if (fun->isNativeFun()) {
MOZ_ASSERT_IF(construct, !fun->isConstructor());
JSNative native = fun->native();
if (!construct && args.ignoresReturnValue() && fun->hasJitInfo()) {
const JSJitInfo* jitInfo = fun->jitInfo();
if (jitInfo->type() == JSJitInfo::IgnoresReturnValueNative) {
native = jitInfo->ignoresReturnValueMethod;
}
}
return CallJSNative(cx, native, reason, args);
}
// Self-hosted builtins are considered native by the onNativeCall hook.
if (fun->isSelfHostedBuiltin()) {
NativeResumeMode resumeMode = DebugAPI::onNativeCall(cx, args, reason);
if (resumeMode != NativeResumeMode::Continue) {
return resumeMode == NativeResumeMode::Override;
}
}
if (!JSFunction::getOrCreateScript(cx, fun)) {
return false;
}
/* Run function until JSOp::RetRval, JSOp::Return or error. */
InvokeState state(cx, args, construct);
// Create |this| if we're constructing. Switch to the callee's realm to
// ensure this object has the correct realm.
AutoRealm ar(cx, state.script());
if (construct && !MaybeCreateThisForConstructor(cx, args)) {
return false;
}
// Calling class constructors throws an error from the callee's realm.
if (construct != CONSTRUCT && fun->isClassConstructor()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_CANT_CALL_CLASS_CONSTRUCTOR);
return false;
}
bool ok = RunScript(cx, state);
MOZ_ASSERT_IF(ok && construct, args.rval().isObject());
return ok;
}
// Returns true if the callee needs an outerized |this| object. Outerization
// means passing the WindowProxy instead of the Window (a GlobalObject) because
// we must never expose the Window to script. This returns false only for DOM
// getters or setters.
static bool CalleeNeedsOuterizedThisObject(const Value& callee) {
if (!callee.isObject() || !callee.toObject().is<JSFunction>()) {
return true;
}
JSFunction& fun = callee.toObject().as<JSFunction>();
if (!fun.isNativeFun() || !fun.hasJitInfo()) {
return true;
}
return fun.jitInfo()->needsOuterizedThisObject();
}
static bool InternalCall(JSContext* cx, const AnyInvokeArgs& args,
CallReason reason) {
MOZ_ASSERT(args.array() + args.length() == args.end(),
"must pass calling arguments to a calling attempt");
#ifdef DEBUG
// The caller is responsible for calling GetThisObject if needed.
if (args.thisv().isObject()) {
JSObject* thisObj = &args.thisv().toObject();
MOZ_ASSERT_IF(CalleeNeedsOuterizedThisObject(args.calleev()),
GetThisObject(thisObj) == thisObj);
}
#endif
return InternalCallOrConstruct(cx, args, NO_CONSTRUCT, reason);
}
bool js::CallFromStack(JSContext* cx, const CallArgs& args,
CallReason reason /* = CallReason::Call */) {
return InternalCall(cx, static_cast<const AnyInvokeArgs&>(args), reason);
}
// ES7 rev 0c1bd3004329336774cbc90de727cd0cf5f11e93
// 7.3.12 Call.
bool js::Call(JSContext* cx, HandleValue fval, HandleValue thisv,
const AnyInvokeArgs& args, MutableHandleValue rval,
CallReason reason) {
// Explicitly qualify these methods to bypass AnyInvokeArgs's deliberate
// shadowing.
args.CallArgs::setCallee(fval);
args.CallArgs::setThis(thisv);
if (thisv.isObject()) {
// If |this| is a global object, it might be a Window and in that case we
// usually have to pass the WindowProxy instead.
JSObject* thisObj = &thisv.toObject();
if (thisObj->is<GlobalObject>()) {
if (CalleeNeedsOuterizedThisObject(fval)) {
args.mutableThisv().setObject(*GetThisObject(thisObj));
}
} else {
// Fast path: we don't have to do anything if the object isn't a global.
MOZ_ASSERT(GetThisObject(thisObj) == thisObj);
}
}
if (!InternalCall(cx, args, reason)) {
return false;
}
rval.set(args.rval());
return true;
}
static bool InternalConstruct(JSContext* cx, const AnyConstructArgs& args,
CallReason reason = CallReason::Call) {
MOZ_ASSERT(args.array() + args.length() + 1 == args.end(),
"must pass constructing arguments to a construction attempt");
MOZ_ASSERT(!FunctionClass.getConstruct());
MOZ_ASSERT(!ExtendedFunctionClass.getConstruct());
// Callers are responsible for enforcing these preconditions.
MOZ_ASSERT(IsConstructor(args.calleev()),
"trying to construct a value that isn't a constructor");
MOZ_ASSERT(IsConstructor(args.CallArgs::newTarget()),
"provided new.target value must be a constructor");
MOZ_ASSERT(args.thisv().isMagic(JS_IS_CONSTRUCTING) ||
args.thisv().isObject());
JSObject& callee = args.callee();
if (callee.is<JSFunction>()) {
RootedFunction fun(cx, &callee.as<JSFunction>());
if (fun->isNativeFun()) {
return CallJSNativeConstructor(cx, fun->native(), args);
}
if (!InternalCallOrConstruct(cx, args, CONSTRUCT, reason)) {
return false;
}
MOZ_ASSERT(args.CallArgs::rval().isObject());
return true;
}
if (callee.is<ProxyObject>()) {
RootedObject proxy(cx, &callee);
return Proxy::construct(cx, proxy, args);
}
JSNative construct = callee.constructHook();
MOZ_ASSERT(construct != nullptr, "IsConstructor without a construct hook?");
return CallJSNativeConstructor(cx, construct, args);
}
// Check that |callee|, the callee in a |new| expression, is a constructor.
static bool StackCheckIsConstructorCalleeNewTarget(JSContext* cx,
HandleValue callee,
HandleValue newTarget) {
// Calls from the stack could have any old non-constructor callee.
if (!IsConstructor(callee)) {
ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_SEARCH_STACK, callee,
nullptr);
return false;
}
// The new.target has already been vetted by previous calls, or is the callee.
// We can just assert that it's a constructor.
MOZ_ASSERT(IsConstructor(newTarget));
return true;
}
bool js::ConstructFromStack(JSContext* cx, const CallArgs& args,
CallReason reason /* CallReason::Call */) {
if (!StackCheckIsConstructorCalleeNewTarget(cx, args.calleev(),
args.newTarget())) {
return false;
}
return InternalConstruct(cx, static_cast<const AnyConstructArgs&>(args),
reason);
}
bool js::Construct(JSContext* cx, HandleValue fval,
const AnyConstructArgs& args, HandleValue newTarget,
MutableHandleObject objp) {
MOZ_ASSERT(args.thisv().isMagic(JS_IS_CONSTRUCTING));
// Explicitly qualify to bypass AnyConstructArgs's deliberate shadowing.
args.CallArgs::setCallee(fval);
args.CallArgs::newTarget().set(newTarget);
if (!InternalConstruct(cx, args)) {
return false;
}
MOZ_ASSERT(args.CallArgs::rval().isObject());
objp.set(&args.CallArgs::rval().toObject());
return true;
}
bool js::InternalConstructWithProvidedThis(JSContext* cx, HandleValue fval,
HandleValue thisv,
const AnyConstructArgs& args,
HandleValue newTarget,
MutableHandleValue rval) {
args.CallArgs::setCallee(fval);
MOZ_ASSERT(thisv.isObject());
args.CallArgs::setThis(thisv);
args.CallArgs::newTarget().set(newTarget);
if (!InternalConstruct(cx, args)) {
return false;
}
rval.set(args.CallArgs::rval());
return true;
}
bool js::CallGetter(JSContext* cx, HandleValue thisv, HandleValue getter,
MutableHandleValue rval) {
FixedInvokeArgs<0> args(cx);
return Call(cx, getter, thisv, args, rval, CallReason::Getter);
}
bool js::CallSetter(JSContext* cx, HandleValue thisv, HandleValue setter,
HandleValue v) {
FixedInvokeArgs<1> args(cx);
args[0].set(v);
RootedValue ignored(cx);
return Call(cx, setter, thisv, args, &ignored, CallReason::Setter);
}
bool js::ExecuteKernel(JSContext* cx, HandleScript script,
HandleObject envChainArg, AbstractFramePtr evalInFrame,
MutableHandleValue result) {
MOZ_ASSERT_IF(script->isGlobalCode(),
IsGlobalLexicalEnvironment(envChainArg) ||
!IsSyntacticEnvironment(envChainArg));
#ifdef DEBUG
RootedObject terminatingEnv(cx, envChainArg);
while (IsSyntacticEnvironment(terminatingEnv)) {
terminatingEnv = terminatingEnv->enclosingEnvironment();
}
MOZ_ASSERT(terminatingEnv->is<GlobalObject>() ||
script->hasNonSyntacticScope());
#endif
if (script->treatAsRunOnce()) {
if (script->hasRunOnce()) {
JS_ReportErrorASCII(cx,
"Trying to execute a run-once script multiple times");
return false;
}
script->setHasRunOnce();
}
if (script->isEmpty()) {
result.setUndefined();
return true;
}
probes::StartExecution(script);
ExecuteState state(cx, script, envChainArg, evalInFrame, result);
bool ok = RunScript(cx, state);
probes::StopExecution(script);
return ok;
}
bool js::Execute(JSContext* cx, HandleScript script, HandleObject envChain,
MutableHandleValue rval) {
/* The env chain is something we control, so we know it can't
have any outer objects on it. */
MOZ_ASSERT(!IsWindowProxy(envChain));
if (script->isModule()) {
MOZ_RELEASE_ASSERT(
envChain == script->module()->environment(),
"Module scripts can only be executed in the module's environment");
} else {
MOZ_RELEASE_ASSERT(
IsGlobalLexicalEnvironment(envChain) || script->hasNonSyntacticScope(),
"Only global scripts with non-syntactic envs can be executed with "
"interesting envchains");
}
/* Ensure the env chain is all same-compartment and terminates in a global. */
#ifdef DEBUG
JSObject* s = envChain;
do {
cx->check(s);
MOZ_ASSERT_IF(!s->enclosingEnvironment(), s->is<GlobalObject>());
} while ((s = s->enclosingEnvironment()));
#endif
return ExecuteKernel(cx, script, envChain, NullFramePtr() /* evalInFrame */,
rval);
}
/*
* ES6 (4-25-16) 12.10.4 InstanceofOperator
*/
bool js::InstanceofOperator(JSContext* cx, HandleObject obj, HandleValue v,
bool* bp) {
/* Step 1. is handled by caller. */
/* Step 2. */
RootedValue hasInstance(cx);
RootedId id(cx, PropertyKey::Symbol(cx->wellKnownSymbols().hasInstance));
if (!GetProperty(cx, obj, obj, id, &hasInstance)) {
return false;
}
if (!hasInstance.isNullOrUndefined()) {
if (!IsCallable(hasInstance)) {
return ReportIsNotFunction(cx, hasInstance);
}
/* Step 3. */
RootedValue rval(cx);
if (!Call(cx, hasInstance, obj, v, &rval)) {
return false;
}
*bp = ToBoolean(rval);
return true;
}
/* Step 4. */
if (!obj->isCallable()) {
RootedValue val(cx, ObjectValue(*obj));
return ReportIsNotFunction(cx, val);
}
/* Step 5. */
return OrdinaryHasInstance(cx, obj, v, bp);
}
JSType js::TypeOfObject(JSObject* obj) {
#ifdef ENABLE_RECORD_TUPLE
MOZ_ASSERT(!js::IsExtendedPrimitive(*obj));
#endif
AutoUnsafeCallWithABI unsafe;
if (EmulatesUndefined(obj)) {
return JSTYPE_UNDEFINED;
}
if (obj->isCallable()) {
return JSTYPE_FUNCTION;
}
return JSTYPE_OBJECT;
}
#ifdef ENABLE_RECORD_TUPLE
JSType TypeOfExtendedPrimitive(JSObject* obj) {
MOZ_ASSERT(js::IsExtendedPrimitive(*obj));
if (obj->is<RecordType>()) {
return JSTYPE_RECORD;
}
if (obj->is<TupleType>()) {
return JSTYPE_TUPLE;
}
MOZ_CRASH("Unknown ExtendedPrimitive");
}
#endif
JSType js::TypeOfValue(const Value& v) {
switch (v.type()) {
case ValueType::Double:
case ValueType::Int32:
return JSTYPE_NUMBER;
case ValueType::String:
return JSTYPE_STRING;
case ValueType::Null:
return JSTYPE_OBJECT;
case ValueType::Undefined:
return JSTYPE_UNDEFINED;
case ValueType::Object:
return TypeOfObject(&v.toObject());
#ifdef ENABLE_RECORD_TUPLE
case ValueType::ExtendedPrimitive:
return TypeOfExtendedPrimitive(&v.toExtendedPrimitive());
#endif
case ValueType::Boolean:
return JSTYPE_BOOLEAN;
case ValueType::BigInt:
return JSTYPE_BIGINT;
case ValueType::Symbol:
return JSTYPE_SYMBOL;
case ValueType::Magic:
case ValueType::PrivateGCThing:
break;
}
ReportBadValueTypeAndCrash(v);
}
bool js::CheckClassHeritageOperation(JSContext* cx, HandleValue heritage) {
if (IsConstructor(heritage)) {
return true;
}
if (heritage.isNull()) {
return true;
}
if (heritage.isObject()) {
ReportIsNotFunction(cx, heritage, 0, CONSTRUCT);
return false;
}
ReportValueError(cx, JSMSG_BAD_HERITAGE, -1, heritage, nullptr,
"not an object or null");
return false;
}
PlainObject* js::ObjectWithProtoOperation(JSContext* cx, HandleValue val) {
if (!val.isObjectOrNull()) {
ReportValueError(cx, JSMSG_NOT_OBJORNULL, -1, val, nullptr);
return nullptr;
}
RootedObject proto(cx, val.toObjectOrNull());
return NewPlainObjectWithProto(cx, proto);
}