Debian Codegraph @

js/src/vm/JSContext.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /* JS execution context. */
8
9 #ifndef vm_JSContext_h
10 #define vm_JSContext_h
11
12 #include "mozilla/BaseProfilerUtils.h" // BaseProfilerThreadId
13 #include "mozilla/Maybe.h"
14 #include "mozilla/MemoryReporting.h"
15
16 #include "jstypes.h" // JS_PUBLIC_API
17
18 #include "builtin/AtomicsObject.h"
19 #include "ds/TraceableFifo.h"
20 #include "frontend/NameCollections.h"
21 #include "gc/GCEnum.h"
22 #include "gc/Memory.h"
23 #include "irregexp/RegExpTypes.h"
24 #include "js/ContextOptions.h" // JS::ContextOptions
25 #include "js/Exception.h"
26 #include "js/GCVector.h"
27 #include "js/Interrupt.h"
28 #include "js/Promise.h"
29 #include "js/Result.h"
30 #include "js/Stack.h" // JS::NativeStackBase, JS::NativeStackLimit
31 #include "js/Utility.h"
32 #include "js/Vector.h"
33 #include "threading/ProtectedData.h"
34 #include "util/StructuredSpewer.h"
35 #include "vm/Activation.h" // js::Activation
36 #include "vm/MallocProvider.h"
37 #include "vm/Runtime.h"
38 #include "wasm/WasmContext.h"
39
40 struct JS_PUBLIC_API JSContext;
41
42 struct DtoaState;
43
44 namespace js {
45
46 class AutoAllocInAtomsZone;
47 class AutoMaybeLeaveAtomsZone;
48 class AutoRealm;
49 struct PortableBaselineStack;
50
51 #ifdef MOZ_EXECUTION_TRACING
52 class ExecutionTracer;
53 #endif
54
55 namespace jit {
56 class ICScript;
57 class JitActivation;
58 class JitContext;
59 class DebugModeOSRVolatileJitFrameIter;
60 } // namespace jit
61
62 /* Detects cycles when traversing an object graph. */
63 class MOZ_RAII AutoCycleDetector {
64 public:
65 using Vector = GCVector<JSObject*, 8>;
66
67 AutoCycleDetector(JSContext* cx, HandleObject objArg)
68 : cx(cx), obj(cx, objArg), cyclic(true) {}
69
70 ~AutoCycleDetector();
71
72 bool init();
73
74 bool foundCycle() { return cyclic; }
75
76 private:
77 JSContext* cx;
78 RootedObject obj;
79 bool cyclic;
80 };
81
82 struct AutoResolving;
83
84 class InternalJobQueue : public JS::JobQueue {
85 public:
86 explicit InternalJobQueue(JSContext* cx)
87 : queue(cx, SystemAllocPolicy()), draining_(false), interrupted_(false) {}
88 ~InternalJobQueue() = default;
89
90 // JS::JobQueue methods.
91 bool getHostDefinedData(JSContext* cx,
92 JS::MutableHandle<JSObject*> data) const override;
93
94 bool enqueuePromiseJob(JSContext* cx, JS::HandleObject promise,
95 JS::HandleObject job, JS::HandleObject allocationSite,
96 JS::HandleObject hostDefinedData) override;
97 void runJobs(JSContext* cx) override;
98 bool empty() const override;
99 bool isDrainingStopped() const override { return interrupted_; }
100
101 // If we are currently in a call to runJobs(), make that call stop processing
102 // jobs once the current one finishes, and return. If we are not currently in
103 // a call to runJobs, make all future calls return immediately.
104 void interrupt() { interrupted_ = true; }
105
106 void uninterrupt() { interrupted_ = false; }
107
108 // Return the front element of the queue, or nullptr if the queue is empty.
109 // This is only used by shell testing functions.
110 JSObject* maybeFront() const;
111
112 #ifdef DEBUG
113 JSObject* copyJobs(JSContext* cx);
114 #endif
115
116 private:
117 using Queue = js::TraceableFifo<JSObject*, 0, SystemAllocPolicy>;
118
119 JS::PersistentRooted<Queue> queue;
120
121 // True if we are in the midst of draining jobs from this queue. We use this
122 // to avoid re-entry (nested calls simply return immediately).
123 bool draining_;
124
125 // True if we've been asked to interrupt draining jobs. Set by interrupt().
126 bool interrupted_;
127
128 class SavedQueue;
129 js::UniquePtr<JobQueue::SavedJobQueue> saveJobQueue(JSContext*) override;
130 };
131
132 class AutoLockScriptData;
133
134 /* Thread Local Storage slot for storing the context for a thread. */
135 extern MOZ_THREAD_LOCAL(JSContext*) TlsContext;
136
137 #ifdef DEBUG
138 JSContext* MaybeGetJSContext();
139 #endif
140
141 enum class InterruptReason : uint32_t {
142 MinorGC = 1 << 0,
143 MajorGC = 1 << 1,
144 AttachOffThreadCompilations = 1 << 2,
145 CallbackUrgent = 1 << 3,
146 CallbackCanWait = 1 << 4,
147 };
148
149 enum class ShouldCaptureStack { Maybe, Always };
150
151 } /* namespace js */
152
153 /*
154 * A JSContext encapsulates the thread local state used when using the JS
155 * runtime.
156 */
157 struct JS_PUBLIC_API JSContext : public JS::RootingContext,
158 public js::MallocProvider<JSContext> {
159 JSContext(JSRuntime* runtime, const JS::ContextOptions& options);
160 ~JSContext();
161
162 bool init();
163
164 static JSContext* from(JS::RootingContext* rcx) {
165 return static_cast<JSContext*>(rcx);
166 }
167
168 private:
169 js::UnprotectedData<JSRuntime*> runtime_;
170 #ifdef DEBUG
171 js::WriteOnceData<bool> initialized_;
172 #endif
173
174 js::ContextData<JS::ContextOptions> options_;
175
176 // Are we currently timing execution? This flag ensures that we do not
177 // double-count execution time in reentrant situations.
178 js::ContextData<bool> measuringExecutionTime_;
179
180 // This variable is used by the HelperThread scheduling to update the priority
181 // of task based on whether JavaScript is being executed on the main thread.
182 mozilla::Atomic<bool, mozilla::ReleaseAcquire> isExecuting_;
183
184 public:
185 // This is used by helper threads to change the runtime their context is
186 // currently operating on.
187 void setRuntime(JSRuntime* rt);
188
189 bool isMeasuringExecutionTime() const { return measuringExecutionTime_; }
190 void setIsMeasuringExecutionTime(bool value) {
191 measuringExecutionTime_ = value;
192 }
193
194 // While JSContexts are meant to be used on a single thread, this reference is
195 // meant to be shared to helper thread tasks. This is used by helper threads
196 // to change the priority of tasks based on whether JavaScript is executed on
197 // the main thread.
198 const mozilla::Atomic<bool, mozilla::ReleaseAcquire>& isExecutingRef() const {
199 return isExecuting_;
200 }
201 void setIsExecuting(bool value) { isExecuting_ = value; }
202
203 #ifdef DEBUG
204 bool isInitialized() const { return initialized_; }
205 #endif
206
207 template <typename T>
208 bool isInsideCurrentZone(T thing) const {
209 return thing->zoneFromAnyThread() == zone_;
210 }
211
212 template <typename T>
213 inline bool isInsideCurrentCompartment(T thing) const {
214 return thing->compartment() == compartment();
215 }
216
217 void onOutOfMemory();
218 void* onOutOfMemory(js::AllocFunction allocFunc, arena_id_t arena,
219 size_t nbytes, void* reallocPtr = nullptr) {
220 return runtime_->onOutOfMemory(allocFunc, arena, nbytes, reallocPtr, this);
221 }
222
223 void onOverRecursed();
224
225 // Allocate a GC thing.
226 template <typename T, js::AllowGC allowGC = js::CanGC, typename... Args>
227 T* newCell(Args&&... args);
228
229 /* Clear the pending exception (if any) due to OOM. */
230 void recoverFromOutOfMemory();
231
232 void reportAllocationOverflow();
233
234 // Accessors for immutable runtime data.
235 JSAtomState& names() { return *runtime_->commonNames; }
236 js::StaticStrings& staticStrings() { return *runtime_->staticStrings; }
237 bool permanentAtomsPopulated() { return runtime_->permanentAtomsPopulated(); }
238 const js::FrozenAtomSet& permanentAtoms() {
239 return *runtime_->permanentAtoms();
240 }
241 js::WellKnownSymbols& wellKnownSymbols() {
242 return *runtime_->wellKnownSymbols;
243 }
244 js::PropertyName* emptyString() { return runtime_->emptyString; }
245 JS::GCContext* gcContext() { return runtime_->gcContext(); }
246 JS::StackKind stackKindForCurrentPrincipal();
247 JS::NativeStackLimit stackLimitForCurrentPrincipal();
248 JS::NativeStackLimit stackLimit(JS::StackKind kind) {
249 return nativeStackLimit[kind];
250 }
251 JS::NativeStackLimit stackLimitForJitCode(JS::StackKind kind);
252 size_t gcSystemPageSize() { return js::gc::SystemPageSize(); }
253
254 /*
255 * "Entering" a realm changes cx->realm (which changes cx->global). Note
256 * that this does not push an Activation so it's possible for the caller's
257 * realm to be != cx->realm(). This is not a problem since, in general, most
258 * places in the VM cannot know that they were called from script (e.g.,
259 * they may have been called through the JSAPI via JS_CallFunction) and thus
260 * cannot expect there is a scripted caller.
261 *
262 * Realms should be entered/left in a LIFO fasion. To enter a realm, code
263 * should prefer using AutoRealm over JS::EnterRealm/JS::LeaveRealm.
264 *
265 * Also note that the JIT can enter (same-compartment) realms without going
266 * through these methods - it will update cx->realm_ directly.
267 */
268 private:
269 inline void setRealm(JS::Realm* realm);
270 inline void enterRealm(JS::Realm* realm);
271
272 inline void enterAtomsZone();
273 inline void leaveAtomsZone(JS::Realm* oldRealm);
274 inline void setZone(js::Zone* zone);
275
276 friend class js::AutoAllocInAtomsZone;
277 friend class js::AutoMaybeLeaveAtomsZone;
278 friend class js::AutoRealm;
279
280 public:
281 inline void enterRealmOf(JSObject* target);
282 inline void enterRealmOf(JSScript* target);
283 inline void enterRealmOf(js::Shape* target);
284 inline void enterNullRealm();
285
286 inline void setRealmForJitExceptionHandler(JS::Realm* realm);
287
288 inline void leaveRealm(JS::Realm* oldRealm);
289
290 // Threads may freely access any data in their realm, compartment and zone.
291 JS::Compartment* compartment() const {
292 return realm_ ? JS::GetCompartmentForRealm(realm_) : nullptr;
293 }
294
295 JS::Realm* realm() const { return realm_; }
296
297 #ifdef DEBUG
298 bool inAtomsZone() const;
299 #endif
300
301 JS::Zone* zone() const {
302 MOZ_ASSERT_IF(!realm() && zone_, inAtomsZone());
303 MOZ_ASSERT_IF(realm(), js::GetRealmZone(realm()) == zone_);
304 return zone_;
305 }
306
307 // For JIT use.
308 static size_t offsetOfZone() { return offsetof(JSContext, zone_); }
309
310 // Current global. This is only safe to use within the scope of the
311 // AutoRealm from which it's called.
312 inline js::Handle<js::GlobalObject*> global() const;
313
314 js::AtomsTable& atoms() { return runtime_->atoms(); }
315
316 js::SymbolRegistry& symbolRegistry() { return runtime_->symbolRegistry(); }
317
318 // Methods to access other runtime data that checks locking internally.
319 js::gc::AtomMarkingRuntime& atomMarking() { return runtime_->gc.atomMarking; }
320 void markAtom(JSAtom* atom) { atomMarking().markAtom(this, atom); }
321 void markAtom(JS::Symbol* symbol) { atomMarking().markAtom(this, symbol); }
322 void markId(jsid id) { atomMarking().markId(this, id); }
323 void markAtomValue(const js::Value& value) {
324 atomMarking().markAtomValue(this, value);
325 }
326
327 // Interface for recording telemetry metrics.
328 js::Metrics metrics() { return js::Metrics(runtime_); }
329
330 JSRuntime* runtime() { return runtime_; }
331 const JSRuntime* runtime() const { return runtime_; }
332
333 static size_t offsetOfRealm() { return offsetof(JSContext, realm_); }
334
335 friend class JS::AutoSaveExceptionState;
336 friend class js::jit::DebugModeOSRVolatileJitFrameIter;
337 friend void js::ReportOutOfMemory(JSContext*);
338 friend void js::ReportOverRecursed(JSContext*);
339 friend void js::ReportOversizedAllocation(JSContext*, const unsigned);
340
341 public:
342 /**
343 * Intentionally awkward signpost method that is stationed on the
344 * boundary between Result-using and non-Result-using code.
345 */
346 template <typename V, typename E>
347 bool resultToBool(const JS::Result<V, E>& result) {
348 return result.isOk();
349 }
350
351 template <typename V, typename E>
352 V* resultToPtr(JS::Result<V*, E>& result) {
353 return result.isOk() ? result.unwrap() : nullptr;
354 }
355
356 mozilla::GenericErrorResult<JS::OOM> alreadyReportedOOM();
357 mozilla::GenericErrorResult<JS::Error> alreadyReportedError();
358
359 /*
360 * Points to the most recent JitActivation pushed on the thread.
361 * See JitActivation constructor in vm/Stack.cpp
362 */
363 js::ContextData<js::jit::JitActivation*> jitActivation;
364
365 // Shim for V8 interfaces used by irregexp code
366 js::ContextData<js::irregexp::Isolate*> isolate;
367
368 /*
369 * Points to the most recent activation running on the thread.
370 * See Activation comment in vm/Stack.h.
371 */
372 js::ContextData<js::Activation*> activation_;
373
374 /*
375 * Points to the most recent profiling activation running on the
376 * thread.
377 */
378 js::Activation* volatile profilingActivation_;
379
380 public:
381 js::Activation* activation() const { return activation_; }
382 static size_t offsetOfActivation() {
383 return offsetof(JSContext, activation_);
384 }
385
386 js::Activation* profilingActivation() const { return profilingActivation_; }
387 static size_t offsetOfProfilingActivation() {
388 return offsetof(JSContext, profilingActivation_);
389 }
390
391 static size_t offsetOfJitActivation() {
392 return offsetof(JSContext, jitActivation);
393 }
394
395 #ifdef JS_CHECK_UNSAFE_CALL_WITH_ABI
396 static size_t offsetOfInUnsafeCallWithABI() {
397 return offsetof(JSContext, inUnsafeCallWithABI);
398 }
399 #endif
400
401 static size_t offsetOfInlinedICScript() {
402 return offsetof(JSContext, inlinedICScript_);
403 }
404
405 public:
406 js::InterpreterStack& interpreterStack() {
407 return runtime()->interpreterStack();
408 }
409 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
410 js::PortableBaselineStack& portableBaselineStack() {
411 return runtime()->portableBaselineStack();
412 }
413 #endif
414
415 private:
416 // Base address of the native stack for the current thread.
417 mozilla::Maybe<JS::NativeStackBase> nativeStackBase_;
418
419 public:
420 JS::NativeStackBase nativeStackBase() const { return *nativeStackBase_; }
421
422 public:
423 // In brittle mode, any failure will produce a diagnostic assertion rather
424 // than propagating an error or throwing an exception. This is used for
425 // intermittent crash diagnostics: if an operation is failing for unknown
426 // reasons, turn on brittle mode and annotate the operations within
427 // SpiderMonkey that the failing operation uses with:
428 //
429 // MOZ_DIAGNOSTIC_ASSERT(!cx->brittleMode, "specific failure");
430 //
431 bool brittleMode = false;
432
433 /*
434 * Stack of debuggers that currently disallow debuggee execution.
435 *
436 * When we check for NX we are inside the debuggee compartment, and thus a
437 * stack of Debuggers that have prevented execution need to be tracked to
438 * enter the correct Debugger compartment to report the error.
439 */
440 js::ContextData<js::EnterDebuggeeNoExecute*> noExecuteDebuggerTop;
441
442 #ifdef JS_CHECK_UNSAFE_CALL_WITH_ABI
443 js::ContextData<uint32_t> inUnsafeCallWithABI;
444 js::ContextData<bool> hasAutoUnsafeCallWithABI;
445 #endif
446
447 #ifdef DEBUG
448 js::ContextData<uint32_t> liveArraySortDataInstances;
449 #endif
450
451 #ifdef JS_SIMULATOR
452 private:
453 js::ContextData<js::jit::Simulator*> simulator_;
454
455 public:
456 js::jit::Simulator* simulator() const;
457 JS::NativeStackLimit* addressOfSimulatorStackLimit();
458 #endif
459
460 public:
461 // State used by util/DoubleToString.cpp.
462 js::ContextData<DtoaState*> dtoaState;
463
464 /*
465 * When this flag is non-zero, any attempt to GC will be skipped. See the
466 * AutoSuppressGC class for for details.
467 */
468 js::ContextData<int32_t> suppressGC;
469
470 #ifdef FUZZING_JS_FUZZILLI
471 uint32_t executionHash;
472 uint32_t executionHashInputs;
473 #endif
474
475 #ifdef DEBUG
476 js::ContextData<size_t> noNurseryAllocationCheck;
477
478 /*
479 * If this is 0, all cross-compartment proxies must be registered in the
480 * wrapper map. This checking must be disabled temporarily while creating
481 * new wrappers. When non-zero, this records the recursion depth of wrapper
482 * creation.
483 */
484 js::ContextData<uintptr_t> disableStrictProxyCheckingCount;
485
486 bool isNurseryAllocAllowed() { return noNurseryAllocationCheck == 0; }
487 void disallowNurseryAlloc() { ++noNurseryAllocationCheck; }
488 void allowNurseryAlloc() {
489 MOZ_ASSERT(!isNurseryAllocAllowed());
490 --noNurseryAllocationCheck;
491 }
492
493 bool isStrictProxyCheckingEnabled() {
494 return disableStrictProxyCheckingCount == 0;
495 }
496 void disableStrictProxyChecking() { ++disableStrictProxyCheckingCount; }
497 void enableStrictProxyChecking() {
498 MOZ_ASSERT(disableStrictProxyCheckingCount > 0);
499 --disableStrictProxyCheckingCount;
500 }
501 #endif
502
503 #if defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
504 // We are currently running a simulated OOM test.
505 js::ContextData<bool> runningOOMTest;
506 #endif
507
508 /*
509 * Some regions of code are hard for the static rooting hazard analysis to
510 * understand. In those cases, we trade the static analysis for a dynamic
511 * analysis. When this is non-zero, we should assert if we trigger, or
512 * might trigger, a GC.
513 */
514 js::ContextData<int> inUnsafeRegion;
515
516 // Count of AutoDisableGenerationalGC instances on the thread's stack.
517 js::ContextData<unsigned> generationalDisabled;
518
519 // Some code cannot tolerate compacting GC so it can be disabled temporarily
520 // with AutoDisableCompactingGC which uses this counter.
521 js::ContextData<unsigned> compactingDisabledCount;
522
523 // Match limit result for the most recent call to RegExpSearcher.
524 js::ContextData<uint32_t> regExpSearcherLastLimit;
525
526 static constexpr size_t offsetOfRegExpSearcherLastLimit() {
527 return offsetof(JSContext, regExpSearcherLastLimit);
528 }
529
530 // Whether we are currently executing the top level of a module.
531 js::ContextData<uint32_t> isEvaluatingModule;
532
533 private:
534 // Pools used for recycling name maps and vectors when parsing and
535 // emitting bytecode. Purged on GC when there are no active script
536 // compilations.
537 js::ContextData<js::frontend::NameCollectionPool> frontendCollectionPool_;
538
539 public:
540 js::frontend::NameCollectionPool& frontendCollectionPool() {
541 return frontendCollectionPool_.ref();
542 }
543
544 void verifyIsSafeToGC() {
545 MOZ_DIAGNOSTIC_ASSERT(!inUnsafeRegion,
546 "[AutoAssertNoGC] possible GC in GC-unsafe region");
547 }
548
549 bool isInUnsafeRegion() const { return bool(inUnsafeRegion); }
550
551 // For JIT use.
552 MOZ_NEVER_INLINE void resetInUnsafeRegion() {
553 MOZ_ASSERT(inUnsafeRegion >= 0);
554 inUnsafeRegion = 0;
555 }
556
557 static constexpr size_t offsetOfInUnsafeRegion() {
558 return offsetof(JSContext, inUnsafeRegion);
559 }
560
561 /* Whether sampling should be enabled or not. */
562 private:
563 mozilla::Atomic<bool, mozilla::SequentiallyConsistent>
564 suppressProfilerSampling;
565
566 public:
567 bool isProfilerSamplingEnabled() const { return !suppressProfilerSampling; }
568 void disableProfilerSampling() { suppressProfilerSampling = true; }
569 void enableProfilerSampling() { suppressProfilerSampling = false; }
570
571 private:
572 js::wasm::Context wasm_;
573
574 public:
575 js::wasm::Context& wasm() { return wasm_; }
576
577 /* Temporary arena pool used while compiling and decompiling. */
578 static const size_t TEMP_LIFO_ALLOC_PRIMARY_CHUNK_SIZE = 4 * 1024;
579
580 private:
581 js::ContextData<js::LifoAlloc> tempLifoAlloc_;
582
583 public:
584 js::LifoAlloc& tempLifoAlloc() { return tempLifoAlloc_.ref(); }
585 const js::LifoAlloc& tempLifoAlloc() const { return tempLifoAlloc_.ref(); }
586
587 js::ContextData<uint32_t> debuggerMutations;
588
589 private:
590 // Indicates if an exception is pending and the reason for it.
591 js::ContextData<JS::ExceptionStatus> status;
592 js::ContextData<JS::PersistentRooted<JS::Value>>
593 unwrappedException_; /* most-recently-thrown exception */
594 js::ContextData<JS::PersistentRooted<js::SavedFrame*>>
595 unwrappedExceptionStack_; /* stack when the exception was thrown */
596
597 JS::Value& unwrappedException() {
598 if (!unwrappedException_.ref().initialized()) {
599 unwrappedException_.ref().init(this);
600 }
601 return unwrappedException_.ref().get();
602 }
603
604 js::SavedFrame*& unwrappedExceptionStack() {
605 if (!unwrappedExceptionStack_.ref().initialized()) {
606 unwrappedExceptionStack_.ref().init(this);
607 }
608 return unwrappedExceptionStack_.ref().get();
609 }
610
611 #ifdef DEBUG
612 // True if this context has ever thrown an exception because of an exceeded
613 // limit: stack space (ReportOverRecursed), memory (ReportOutOfMemory), or
614 // some other self-imposed limit (eg ReportOversizedAllocation). Used when
615 // detecting bailout loops in WarpOracle: bailout loops involving resource
616 // exhaustion are generally not interesting.
617 js::ContextData<bool> hadResourceExhaustion_;
618
619 // True if this context has ever thrown an uncatchable exception to terminate
620 // execution from the interrupt callback.
621 js::ContextData<bool> hadUncatchableException_;
622
623 public:
624 bool hadResourceExhaustion() const {
625 return hadResourceExhaustion_ || js::oom::simulator.isThreadSimulatingAny();
626 }
627 bool hadUncatchableException() const { return hadUncatchableException_; }
628 #endif
629
630 public:
631 void reportResourceExhaustion() {
632 #ifdef DEBUG
633 hadResourceExhaustion_ = true;
634 #endif
635 }
636 void reportUncatchableException() {
637 // Make sure the context has no pending exception. See also the comment for
638 // JS::ReportUncatchableException.
639 clearPendingException();
640 #ifdef DEBUG
641 hadUncatchableException_ = true;
642 #endif
643 }
644
645 js::ContextData<int32_t> reportGranularity; /* see vm/Probes.h */
646
647 js::ContextData<js::AutoResolving*> resolvingList;
648
649 #ifdef DEBUG
650 js::ContextData<js::AutoEnterPolicy*> enteredPolicy;
651 #endif
652
653 /* True if generating an error, to prevent runaway recursion. */
654 js::ContextData<bool> generatingError;
655
656 private:
657 /* State for object and array toSource conversion. */
658 js::ContextData<js::AutoCycleDetector::Vector> cycleDetectorVector_;
659
660 public:
661 js::AutoCycleDetector::Vector& cycleDetectorVector() {
662 return cycleDetectorVector_.ref();
663 }
664 const js::AutoCycleDetector::Vector& cycleDetectorVector() const {
665 return cycleDetectorVector_.ref();
666 }
667
668 /* Client opaque pointer. */
669 js::UnprotectedData<void*> data;
670
671 void initJitStackLimit();
672 void resetJitStackLimit();
673
674 public:
675 JS::ContextOptions& options() { return options_.ref(); }
676
677 bool runtimeMatches(JSRuntime* rt) const { return runtime_ == rt; }
678
679 private:
680 /*
681 * Youngest frame of a saved stack that will be picked up as an async stack
682 * by any new Activation, and is nullptr when no async stack should be used.
683 *
684 * The JS::AutoSetAsyncStackForNewCalls class can be used to set this.
685 *
686 * New activations will reset this to nullptr on construction after getting
687 * the current value, and will restore the previous value on destruction.
688 */
689 js::ContextData<JS::PersistentRooted<js::SavedFrame*>>
690 asyncStackForNewActivations_;
691
692 public:
693 js::SavedFrame*& asyncStackForNewActivations() {
694 if (!asyncStackForNewActivations_.ref().initialized()) {
695 asyncStackForNewActivations_.ref().init(this);
696 }
697 return asyncStackForNewActivations_.ref().get();
698 }
699
700 /*
701 * Value of asyncCause to be attached to asyncStackForNewActivations.
702 */
703 js::ContextData<const char*> asyncCauseForNewActivations;
704
705 /*
706 * True if the async call was explicitly requested, e.g. via
707 * callFunctionWithAsyncStack.
708 */
709 js::ContextData<bool> asyncCallIsExplicit;
710
711 bool currentlyRunningInInterpreter() const {
712 return activation()->isInterpreter();
713 }
714 bool currentlyRunningInJit() const { return activation()->isJit(); }
715 js::InterpreterFrame* interpreterFrame() const {
716 return activation()->asInterpreter()->current();
717 }
718 js::InterpreterRegs& interpreterRegs() const {
719 return activation()->asInterpreter()->regs();
720 }
721
722 /*
723 * Get the topmost script and optional pc on the stack. By default, this
724 * function only returns a JSScript in the current realm, returning nullptr
725 * if the current script is in a different realm. This behavior can be
726 * overridden by passing AllowCrossRealm::Allow.
727 */
728 enum class AllowCrossRealm { DontAllow = false, Allow = true };
729 JSScript* currentScript(
730 jsbytecode** ppc = nullptr,
731 AllowCrossRealm allowCrossRealm = AllowCrossRealm::DontAllow);
732
733 inline void minorGC(JS::GCReason reason);
734
735 public:
736 bool isExceptionPending() const {
737 return JS::IsCatchableExceptionStatus(status);
738 }
739
740 /**
741 * Return the pending exception and wrap it into the current compartment.
742 */
743 [[nodiscard]] bool getPendingException(JS::MutableHandleValue rval);
744
745 /**
746 * Return the pending exception stack and wrap it into the current
747 * compartment. Return |JS::NullValue| when the pending exception has no stack
748 * attached.
749 */
750 [[nodiscard]] bool getPendingExceptionStack(JS::MutableHandleValue rval);
751
752 /**
753 * Return the pending exception stack, but does not wrap it into the current
754 * compartment. Return |nullptr| when the pending exception has no stack
755 * attached.
756 */
757 js::SavedFrame* getPendingExceptionStack();
758
759 #ifdef DEBUG
760 /**
761 * Return the pending exception (without wrapping).
762 */
763 const JS::Value& getPendingExceptionUnwrapped();
764 #endif
765
766 bool isThrowingDebuggeeWouldRun();
767 bool isClosingGenerator();
768
769 void setPendingException(JS::HandleValue v,
770 JS::Handle<js::SavedFrame*> stack);
771 void setPendingException(JS::HandleValue v,
772 js::ShouldCaptureStack captureStack);
773
774 void clearPendingException() {
775 status = JS::ExceptionStatus::None;
776 unwrappedException().setUndefined();
777 unwrappedExceptionStack() = nullptr;
778 }
779
780 bool isThrowingOutOfMemory() const {
781 return status == JS::ExceptionStatus::OutOfMemory;
782 }
783 bool isThrowingOverRecursed() const {
784 return status == JS::ExceptionStatus::OverRecursed;
785 }
786 bool isPropagatingForcedReturn() const {
787 return status == JS::ExceptionStatus::ForcedReturn;
788 }
789 void setPropagatingForcedReturn() {
790 MOZ_ASSERT(status == JS::ExceptionStatus::None);
791 status = JS::ExceptionStatus::ForcedReturn;
792 }
793 void clearPropagatingForcedReturn() {
794 MOZ_ASSERT(status == JS::ExceptionStatus::ForcedReturn);
795 status = JS::ExceptionStatus::None;
796 }
797
798 /*
799 * See JS_SetTrustedPrincipals in jsapi.h.
800 * Note: !cx->realm() is treated as trusted.
801 */
802 inline bool runningWithTrustedPrincipals();
803
804 // Checks if the page's Content-Security-Policy (CSP) allows
805 // runtime code generation "unsafe-eval", or "wasm-unsafe-eval" for Wasm.
806 bool isRuntimeCodeGenEnabled(
807 JS::RuntimeCode kind, JS::Handle<JSString*> codeString,
808 JS::CompilationType compilationType,
809 JS::Handle<JS::StackGCVector<JSString*>> parameterStrings,
810 JS::Handle<JSString*> bodyString,
811 JS::Handle<JS::StackGCVector<JS::Value>> parameterArgs,
812 JS::Handle<JS::Value> bodyArg, bool* outCanCompileStrings);
813
814 // Get code to be used by eval for Object argument.
815 bool getCodeForEval(JS::HandleObject code,
816 JS::MutableHandle<JSString*> outCode);
817
818 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
819 size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
820
821 void trace(JSTracer* trc);
822
823 inline js::RuntimeCaches& caches();
824
825 public:
826 using InterruptCallbackVector =
827 js::Vector<JSInterruptCallback, 2, js::SystemAllocPolicy>;
828
829 private:
830 js::ContextData<InterruptCallbackVector> interruptCallbacks_;
831
832 public:
833 InterruptCallbackVector& interruptCallbacks() {
834 return interruptCallbacks_.ref();
835 }
836
837 js::ContextData<bool> interruptCallbackDisabled;
838
839 // Bitfield storing InterruptReason values.
840 mozilla::Atomic<uint32_t, mozilla::Relaxed> interruptBits_;
841
842 // Any thread can call requestInterrupt() to request that this thread
843 // stop running. To stop this thread, requestInterrupt sets two fields:
844 // interruptBits_ (a bitset of InterruptReasons) and jitStackLimit (set to
845 // JS::NativeStackLimitMin). The JS engine must continually poll one of these
846 // fields and call handleInterrupt if either field has the interrupt value.
847 //
848 // The point of setting jitStackLimit to JS::NativeStackLimitMin is that JIT
849 // code already needs to guard on jitStackLimit in every function prologue to
850 // avoid stack overflow, so we avoid a second branch on interruptBits_ by
851 // setting jitStackLimit to a value that is guaranteed to fail the guard.)
852 //
853 // Note that the writes to interruptBits_ and jitStackLimit use a Relaxed
854 // Atomic so, while the writes are guaranteed to eventually be visible to
855 // this thread, it can happen in any order. handleInterrupt calls the
856 // interrupt callback if either is set, so it really doesn't matter as long
857 // as the JS engine is continually polling at least one field. In corner
858 // cases, this relaxed ordering could lead to an interrupt handler being
859 // called twice in succession after a single requestInterrupt call, but
860 // that's fine.
861 void requestInterrupt(js::InterruptReason reason);
862 bool handleInterrupt();
863
864 MOZ_ALWAYS_INLINE bool hasAnyPendingInterrupt() const {
865 static_assert(sizeof(interruptBits_) == sizeof(uint32_t),
866 "Assumed by JIT callers");
867 return interruptBits_ != 0;
868 }
869 bool hasPendingInterrupt(js::InterruptReason reason) const {
870 return interruptBits_ & uint32_t(reason);
871 }
872 void clearPendingInterrupt(js::InterruptReason reason);
873
874 // For JIT use. Points to the inlined ICScript for a baseline script
875 // being invoked as part of a trial inlining. Contains nullptr at
876 // all times except for the brief moment between being set in the
877 // caller and read in the callee's prologue.
878 js::ContextData<js::jit::ICScript*> inlinedICScript_;
879
880 public:
881 void* addressOfInterruptBits() { return &interruptBits_; }
882 void* addressOfJitStackLimit() { return &jitStackLimit; }
883 void* addressOfJitStackLimitNoInterrupt() {
884 return &jitStackLimitNoInterrupt;
885 }
886 void* addressOfZone() { return &zone_; }
887
888 const void* addressOfRealm() const { return &realm_; }
889
890 void* addressOfInlinedICScript() { return &inlinedICScript_; }
891
892 const void* addressOfJitActivation() const { return &jitActivation; }
893
894 // Futex state, used by Atomics.wait() and Atomics.wake() on the Atomics
895 // object.
896 js::FutexThread fx;
897
898 mozilla::Atomic<JS::NativeStackLimit, mozilla::Relaxed> jitStackLimit;
899
900 // Like jitStackLimit, but not reset to trigger interrupts.
901 js::ContextData<JS::NativeStackLimit> jitStackLimitNoInterrupt;
902
903 // Queue of pending jobs as described in ES2016 section 8.4.
904 //
905 // This is a non-owning pointer to either:
906 // - a JobQueue implementation the embedding provided by calling
907 // JS::SetJobQueue, owned by the embedding, or
908 // - our internal JobQueue implementation, established by calling
909 // js::UseInternalJobQueues, owned by JSContext::internalJobQueue below.
910 js::ContextData<JS::JobQueue*> jobQueue;
911
912 // If the embedding has called js::UseInternalJobQueues, this is the owning
913 // pointer to our internal JobQueue implementation, which JSContext::jobQueue
914 // borrows.
915 js::ContextData<js::UniquePtr<js::InternalJobQueue>> internalJobQueue;
916
917 // True if jobQueue is empty, or we are running the last job in the queue.
918 // Such conditions permit optimizations around `await` expressions.
919 js::ContextData<bool> canSkipEnqueuingJobs;
920
921 js::ContextData<JS::PromiseRejectionTrackerCallback>
922 promiseRejectionTrackerCallback;
923 js::ContextData<void*> promiseRejectionTrackerCallbackData;
924
925 JSObject* getIncumbentGlobal(JSContext* cx);
926 bool enqueuePromiseJob(JSContext* cx, js::HandleFunction job,
927 js::HandleObject promise,
928 js::HandleObject incumbentGlobal);
929 void addUnhandledRejectedPromise(JSContext* cx, js::HandleObject promise);
930 void removeUnhandledRejectedPromise(JSContext* cx, js::HandleObject promise);
931
932 private:
933 template <class... Args>
934 inline void checkImpl(const Args&... args);
935
936 bool contextChecksEnabled() const {
937 // Don't perform these checks when called from a finalizer. The checking
938 // depends on other objects not having been swept yet.
939 return !RuntimeHeapIsCollecting(runtime()->heapState());
940 }
941
942 public:
943 // Assert the arguments are in this context's realm (for scripts),
944 // compartment (for objects) or zone (for strings, symbols).
945 template <class... Args>
946 inline void check(const Args&... args);
947 template <class... Args>
948 inline void releaseCheck(const Args&... args);
949 template <class... Args>
950 MOZ_ALWAYS_INLINE void debugOnlyCheck(const Args&... args);
951
952 #ifdef JS_STRUCTURED_SPEW
953 private:
954 // Spewer for this thread
955 js::UnprotectedData<js::StructuredSpewer> structuredSpewer_;
956
957 public:
958 js::StructuredSpewer& spewer() { return structuredSpewer_.ref(); }
959 #endif
960
961 // Debugger having set `exclusiveDebuggerOnEval` property to true
962 // want their evaluations and calls to be ignore by all other Debuggers
963 // except themself. This flag indicates whether we are in such debugger
964 // evaluation, and which debugger initiated the evaluation. This debugger
965 // has other references on the stack and does not need to be traced.
966 js::ContextData<js::Debugger*> insideExclusiveDebuggerOnEval;
967
968 #ifdef MOZ_EXECUTION_TRACING
969 private:
970 // This holds onto the JS execution tracer, a system which when turned on
971 // records function calls and other information about the JS which has been
972 // run under this context.
973 js::UniquePtr<js::ExecutionTracer> executionTracer_;
974
975 // See suspendExecutionTracing
976 bool executionTracerSuspended_ = false;
977
978 // Cleans up caches and realm flags associated with execution tracing, while
979 // leaving the underlying tracing buffers intact to be read from later.
980 void cleanUpExecutionTracingState();
981
982 public:
983 js::ExecutionTracer& getExecutionTracer() {
984 MOZ_ASSERT(hasExecutionTracer());
985 return *executionTracer_;
986 }
987
988 // See the latter clause of the comment over executionTracer_
989 [[nodiscard]] bool enableExecutionTracing();
990 void disableExecutionTracing();
991
992 // suspendExecutionTracing will turn off tracing, and clean up the relevant
993 // flags on this context's realms, but still leave the trace around to be
994 // collected. This currently is only called when an error occurs during
995 // tracing.
996 void suspendExecutionTracing();
997
998 // Returns true if there is currently an ExecutionTracer tracing this
999 // context's execution.
1000 bool hasExecutionTracer() {
1001 return !!executionTracer_ && !executionTracerSuspended_;
1002 }
1003 #else
1004 bool hasExecutionTracer() { return false; }
1005 #endif
1006
1007 }; /* struct JSContext */
1008
1009 inline JSContext* JSRuntime::mainContextFromOwnThread() {
1010 MOZ_ASSERT(mainContextFromAnyThread() == js::TlsContext.get());
1011 return mainContextFromAnyThread();
1012 }
1013
1014 namespace js {
1015
1016 struct MOZ_RAII AutoResolving {
1017 public:
1018 AutoResolving(JSContext* cx, HandleObject obj, HandleId id)
1019 : context(cx), object(obj), id(id), link(cx->resolvingList) {
1020 MOZ_ASSERT(obj);
1021 cx->resolvingList = this;
1022 }
1023
1024 ~AutoResolving() {
1025 MOZ_ASSERT(context->resolvingList == this);
1026 context->resolvingList = link;
1027 }
1028
1029 bool alreadyStarted() const { return link && alreadyStartedSlow(); }
1030
1031 private:
1032 bool alreadyStartedSlow() const;
1033
1034 JSContext* const context;
1035 HandleObject object;
1036 HandleId id;
1037 AutoResolving* const link;
1038 };
1039
1040 /*
1041 * Create and destroy functions for JSContext, which is manually allocated
1042 * and exclusively owned.
1043 */
1044 extern JSContext* NewContext(uint32_t maxBytes, JSRuntime* parentRuntime);
1045
1046 extern void DestroyContext(JSContext* cx);
1047
1048 /* |callee| requires a usage string provided by JS_DefineFunctionsWithHelp. */
1049 extern void ReportUsageErrorASCII(JSContext* cx, HandleObject callee,
1050 const char* msg);
1051
1052 extern void ReportIsNotDefined(JSContext* cx, Handle<PropertyName*> name);
1053
1054 extern void ReportIsNotDefined(JSContext* cx, HandleId id);
1055
1056 /*
1057 * Report an attempt to access the property of a null or undefined value (v).
1058 */
1059 extern void ReportIsNullOrUndefinedForPropertyAccess(JSContext* cx,
1060 HandleValue v, int vIndex);
1061 extern void ReportIsNullOrUndefinedForPropertyAccess(JSContext* cx,
1062 HandleValue v, int vIndex,
1063 HandleId key);
1064
1065 /*
1066 * Report error using js::DecompileValueGenerator(cx, spindex, v, fallback) as
1067 * the first argument for the error message.
1068 */
1069 extern bool ReportValueError(JSContext* cx, const unsigned errorNumber,
1070 int spindex, HandleValue v, HandleString fallback,
1071 const char* arg1 = nullptr,
1072 const char* arg2 = nullptr);
1073
1074 JSObject* CreateErrorNotesArray(JSContext* cx, JSErrorReport* report);
1075
1076 /************************************************************************/
1077
1078 /*
1079 * Encapsulates an external array of values and adds a trace method, for use in
1080 * Rooted.
1081 */
1082 class MOZ_STACK_CLASS ExternalValueArray {
1083 public:
1084 ExternalValueArray(size_t len, Value* vec) : array_(vec), length_(len) {}
1085
1086 Value* begin() { return array_; }
1087 size_t length() { return length_; }
1088
1089 void trace(JSTracer* trc);
1090
1091 private:
1092 Value* array_;
1093 size_t length_;
1094 };
1095
1096 /* RootedExternalValueArray roots an external array of Values. */
1097 class MOZ_RAII RootedExternalValueArray
1098 : public JS::Rooted<ExternalValueArray> {
1099 public:
1100 RootedExternalValueArray(JSContext* cx, size_t len, Value* vec)
1101 : JS::Rooted<ExternalValueArray>(cx, ExternalValueArray(len, vec)) {}
1102
1103 private:
1104 };
1105
1106 class AutoAssertNoPendingException {
1107 #ifdef DEBUG
1108 JSContext* cx_;
1109
1110 public:
1111 explicit AutoAssertNoPendingException(JSContext* cxArg) : cx_(cxArg) {
1112 MOZ_ASSERT(!JS_IsExceptionPending(cx_));
1113 }
1114
1115 ~AutoAssertNoPendingException() { MOZ_ASSERT(!JS_IsExceptionPending(cx_)); }
1116 #else
1117 public:
1118 explicit AutoAssertNoPendingException(JSContext* cxArg) {}
1119 #endif
1120 };
1121
1122 class MOZ_RAII AutoNoteExclusiveDebuggerOnEval {
1123 JSContext* cx;
1124 Debugger* oldValue;
1125
1126 public:
1127 AutoNoteExclusiveDebuggerOnEval(JSContext* cx, Debugger* dbg)
1128 : cx(cx), oldValue(cx->insideExclusiveDebuggerOnEval) {
1129 cx->insideExclusiveDebuggerOnEval = dbg;
1130 }
1131
1132 ~AutoNoteExclusiveDebuggerOnEval() {
1133 cx->insideExclusiveDebuggerOnEval = oldValue;
1134 }
1135 };
1136
1137 enum UnsafeABIStrictness {
1138 NoExceptions,
1139 AllowPendingExceptions,
1140 AllowThrownExceptions
1141 };
1142
1143 // Should be used in functions called directly from JIT code (with
1144 // masm.callWithABI). This assert invariants in debug builds. Resets
1145 // JSContext::inUnsafeCallWithABI on destruction.
1146 //
1147 // In debug mode, masm.callWithABI inserts code to verify that the callee
1148 // function uses AutoUnsafeCallWithABI.
1149 //
1150 // While this object is live:
1151 // 1. cx->hasAutoUnsafeCallWithABI must be true.
1152 // 2. We can't GC.
1153 // 3. Exceptions should not be pending/thrown.
1154 //
1155 // Note that #3 is a precaution, not a requirement. By default, we assert that
1156 // the function is not called with a pending exception, and that it does not
1157 // throw an exception itself.
1158 class MOZ_RAII AutoUnsafeCallWithABI {
1159 #ifdef JS_CHECK_UNSAFE_CALL_WITH_ABI
1160 JSContext* cx_;
1161 bool nested_;
1162 bool checkForPendingException_;
1163 #endif
1164 JS::AutoCheckCannotGC nogc;
1165
1166 public:
1167 #ifdef JS_CHECK_UNSAFE_CALL_WITH_ABI
1168 explicit AutoUnsafeCallWithABI(
1169 UnsafeABIStrictness strictness = UnsafeABIStrictness::NoExceptions);
1170 ~AutoUnsafeCallWithABI();
1171 #else
1172 explicit AutoUnsafeCallWithABI(
1173 UnsafeABIStrictness unused_ = UnsafeABIStrictness::NoExceptions) {}
1174 #endif
1175 };
1176
1177 } /* namespace js */
1178
1179 #define CHECK_THREAD(cx) \
1180 MOZ_ASSERT_IF(cx, js::CurrentThreadCanAccessRuntime(cx->runtime()))
1181
1182 /**
1183 * [SMDOC] JS::Result transitional macros
1184 *
1185 * ## Checking Results when your return type is not Result
1186 *
1187 * This header defines alternatives to MOZ_TRY and MOZ_TRY_VAR for when you
1188 * need to call a `Result` function from a function that uses false or nullptr
1189 * to indicate errors:
1190 *
1191 * JS_TRY_OR_RETURN_FALSE(cx, DefenestrateObject(cx, obj));
1192 * JS_TRY_VAR_OR_RETURN_FALSE(cx, v, GetObjectThrug(cx, obj));
1193 *
1194 * JS_TRY_VAR_OR_RETURN_NULL(cx, v, GetObjectThrug(cx, obj));
1195 *
1196 * When TRY is not what you want, because you need to do some cleanup or
1197 * recovery on error, use this idiom:
1198 *
1199 * if (!cx->resultToBool(expr_that_is_a_Result)) {
1200 * ... your recovery code here ...
1201 * }
1202 *
1203 * In place of a tail call, you can use one of these methods:
1204 *
1205 * return cx->resultToBool(expr); // false on error
1206 * return cx->resultToPtr(expr); // null on error
1207 *
1208 * Once we are using `Result` everywhere, including in public APIs, all of
1209 * these will go away.
1210 */
1211
1212 /**
1213 * JS_TRY_OR_RETURN_FALSE(cx, expr) runs expr to compute a Result value.
1214 * On success, nothing happens; on error, it returns false immediately.
1215 *
1216 * Implementation note: this involves cx because this may eventually
1217 * do the work of setting a pending exception or reporting OOM.
1218 */
1219 #define JS_TRY_OR_RETURN_FALSE(cx, expr) \
1220 do { \
1221 auto tmpResult_ = (expr); \
1222 if (tmpResult_.isErr()) return (cx)->resultToBool(tmpResult_); \
1223 } while (0)
1224
1225 #define JS_TRY_VAR_OR_RETURN_FALSE(cx, target, expr) \
1226 do { \
1227 auto tmpResult_ = (expr); \
1228 if (tmpResult_.isErr()) return (cx)->resultToBool(tmpResult_); \
1229 (target) = tmpResult_.unwrap(); \
1230 } while (0)
1231
1232 #define JS_TRY_VAR_OR_RETURN_NULL(cx, target, expr) \
1233 do { \
1234 auto tmpResult_ = (expr); \
1235 if (tmpResult_.isErr()) { \
1236 MOZ_ALWAYS_FALSE((cx)->resultToBool(tmpResult_)); \
1237 return nullptr; \
1238 } \
1239 (target) = tmpResult_.unwrap(); \
1240 } while (0)
1241
1242 #endif /* vm_JSContext_h */