Debian Codegraph @

js/src/vm/Runtime.cpp

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 #include "vm/Runtime.h"
8
9 #include "mozilla/Atomics.h"
10 #include "mozilla/DebugOnly.h"
11 #if JS_HAS_INTL_API
12 # include "mozilla/intl/Locale.h"
13 #endif
14 #include "mozilla/MemoryReporting.h"
15 #include "mozilla/ThreadLocal.h"
16
17 #include <locale.h>
18 #include <string.h>
19
20 #include "jsfriendapi.h"
21 #include "jsmath.h"
22
23 #include "frontend/CompilationStencil.h"
24 #include "frontend/ParserAtom.h" // frontend::WellKnownParserAtoms
25 #include "gc/GC.h"
26 #include "gc/PublicIterators.h"
27 #include "jit/IonCompileTask.h"
28 #include "jit/JitRuntime.h"
29 #include "jit/Simulator.h"
30 #include "js/AllocationLogging.h" // JS_COUNT_CTOR, JS_COUNT_DTOR
31 #include "js/experimental/JSStencil.h"
32 #include "js/experimental/SourceHook.h"
33 #include "js/friend/ErrorMessages.h" // JSMSG_*
34 #include "js/Interrupt.h"
35 #include "js/MemoryMetrics.h"
36 #include "js/Stack.h" // JS::NativeStackLimitMin
37 #include "js/Wrapper.h"
38 #include "js/WrapperCallbacks.h"
39 #include "vm/DateTime.h"
40 #include "vm/JSObject.h"
41 #include "vm/JSScript.h"
42 #include "vm/PromiseObject.h" // js::PromiseObject
43 #include "vm/SharedImmutableStringsCache.h"
44 #include "vm/Warnings.h" // js::WarnNumberUC
45 #include "wasm/WasmPI.h"
46 #include "wasm/WasmSignalHandlers.h"
47
48 #include "debugger/DebugAPI-inl.h"
49 #include "gc/ArenaList-inl.h"
50 #include "vm/JSContext-inl.h"
51 #include "vm/Realm-inl.h"
52
53 using namespace js;
54
55 using mozilla::Atomic;
56 using mozilla::DebugOnly;
57
58 /* static */ MOZ_THREAD_LOCAL(JSContext*) js::TlsContext;
59 /* static */
60 Atomic<size_t> JSRuntime::liveRuntimesCount;
61 Atomic<JS::LargeAllocationFailureCallback> js::OnLargeAllocationFailure;
62
63 JS::FilenameValidationCallback js::gFilenameValidationCallback = nullptr;
64
65 namespace js {
66
67 #ifndef __wasi__
68 bool gCanUseExtraThreads = true;
69 #else
70 bool gCanUseExtraThreads = false;
71 #endif
72 } // namespace js
73
74 void js::DisableExtraThreads() { gCanUseExtraThreads = false; }
75
76 const JSSecurityCallbacks js::NullSecurityCallbacks = {};
77
78 static const JSWrapObjectCallbacks DefaultWrapObjectCallbacks = {
79 TransparentObjectWrapper, nullptr};
80
81 extern bool DefaultHostEnsureCanAddPrivateElementCallback(JSContext* cx,
82 HandleValue val);
83
84 static size_t ReturnZeroSize(const void* p) { return 0; }
85
86 JSRuntime::JSRuntime(JSRuntime* parentRuntime)
87 : parentRuntime(parentRuntime),
88 #ifdef DEBUG
89 updateChildRuntimeCount(parentRuntime),
90 initialized_(false),
91 #endif
92 mainContext_(nullptr),
93 profilerSampleBufferRangeStart_(0),
94 telemetryCallback(nullptr),
95 consumeStreamCallback(nullptr),
96 reportStreamErrorCallback(nullptr),
97 hadOutOfMemory(false),
98 allowRelazificationForTesting(false),
99 destroyCompartmentCallback(nullptr),
100 sizeOfIncludingThisCompartmentCallback(nullptr),
101 destroyRealmCallback(nullptr),
102 realmNameCallback(nullptr),
103 securityCallbacks(&NullSecurityCallbacks),
104 DOMcallbacks(nullptr),
105 destroyPrincipals(nullptr),
106 readPrincipals(nullptr),
107 canAddPrivateElement(&DefaultHostEnsureCanAddPrivateElementCallback),
108 warningReporter(nullptr),
109 geckoProfiler_(thisFromCtor()),
110 trustedPrincipals_(nullptr),
111 wrapObjectCallbacks(&DefaultWrapObjectCallbacks),
112 preserveWrapperCallback(nullptr),
113 scriptEnvironmentPreparer(nullptr),
114 ctypesActivityCallback(nullptr),
115 windowProxyClass_(nullptr),
116 numRealms(0),
117 numDebuggeeRealms_(0),
118 numDebuggeeRealmsObservingCoverage_(0),
119 localeCallbacks(nullptr),
120 defaultLocale(nullptr),
121 profilingScripts(false),
122 scriptAndCountsVector(nullptr),
123 watchtowerTestingLog(nullptr),
124 jitRuntime_(nullptr),
125 gc(thisFromCtor()),
126 emptyString(nullptr),
127 #if !JS_HAS_INTL_API
128 thousandsSeparator(nullptr),
129 decimalSeparator(nullptr),
130 numGrouping(nullptr),
131 #endif
132 beingDestroyed_(false),
133 allowContentJS_(true),
134 atoms_(nullptr),
135 permanentAtoms_(nullptr),
136 staticStrings(nullptr),
137 commonNames(nullptr),
138 wellKnownSymbols(nullptr),
139 scriptDataTableHolder_(SharedScriptDataTableHolder::NeedsLock::No),
140 liveSABs(0),
141 beforeWaitCallback(nullptr),
142 afterWaitCallback(nullptr),
143 offthreadBaselineCompilationEnabled_(false),
144 offthreadIonCompilationEnabled_(true),
145 autoWritableJitCodeActive_(false),
146 oomCallback(nullptr),
147 debuggerMallocSizeOf(ReturnZeroSize),
148 stackFormat_(parentRuntime ? js::StackFormat::Default
149 : js::StackFormat::SpiderMonkey),
150 wasmInstances(mutexid::WasmRuntimeInstances),
151 moduleAsyncEvaluatingPostOrder(ASYNC_EVALUATING_POST_ORDER_INIT) {
152 JS_COUNT_CTOR(JSRuntime);
153 liveRuntimesCount++;
154
155 #ifndef __wasi__
156 // See function comment for why we call this now, not in JS_Init().
157 wasm::EnsureEagerProcessSignalHandlers();
158 #endif // __wasi__
159 }
160
161 JSRuntime::~JSRuntime() {
162 JS_COUNT_DTOR(JSRuntime);
163 MOZ_ASSERT(!initialized_);
164
165 DebugOnly<size_t> oldCount = liveRuntimesCount--;
166 MOZ_ASSERT(oldCount > 0);
167
168 MOZ_ASSERT(wasmInstances.lock()->empty());
169
170 MOZ_ASSERT(numRealms == 0);
171 MOZ_ASSERT(numDebuggeeRealms_ == 0);
172 MOZ_ASSERT(numDebuggeeRealmsObservingCoverage_ == 0);
173 }
174
175 bool JSRuntime::init(JSContext* cx, uint32_t maxbytes) {
176 #ifdef DEBUG
177 MOZ_ASSERT(!initialized_);
178 initialized_ = true;
179 #endif
180
181 if (CanUseExtraThreads() && !EnsureHelperThreadsInitialized()) {
182 return false;
183 }
184
185 mainContext_ = cx;
186
187 if (!gc.init(maxbytes)) {
188 return false;
189 }
190
191 if (!InitRuntimeNumberState(this)) {
192 return false;
193 }
194
195 // As a hack, we clear our timezone cache every time we create a new runtime.
196 // Also see the comment in JS::Realm::init().
197 js::ResetTimeZoneInternal(ResetTimeZoneMode::DontResetIfOffsetUnchanged);
198
199 caches().megamorphicSetPropCache = MakeUnique<MegamorphicSetPropCache>();
200 if (!caches().megamorphicSetPropCache) {
201 return false;
202 }
203
204 return true;
205 }
206
207 void JSRuntime::destroyRuntime() {
208 MOZ_ASSERT(!JS::RuntimeHeapIsBusy());
209 MOZ_ASSERT(childRuntimeCount == 0);
210 MOZ_ASSERT(initialized_);
211
212 #ifdef JS_HAS_INTL_API
213 sharedIntlData.ref().destroyInstance();
214 #endif
215
216 watchtowerTestingLog.ref().reset();
217
218 if (gc.wasInitialized()) {
219 /*
220 * Finish any in-progress GCs first.
221 */
222 JSContext* cx = mainContextFromOwnThread();
223 if (JS::IsIncrementalGCInProgress(cx)) {
224 gc::FinishGC(cx);
225 }
226
227 /* Free source hook early, as its destructor may want to delete roots. */
228 sourceHook = nullptr;
229
230 /*
231 * Cancel any pending, in progress or completed baseline/Ion compilations
232 * and parse tasks. Waiting for wasm and compression tasks is done
233 * synchronously (on the main thread or during parse tasks), so no
234 * explicit canceling is needed for these.
235 */
236 CancelOffThreadCompile(this);
237 CancelOffThreadDelazify(this);
238 CancelOffThreadCompressions(this);
239
240 /*
241 * Flag us as being destroyed. This allows the GC to free things like
242 * interned atoms and Ion trampolines.
243 */
244 beingDestroyed_ = true;
245
246 /* Remove persistent GC roots. */
247 gc.finishRoots();
248
249 /* Allow the GC to release scripts that were being profiled. */
250 profilingScripts = false;
251
252 JS::PrepareForFullGC(cx);
253 gc.gc(JS::GCOptions::Shutdown, JS::GCReason::DESTROY_RUNTIME);
254 }
255
256 AutoNoteSingleThreadedRegion anstr;
257
258 MOZ_ASSERT(scriptDataTableHolder().getWithoutLock().empty());
259
260 #if !JS_HAS_INTL_API
261 FinishRuntimeNumberState(this);
262 #endif
263
264 gc.finish();
265
266 for (auto [f, data] : cleanupClosures.ref()) {
267 f(data);
268 }
269 cleanupClosures.ref().clear();
270
271 defaultLocale = nullptr;
272 js_delete(jitRuntime_.ref());
273
274 #ifdef DEBUG
275 initialized_ = false;
276 #endif
277 }
278
279 void JSRuntime::addTelemetry(JSMetric id, uint32_t sample) {
280 if (telemetryCallback) {
281 (*telemetryCallback)(id, sample);
282 }
283 }
284
285 void JSRuntime::setTelemetryCallback(
286 JSRuntime* rt, JSAccumulateTelemetryDataCallback callback) {
287 rt->telemetryCallback = callback;
288 }
289
290 void JSRuntime::setUseCounter(JSObject* obj, JSUseCounter counter) {
291 if (useCounterCallback) {
292 // A use counter callback cannot GC.
293 JS::AutoSuppressGCAnalysis suppress;
294 (*useCounterCallback)(obj, counter);
295 }
296 }
297
298 void JSRuntime::setUseCounterCallback(JSRuntime* rt,
299 JSSetUseCounterCallback callback) {
300 rt->useCounterCallback = callback;
301 }
302
303 void JSRuntime::addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
304 JS::RuntimeSizes* rtSizes) {
305 rtSizes->object += mallocSizeOf(this);
306
307 rtSizes->atomsTable += atoms().sizeOfIncludingThis(mallocSizeOf);
308 rtSizes->gc.marker += gc.markers.sizeOfExcludingThis(mallocSizeOf);
309 for (auto& marker : gc.markers) {
310 rtSizes->gc.marker += marker->sizeOfIncludingThis(mallocSizeOf);
311 }
312
313 if (!parentRuntime) {
314 rtSizes->atomsTable += mallocSizeOf(staticStrings);
315 rtSizes->atomsTable += mallocSizeOf(commonNames);
316 rtSizes->atomsTable += permanentAtoms()->sizeOfIncludingThis(mallocSizeOf);
317
318 rtSizes->selfHostStencil =
319 selfHostStencilInput_->sizeOfIncludingThis(mallocSizeOf) +
320 selfHostStencil_->sizeOfIncludingThis(mallocSizeOf) +
321 selfHostScriptMap.ref().shallowSizeOfExcludingThis(mallocSizeOf);
322 }
323
324 JSContext* cx = mainContextFromAnyThread();
325 rtSizes->contexts += cx->sizeOfIncludingThis(mallocSizeOf);
326 rtSizes->temporary += cx->tempLifoAlloc().sizeOfExcludingThis(mallocSizeOf);
327 rtSizes->interpreterStack +=
328 cx->interpreterStack().sizeOfExcludingThis(mallocSizeOf);
329 rtSizes->uncompressedSourceCache +=
330 caches().uncompressedSourceCache.sizeOfExcludingThis(mallocSizeOf);
331
332 rtSizes->gc.nurseryCommitted += gc.nursery().totalCommitted();
333 rtSizes->gc.nurseryMallocedBuffers +=
334 gc.nursery().sizeOfMallocedBuffers(mallocSizeOf);
335 gc.storeBuffer().addSizeOfExcludingThis(mallocSizeOf, &rtSizes->gc);
336
337 rtSizes->gc.nurseryMallocedBlockCache +=
338 gc.nursery().sizeOfMallocedBlockCache(mallocSizeOf);
339 rtSizes->gc.nurseryTrailerBlockSets +=
340 gc.nursery().sizeOfTrailerBlockSets(mallocSizeOf);
341
342 if (isMainRuntime()) {
343 rtSizes->sharedImmutableStringsCache +=
344 js::SharedImmutableStringsCache::getSingleton().sizeOfExcludingThis(
345 mallocSizeOf);
346 rtSizes->atomsTable +=
347 js::frontend::WellKnownParserAtoms::getSingleton().sizeOfExcludingThis(
348 mallocSizeOf);
349 }
350
351 #ifdef JS_HAS_INTL_API
352 rtSizes->sharedIntlData +=
353 sharedIntlData.ref().sizeOfExcludingThis(mallocSizeOf);
354 #endif
355
356 {
357 auto& table = scriptDataTableHolder().getWithoutLock();
358
359 rtSizes->scriptData += table.shallowSizeOfExcludingThis(mallocSizeOf);
360 for (SharedImmutableScriptDataTable::Range r = table.all(); !r.empty();
361 r.popFront()) {
362 rtSizes->scriptData += r.front()->sizeOfIncludingThis(mallocSizeOf);
363 }
364 }
365
366 if (isMainRuntime()) {
367 AutoLockGlobalScriptData lock;
368
369 auto& table = js::globalSharedScriptDataTableHolder.get(lock);
370
371 rtSizes->scriptData += table.shallowSizeOfExcludingThis(mallocSizeOf);
372 for (SharedImmutableScriptDataTable::Range r = table.all(); !r.empty();
373 r.popFront()) {
374 rtSizes->scriptData += r.front()->sizeOfIncludingThis(mallocSizeOf);
375 }
376 }
377
378 if (jitRuntime_) {
379 // Sizes of the IonCompileTasks we are holding for lazy linking
380 for (auto* task : jitRuntime_->ionLazyLinkList(this)) {
381 rtSizes->jitLazyLink += task->sizeOfExcludingThis(mallocSizeOf);
382 }
383 }
384
385 rtSizes->wasmRuntime +=
386 wasmInstances.lock()->sizeOfExcludingThis(mallocSizeOf);
387 }
388
389 static bool InvokeInterruptCallbacks(JSContext* cx) {
390 bool stop = false;
391 for (JSInterruptCallback cb : cx->interruptCallbacks()) {
392 if (!cb(cx)) {
393 stop = true;
394 }
395 }
396 return stop;
397 }
398
399 static bool HandleInterrupt(JSContext* cx, bool invokeCallback) {
400 MOZ_ASSERT(!cx->zone()->isAtomsZone());
401
402 cx->runtime()->gc.gcIfRequested();
403
404 // A worker thread may have requested an interrupt after finishing an
405 // offthread compilation.
406 jit::AttachFinishedCompilations(cx);
407
408 // Don't call the interrupt callback if we only interrupted for GC or Ion.
409 if (!invokeCallback) {
410 return true;
411 }
412
413 // Important: Additional callbacks can occur inside the callback handler
414 // if it re-enters the JS engine. The embedding must ensure that the
415 // callback is disconnected before attempting such re-entry.
416 if (cx->interruptCallbackDisabled) {
417 return true;
418 }
419
420 bool stop;
421 #ifdef ENABLE_WASM_JSPI
422 if (IsSuspendableStackActive(cx)) {
423 stop = wasm::CallOnMainStack(
424 cx, reinterpret_cast<wasm::CallOnMainStackFn>(InvokeInterruptCallbacks),
425 (void*)cx);
426 } else
427 #endif
428 {
429 stop = InvokeInterruptCallbacks(cx);
430 }
431
432 if (!stop) {
433 // Debugger treats invoking the interrupt callback as a "step", so
434 // invoke the onStep handler.
435 if (cx->realm()->isDebuggee()) {
436 ScriptFrameIter iter(cx);
437 if (!iter.done() && cx->compartment() == iter.compartment() &&
438 DebugAPI::stepModeEnabled(iter.script())) {
439 if (!DebugAPI::onSingleStep(cx)) {
440 return false;
441 }
442 }
443 }
444
445 return true;
446 }
447
448 // No need to set aside any pending exception here: ComputeStackString
449 // already does that.
450 JSString* stack = ComputeStackString(cx);
451
452 UniqueTwoByteChars stringChars;
453 if (stack) {
454 stringChars = JS_CopyStringCharsZ(cx, stack);
455 if (!stringChars) {
456 cx->recoverFromOutOfMemory();
457 }
458 }
459
460 const char16_t* chars;
461 if (stringChars) {
462 chars = stringChars.get();
463 } else {
464 chars = u"(stack not available)";
465 }
466 WarnNumberUC(cx, JSMSG_TERMINATED, chars);
467 cx->reportUncatchableException();
468 return false;
469 }
470
471 void JSContext::requestInterrupt(InterruptReason reason) {
472 interruptBits_ |= uint32_t(reason);
473 jitStackLimit = JS::NativeStackLimitMin;
474
475 if (reason == InterruptReason::CallbackUrgent) {
476 // If this interrupt is urgent (slow script dialog for instance), take
477 // additional steps to interrupt corner cases where the above fields are
478 // not regularly polled.
479 FutexThread::lock();
480 if (fx.isWaiting()) {
481 fx.notify(FutexThread::NotifyForJSInterrupt);
482 }
483 fx.unlock();
484 }
485
486 if (reason == InterruptReason::CallbackUrgent ||
487 reason == InterruptReason::MajorGC ||
488 reason == InterruptReason::MinorGC) {
489 wasm::InterruptRunningCode(this);
490 }
491 }
492
493 bool JSContext::handleInterrupt() {
494 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime()));
495 if (hasAnyPendingInterrupt() || jitStackLimit == JS::NativeStackLimitMin) {
496 bool invokeCallback =
497 hasPendingInterrupt(InterruptReason::CallbackUrgent) ||
498 hasPendingInterrupt(InterruptReason::CallbackCanWait);
499 interruptBits_ = 0;
500 resetJitStackLimit();
501 return HandleInterrupt(this, invokeCallback);
502 }
503 return true;
504 }
505
506 void JSContext::clearPendingInterrupt(js::InterruptReason reason) {
507 // Interrupt bit have already been cleared.
508 interruptBits_ &= ~uint32_t(reason);
509 }
510
511 bool JSRuntime::setDefaultLocale(const char* locale) {
512 if (!locale) {
513 return false;
514 }
515
516 UniqueChars newLocale = DuplicateString(mainContextFromOwnThread(), locale);
517 if (!newLocale) {
518 return false;
519 }
520
521 defaultLocale.ref() = std::move(newLocale);
522 return true;
523 }
524
525 void JSRuntime::resetDefaultLocale() { defaultLocale = nullptr; }
526
527 const char* JSRuntime::getDefaultLocale() {
528 if (defaultLocale.ref()) {
529 return defaultLocale.ref().get();
530 }
531
532 // Use ICU if available to retrieve the default locale, this ensures ICU's
533 // default locale matches our default locale.
534 #if JS_HAS_INTL_API
535 const char* locale = mozilla::intl::Locale::GetDefaultLocale();
536 #else
537 const char* locale = setlocale(LC_ALL, nullptr);
538 #endif
539
540 // convert to a well-formed BCP 47 language tag
541 if (!locale || !strcmp(locale, "C")) {
542 locale = "und";
543 }
544
545 UniqueChars lang = DuplicateString(mainContextFromOwnThread(), locale);
546 if (!lang) {
547 return nullptr;
548 }
549
550 char* p;
551 if ((p = strchr(lang.get(), '.'))) {
552 *p = '\0';
553 }
554 while ((p = strchr(lang.get(), '_'))) {
555 *p = '-';
556 }
557
558 defaultLocale.ref() = std::move(lang);
559 return defaultLocale.ref().get();
560 }
561
562 #ifdef JS_HAS_INTL_API
563 void JSRuntime::traceSharedIntlData(JSTracer* trc) {
564 sharedIntlData.ref().trace(trc);
565 }
566 #endif
567
568 SharedScriptDataTableHolder& JSRuntime::scriptDataTableHolder() {
569 return scriptDataTableHolder_;
570 }
571
572 bool JSRuntime::getHostDefinedData(JSContext* cx,
573 JS::MutableHandle<JSObject*> data) const {
574 MOZ_ASSERT(cx->jobQueue);
575
576 return cx->jobQueue->getHostDefinedData(cx, data);
577 }
578
579 bool JSRuntime::enqueuePromiseJob(JSContext* cx, HandleFunction job,
580 HandleObject promise,
581 HandleObject hostDefinedData) {
582 MOZ_ASSERT(cx->jobQueue,
583 "Must select a JobQueue implementation using JS::JobQueue "
584 "or js::UseInternalJobQueues before using Promises");
585
586 RootedObject allocationSite(cx);
587 if (promise) {
588 #ifdef DEBUG
589 AssertSameCompartment(job, promise);
590 #endif
591
592 RootedObject unwrappedPromise(cx, promise);
593 // While the job object is guaranteed to be unwrapped, the promise
594 // might be wrapped. See the comments in EnqueuePromiseReactionJob in
595 // builtin/Promise.cpp for details.
596 if (IsWrapper(promise)) {
597 unwrappedPromise = UncheckedUnwrap(promise);
598 }
599 if (unwrappedPromise->is<PromiseObject>()) {
600 allocationSite = JS::GetPromiseAllocationSite(unwrappedPromise);
601 }
602 }
603 return cx->jobQueue->enqueuePromiseJob(cx, promise, job, allocationSite,
604 hostDefinedData);
605 }
606
607 void JSRuntime::addUnhandledRejectedPromise(JSContext* cx,
608 js::HandleObject promise) {
609 MOZ_ASSERT(promise->is<PromiseObject>());
610 if (!cx->promiseRejectionTrackerCallback) {
611 return;
612 }
613
614 bool mutedErrors = false;
615 if (JSScript* script = cx->currentScript()) {
616 mutedErrors = script->mutedErrors();
617 }
618
619 void* data = cx->promiseRejectionTrackerCallbackData;
620 cx->promiseRejectionTrackerCallback(
621 cx, mutedErrors, promise, JS::PromiseRejectionHandlingState::Unhandled,
622 data);
623 }
624
625 void JSRuntime::removeUnhandledRejectedPromise(JSContext* cx,
626 js::HandleObject promise) {
627 MOZ_ASSERT(promise->is<PromiseObject>());
628 if (!cx->promiseRejectionTrackerCallback) {
629 return;
630 }
631
632 bool mutedErrors = false;
633 if (JSScript* script = cx->currentScript()) {
634 mutedErrors = script->mutedErrors();
635 }
636
637 void* data = cx->promiseRejectionTrackerCallbackData;
638 cx->promiseRejectionTrackerCallback(
639 cx, mutedErrors, promise, JS::PromiseRejectionHandlingState::Handled,
640 data);
641 }
642
643 mozilla::non_crypto::XorShift128PlusRNG& JSRuntime::randomKeyGenerator() {
644 MOZ_ASSERT(CurrentThreadCanAccessRuntime(this));
645 if (randomKeyGenerator_.isNothing()) {
646 mozilla::Array<uint64_t, 2> seed;
647 GenerateXorShift128PlusSeed(seed);
648 randomKeyGenerator_.emplace(seed[0], seed[1]);
649 }
650 return randomKeyGenerator_.ref();
651 }
652
653 mozilla::HashCodeScrambler JSRuntime::randomHashCodeScrambler() {
654 auto& rng = randomKeyGenerator();
655 return mozilla::HashCodeScrambler(rng.next(), rng.next());
656 }
657
658 mozilla::non_crypto::XorShift128PlusRNG JSRuntime::forkRandomKeyGenerator() {
659 auto& rng = randomKeyGenerator();
660 return mozilla::non_crypto::XorShift128PlusRNG(rng.next(), rng.next());
661 }
662
663 js::HashNumber JSRuntime::randomHashCode() {
664 MOZ_ASSERT(CurrentThreadCanAccessRuntime(this));
665
666 if (randomHashCodeGenerator_.isNothing()) {
667 mozilla::Array<uint64_t, 2> seed;
668 GenerateXorShift128PlusSeed(seed);
669 randomHashCodeGenerator_.emplace(seed[0], seed[1]);
670 }
671
672 return HashNumber(randomHashCodeGenerator_->next());
673 }
674
675 JS_PUBLIC_API void* JSRuntime::onOutOfMemory(AllocFunction allocFunc,
676 arena_id_t arena, size_t nbytes,
677 void* reallocPtr,
678 JSContext* maybecx) {
679 MOZ_ASSERT_IF(allocFunc != AllocFunction::Realloc, !reallocPtr);
680
681 if (JS::RuntimeHeapIsBusy()) {
682 return nullptr;
683 }
684
685 if (!oom::IsSimulatedOOMAllocation()) {
686 /*
687 * Retry when we are done with the background sweeping and have stopped
688 * all the allocations and released the empty GC chunks.
689 */
690 gc.onOutOfMallocMemory();
691 void* p;
692 switch (allocFunc) {
693 case AllocFunction::Malloc:
694 p = js_arena_malloc(arena, nbytes);
695 break;
696 case AllocFunction::Calloc:
697 p = js_arena_calloc(arena, nbytes, 1);
698 break;
699 case AllocFunction::Realloc:
700 p = js_arena_realloc(arena, reallocPtr, nbytes);
701 break;
702 default:
703 MOZ_CRASH();
704 }
705 if (p) {
706 return p;
707 }
708 }
709
710 if (maybecx) {
711 ReportOutOfMemory(maybecx);
712 }
713 return nullptr;
714 }
715
716 void* JSRuntime::onOutOfMemoryCanGC(AllocFunction allocFunc, arena_id_t arena,
717 size_t bytes, void* reallocPtr) {
718 if (OnLargeAllocationFailure && bytes >= LARGE_ALLOCATION) {
719 OnLargeAllocationFailure();
720 }
721 return onOutOfMemory(allocFunc, arena, bytes, reallocPtr);
722 }
723
724 bool JSRuntime::activeGCInAtomsZone() {
725 Zone* zone = unsafeAtomsZone();
726 return (zone->needsIncrementalBarrier() &&
727 !gc.isVerifyPreBarriersEnabled()) ||
728 zone->wasGCStarted();
729 }
730
731 void JSRuntime::incrementNumDebuggeeRealms() {
732 if (numDebuggeeRealms_ == 0) {
733 jitRuntime()->baselineInterpreter().toggleDebuggerInstrumentation(true);
734 }
735
736 numDebuggeeRealms_++;
737 MOZ_ASSERT(numDebuggeeRealms_ <= numRealms);
738 }
739
740 void JSRuntime::decrementNumDebuggeeRealms() {
741 MOZ_ASSERT(numDebuggeeRealms_ > 0);
742 numDebuggeeRealms_--;
743
744 // Note: if we had shutdown leaks we can end up here while destroying the
745 // runtime. It's not safe to access JitRuntime trampolines because they're no
746 // longer traced.
747 if (numDebuggeeRealms_ == 0 && !isBeingDestroyed()) {
748 jitRuntime()->baselineInterpreter().toggleDebuggerInstrumentation(false);
749 }
750 }
751
752 void JSRuntime::incrementNumDebuggeeRealmsObservingCoverage() {
753 if (numDebuggeeRealmsObservingCoverage_ == 0) {
754 jit::BaselineInterpreter& interp = jitRuntime()->baselineInterpreter();
755 interp.toggleCodeCoverageInstrumentation(true);
756 }
757
758 numDebuggeeRealmsObservingCoverage_++;
759 MOZ_ASSERT(numDebuggeeRealmsObservingCoverage_ <= numRealms);
760 }
761
762 void JSRuntime::decrementNumDebuggeeRealmsObservingCoverage() {
763 MOZ_ASSERT(numDebuggeeRealmsObservingCoverage_ > 0);
764 numDebuggeeRealmsObservingCoverage_--;
765
766 // Note: if we had shutdown leaks we can end up here while destroying the
767 // runtime. It's not safe to access JitRuntime trampolines because they're no
768 // longer traced.
769 if (numDebuggeeRealmsObservingCoverage_ == 0 && !isBeingDestroyed()) {
770 jit::BaselineInterpreter& interp = jitRuntime()->baselineInterpreter();
771 interp.toggleCodeCoverageInstrumentation(false);
772 }
773 }
774
775 bool js::CurrentThreadCanAccessRuntime(const JSRuntime* rt) {
776 return rt->mainContextFromAnyThread() == TlsContext.get();
777 }
778
779 bool js::CurrentThreadCanAccessZone(Zone* zone) {
780 return CurrentThreadCanAccessRuntime(zone->runtime_);
781 }
782
783 #ifdef DEBUG
784 bool js::CurrentThreadIsMainThread() { return !!TlsContext.get(); }
785 #endif
786
787 JS_PUBLIC_API void JS::SetJSContextProfilerSampleBufferRangeStart(
788 JSContext* cx, uint64_t rangeStart) {
789 cx->runtime()->setProfilerSampleBufferRangeStart(rangeStart);
790 }
791
792 JS_PUBLIC_API bool JS::IsProfilingEnabledForContext(JSContext* cx) {
793 MOZ_ASSERT(cx);
794 return cx->runtime()->geckoProfiler().enabled();
795 }
796
797 JS_PUBLIC_API void JS::EnableRecordingAllocations(
798 JSContext* cx, JS::RecordAllocationsCallback callback, double probability) {
799 MOZ_ASSERT(cx);
800 cx->runtime()->startRecordingAllocations(probability, callback);
801 }
802
803 JS_PUBLIC_API void JS::DisableRecordingAllocations(JSContext* cx) {
804 MOZ_ASSERT(cx);
805 cx->runtime()->stopRecordingAllocations();
806 }
807
808 JS_PUBLIC_API void JS::shadow::RegisterWeakCache(
809 JSRuntime* rt, detail::WeakCacheBase* cachep) {
810 rt->registerWeakCache(cachep);
811 }
812
813 void JSRuntime::startRecordingAllocations(
814 double probability, JS::RecordAllocationsCallback callback) {
815 allocationSamplingProbability = probability;
816 recordAllocationCallback = callback;
817
818 // Go through all of the existing realms, and turn on allocation tracking.
819 for (RealmsIter realm(this); !realm.done(); realm.next()) {
820 realm->setAllocationMetadataBuilder(&SavedStacks::metadataBuilder);
821 realm->chooseAllocationSamplingProbability();
822 }
823 }
824
825 void JSRuntime::stopRecordingAllocations() {
826 recordAllocationCallback = nullptr;
827 // Go through all of the existing realms, and turn on allocation tracking.
828 for (RealmsIter realm(this); !realm.done(); realm.next()) {
829 js::GlobalObject* global = realm->maybeGlobal();
830 if (!realm->isDebuggee() || !global ||
831 !DebugAPI::isObservedByDebuggerTrackingAllocations(*global)) {
832 // Only remove the allocation metadata builder if no Debuggers are
833 // tracking allocations.
834 realm->forgetAllocationMetadataBuilder();
835 }
836 }
837 }
838
839 // This function can run to ensure that when new realms are created
840 // they have allocation logging turned on.
841 void JSRuntime::ensureRealmIsRecordingAllocations(
842 Handle<GlobalObject*> global) {
843 if (recordAllocationCallback) {
844 if (!global->realm()->isRecordingAllocations()) {
845 // This is a new realm, turn on allocations for it.
846 global->realm()->setAllocationMetadataBuilder(
847 &SavedStacks::metadataBuilder);
848 }
849 // Ensure the probability is up to date with the current combination of
850 // debuggers and runtime profiling.
851 global->realm()->chooseAllocationSamplingProbability();
852 }
853 }
854
855 void js::HasSeenObjectEmulateUndefinedFuse::popFuse(JSContext* cx) {
856 js::InvalidatingRuntimeFuse::popFuse(cx);
857 MOZ_ASSERT(cx->global());
858 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::ISHTMLDDA_FUSE);
859 }
860
861 void js::HasSeenArrayExceedsInt32LengthFuse::popFuse(JSContext* cx) {
862 if (intact()) {
863 js::InvalidatingRuntimeFuse::popFuse(cx);
864 }
865 }