Debian Codegraph @

js/src/builtin/TestingFunctions.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 "builtin/TestingFunctions.h"
8
9 #include "mozilla/Atomics.h"
10 #include "mozilla/Casting.h"
11 #include "mozilla/FloatingPoint.h"
12 #ifdef JS_HAS_INTL_API
13 # include "mozilla/intl/ICU4CLibrary.h"
14 # include "mozilla/intl/Locale.h"
15 # include "mozilla/intl/String.h"
16 # include "mozilla/intl/TimeZone.h"
17 #endif
18 #include "mozilla/Maybe.h"
19 #include "mozilla/RefPtr.h"
20 #include "mozilla/ScopeExit.h"
21 #include "mozilla/Span.h"
22 #include "mozilla/Sprintf.h"
23 #include "mozilla/StringBuffer.h"
24 #include "mozilla/TextUtils.h"
25 #include "mozilla/ThreadLocal.h"
26
27 #include <algorithm>
28 #include <cfloat>
29 #include <cinttypes>
30 #include <cmath>
31 #include <cstdlib>
32 #include <ctime>
33 #include <functional>
34 #include <initializer_list>
35 #include <iterator>
36 #include <utility>
37
38 #if defined(XP_UNIX) && !defined(XP_DARWIN)
39 # include <time.h>
40 #else
41 # include <chrono>
42 #endif
43
44 #include "fdlibm.h"
45 #include "jsapi.h"
46 #include "jsfriendapi.h"
47
48 #ifdef JS_HAS_INTL_API
49 # include "builtin/intl/CommonFunctions.h"
50 # include "builtin/intl/FormatBuffer.h"
51 # include "builtin/intl/SharedIntlData.h"
52 #endif
53 #include "builtin/BigInt.h"
54 #include "builtin/JSON.h"
55 #include "builtin/MapObject.h"
56 #include "builtin/Promise.h"
57 #include "builtin/TestingUtility.h" // js::ParseCompileOptions, js::ParseDebugMetadata
58 #include "ds/IdValuePair.h" // js::IdValuePair
59 #include "frontend/CompilationStencil.h" // frontend::CompilationStencil
60 #include "frontend/FrontendContext.h" // AutoReportFrontendContext
61 #include "gc/GC.h"
62 #include "gc/GCEnum.h"
63 #include "gc/GCLock.h"
64 #include "gc/Zone.h"
65 #include "jit/BaselineJIT.h"
66 #include "jit/CacheIRSpewer.h"
67 #include "jit/Disassemble.h"
68 #include "jit/FlushICache.h"
69 #include "jit/InlinableNatives.h"
70 #include "jit/Invalidation.h"
71 #include "jit/Ion.h"
72 #include "jit/JitOptions.h"
73 #include "jit/JitRuntime.h"
74 #include "jit/JitScript.h"
75 #include "jit/TrialInlining.h"
76 #include "js/Array.h" // JS::NewArrayObject
77 #include "js/ArrayBuffer.h" // JS::{DetachArrayBuffer,GetArrayBufferLengthAndData,NewArrayBufferWithContents}
78 #include "js/CallAndConstruct.h" // JS::Call, JS::IsCallable, JS::IsConstructor, JS_CallFunction
79 #include "js/CharacterEncoding.h"
80 #include "js/CompilationAndEvaluation.h"
81 #include "js/CompileOptions.h" // JS::CompileOptions, JS::DecodeOptions, JS::InstantiateOptions
82 #include "js/Conversions.h"
83 #include "js/Date.h"
84 #include "js/experimental/CodeCoverage.h" // js::GetCodeCoverageSummary
85 #include "js/experimental/CompileScript.h" // JS::CompileGlobalScriptToStencil, JS::CompileModuleScriptToStencil, JS::PrepareForInstantiate
86 #include "js/experimental/JSStencil.h" // JS::Stencil, JS::EncodeStencil, JS::DecodeStencil, JS::InstantiateGlobalStencil
87 #include "js/experimental/PCCountProfiling.h" // JS::{Start,Stop}PCCountProfiling, JS::PurgePCCounts, JS::GetPCCountScript{Count,Summary,Contents}
88 #include "js/experimental/TypedData.h" // JS_GetObjectAsUint8Array
89 #include "js/friend/DumpFunctions.h" // js::Dump{Backtrace,Heap,Object}, JS::FormatStackDump, js::IgnoreNurseryObjects
90 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
91 #include "js/friend/WindowProxy.h" // js::ToWindowProxyIfWindow
92 #include "js/GlobalObject.h"
93 #include "js/HashTable.h"
94 #include "js/Interrupt.h"
95 #include "js/LocaleSensitive.h"
96 #include "js/Prefs.h"
97 #include "js/Printf.h"
98 #include "js/PropertyAndElement.h" // JS_DefineProperties, JS_DefineProperty, JS_DefinePropertyById, JS_Enumerate, JS_GetProperty, JS_GetPropertyById, JS_HasProperty, JS_SetElement, JS_SetProperty
99 #include "js/PropertySpec.h"
100 #include "js/SourceText.h"
101 #include "js/StableStringChars.h"
102 #include "js/Stack.h"
103 #include "js/String.h" // JS::GetLinearStringLength, JS::StringToLinearString
104 #include "js/StructuredClone.h"
105 #include "js/Transcoding.h" // JS::TranscodeResult, JS::TranscodeRange, JS::TranscodeBuffer, JS::IsTranscodeFailureResult
106 #include "js/UbiNode.h"
107 #include "js/UbiNodeBreadthFirst.h"
108 #include "js/UbiNodeShortestPaths.h"
109 #include "js/UniquePtr.h"
110 #include "js/Vector.h"
111 #include "js/Wrapper.h"
112 #include "threading/CpuCount.h"
113 #include "util/DifferentialTesting.h"
114 #include "util/StringBuilder.h"
115 #include "util/Text.h"
116 #include "vm/BooleanObject.h"
117 #include "vm/DateObject.h"
118 #include "vm/DateTime.h"
119 #include "vm/ErrorObject.h"
120 #include "vm/GlobalObject.h"
121 #include "vm/HelperThreads.h"
122 #include "vm/HelperThreadState.h"
123 #include "vm/Interpreter.h"
124 #include "vm/JSContext.h"
125 #include "vm/JSObject.h"
126 #include "vm/NumberObject.h"
127 #include "vm/PlainObject.h" // js::PlainObject
128 #include "vm/PromiseObject.h" // js::PromiseObject, js::PromiseSlot_*
129 #include "vm/ProxyObject.h"
130 #include "vm/RealmFuses.h"
131 #include "vm/SavedStacks.h"
132 #include "vm/ScopeKind.h"
133 #include "vm/Stack.h"
134 #include "vm/StencilObject.h" // StencilObject, StencilXDRBufferObject
135 #include "vm/StringObject.h"
136 #include "vm/StringType.h"
137 #include "wasm/AsmJS.h"
138 #include "wasm/WasmBaselineCompile.h"
139 #include "wasm/WasmBuiltinModule.h"
140 #include "wasm/WasmDump.h"
141 #include "wasm/WasmFeatures.h"
142 #include "wasm/WasmGcObject.h"
143 #include "wasm/WasmInstance.h"
144 #include "wasm/WasmIonCompile.h"
145 #include "wasm/WasmJS.h"
146 #include "wasm/WasmModule.h"
147 #include "wasm/WasmValType.h"
148 #include "wasm/WasmValue.h"
149
150 #include "debugger/DebugAPI-inl.h"
151 #include "vm/Compartment-inl.h"
152 #include "vm/EnvironmentObject-inl.h"
153 #include "vm/JSContext-inl.h"
154 #include "vm/JSObject-inl.h"
155 #include "vm/NativeObject-inl.h"
156 #include "vm/ObjectFlags-inl.h"
157 #include "vm/StringType-inl.h"
158 #include "wasm/WasmInstance-inl.h"
159
160 using namespace js;
161
162 using mozilla::AssertedCast;
163 using mozilla::AsWritableChars;
164 using mozilla::Maybe;
165 using mozilla::Span;
166
167 using JS::AutoStableStringChars;
168 using JS::CompileOptions;
169 using JS::SliceBudget;
170 using JS::SourceText;
171 using JS::WorkBudget;
172
173 // If fuzzingSafe is set, remove functionality that could cause problems with
174 // fuzzers. Set this via the environment variable MOZ_FUZZING_SAFE.
175 mozilla::Atomic<bool> js::fuzzingSafe(false);
176
177 // If disableOOMFunctions is set, disable functionality that causes artificial
178 // OOM conditions.
179 static mozilla::Atomic<bool> disableOOMFunctions(false);
180
181 static bool EnvVarIsDefined(const char* name) {
182 const char* value = getenv(name);
183 return value && *value;
184 }
185
186 #if defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
187 static bool EnvVarAsInt(const char* name, int* valueOut) {
188 if (!EnvVarIsDefined(name)) {
189 return false;
190 }
191
192 *valueOut = atoi(getenv(name));
193 return true;
194 }
195 #endif
196
197 static bool GetRealmConfiguration(JSContext* cx, unsigned argc, Value* vp) {
198 CallArgs args = CallArgsFromVp(argc, vp);
199 RootedObject callee(cx, &args.callee());
200 RootedObject info(cx, JS_NewPlainObject(cx));
201 if (!info) {
202 return false;
203 }
204 if (args.length() > 1) {
205 ReportUsageErrorASCII(cx, callee, "Must have zero or one arguments");
206 return false;
207 }
208 if (args.length() == 1 && !args[0].isString()) {
209 ReportUsageErrorASCII(cx, callee, "Argument must be a string");
210 return false;
211 }
212
213 bool importAttributes = cx->options().importAttributes();
214 if (!JS_SetProperty(cx, info, "importAttributes",
215 importAttributes ? TrueHandleValue : FalseHandleValue)) {
216 return false;
217 }
218
219 if (args.length() == 1) {
220 RootedString str(cx, ToString(cx, args[0]));
221 if (!str) {
222 return false;
223 }
224 RootedId id(cx);
225 if (!JS_StringToId(cx, str, &id)) {
226 return false;
227 }
228
229 bool hasProperty;
230 if (JS_HasPropertyById(cx, info, id, &hasProperty) && hasProperty) {
231 // Returning a true/false from GetProperty
232 return GetProperty(cx, info, info, id, args.rval());
233 }
234
235 ReportUsageErrorASCII(cx, callee, "Invalid option name");
236 return false;
237 }
238
239 args.rval().setObject(*info);
240 return true;
241 }
242
243 static bool GetBuildConfiguration(JSContext* cx, unsigned argc, Value* vp) {
244 CallArgs args = CallArgsFromVp(argc, vp);
245 RootedObject callee(cx, &args.callee());
246 RootedObject info(cx, JS_NewPlainObject(cx));
247 if (!info) {
248 return false;
249 }
250 if (args.length() > 1) {
251 ReportUsageErrorASCII(cx, callee, "Must have zero or one arguments");
252 return false;
253 }
254 if (args.length() == 1 && !args[0].isString()) {
255 ReportUsageErrorASCII(cx, callee, "Argument must be a string");
256 return false;
257 }
258
259 if (!JS_SetProperty(cx, info, "rooting-analysis", FalseHandleValue)) {
260 return false;
261 }
262
263 if (!JS_SetProperty(cx, info, "exact-rooting", TrueHandleValue)) {
264 return false;
265 }
266
267 if (!JS_SetProperty(cx, info, "trace-jscalls-api", FalseHandleValue)) {
268 return false;
269 }
270
271 if (!JS_SetProperty(cx, info, "incremental-gc", TrueHandleValue)) {
272 return false;
273 }
274
275 if (!JS_SetProperty(cx, info, "generational-gc", TrueHandleValue)) {
276 return false;
277 }
278
279 if (!JS_SetProperty(cx, info, "oom-backtraces", FalseHandleValue)) {
280 return false;
281 }
282
283 RootedValue value(cx);
284 #ifdef DEBUG
285 value = BooleanValue(true);
286 #else
287 value = BooleanValue(false);
288 #endif
289 if (!JS_SetProperty(cx, info, "debug", value)) {
290 return false;
291 }
292
293 #ifdef RELEASE_OR_BETA
294 value = BooleanValue(true);
295 #else
296 value = BooleanValue(false);
297 #endif
298 if (!JS_SetProperty(cx, info, "release_or_beta", value)) {
299 return false;
300 }
301
302 #ifdef EARLY_BETA_OR_EARLIER
303 value = BooleanValue(true);
304 #else
305 value = BooleanValue(false);
306 #endif
307 if (!JS_SetProperty(cx, info, "early_beta_or_earlier", value)) {
308 return false;
309 }
310
311 #ifdef MOZ_CODE_COVERAGE
312 value = BooleanValue(true);
313 #else
314 value = BooleanValue(false);
315 #endif
316 if (!JS_SetProperty(cx, info, "coverage", value)) {
317 return false;
318 }
319
320 #ifdef JS_HAS_CTYPES
321 value = BooleanValue(true);
322 #else
323 value = BooleanValue(false);
324 #endif
325 if (!JS_SetProperty(cx, info, "has-ctypes", value)) {
326 return false;
327 }
328
329 #if defined(_M_IX86) || defined(__i386__)
330 value = BooleanValue(true);
331 #else
332 value = BooleanValue(false);
333 #endif
334 if (!JS_SetProperty(cx, info, "x86", value)) {
335 return false;
336 }
337
338 #if defined(_M_X64) || defined(__x86_64__)
339 value = BooleanValue(true);
340 #else
341 value = BooleanValue(false);
342 #endif
343 if (!JS_SetProperty(cx, info, "x64", value)) {
344 return false;
345 }
346
347 #ifdef JS_CODEGEN_ARM
348 value = BooleanValue(true);
349 #else
350 value = BooleanValue(false);
351 #endif
352 if (!JS_SetProperty(cx, info, "arm", value)) {
353 return false;
354 }
355
356 #ifdef JS_SIMULATOR_ARM
357 value = BooleanValue(true);
358 #else
359 value = BooleanValue(false);
360 #endif
361 if (!JS_SetProperty(cx, info, "arm-simulator", value)) {
362 return false;
363 }
364
365 #ifdef ANDROID
366 value = BooleanValue(true);
367 #else
368 value = BooleanValue(false);
369 #endif
370 if (!JS_SetProperty(cx, info, "android", value)) {
371 return false;
372 }
373
374 #ifdef XP_WIN
375 value = BooleanValue(true);
376 #else
377 value = BooleanValue(false);
378 #endif
379 if (!JS_SetProperty(cx, info, "windows", value)) {
380 return false;
381 }
382
383 #ifdef XP_MACOSX
384 value = BooleanValue(true);
385 #else
386 value = BooleanValue(false);
387 #endif
388 if (!JS_SetProperty(cx, info, "osx", value)) {
389 return false;
390 }
391
392 #ifdef JS_CODEGEN_ARM64
393 value = BooleanValue(true);
394 #else
395 value = BooleanValue(false);
396 #endif
397 if (!JS_SetProperty(cx, info, "arm64", value)) {
398 return false;
399 }
400
401 #ifdef JS_SIMULATOR_ARM64
402 value = BooleanValue(true);
403 #else
404 value = BooleanValue(false);
405 #endif
406 if (!JS_SetProperty(cx, info, "arm64-simulator", value)) {
407 return false;
408 }
409
410 #ifdef JS_CODEGEN_MIPS64
411 value = BooleanValue(true);
412 #else
413 value = BooleanValue(false);
414 #endif
415 if (!JS_SetProperty(cx, info, "mips64", value)) {
416 return false;
417 }
418
419 #ifdef JS_SIMULATOR_MIPS64
420 value = BooleanValue(true);
421 #else
422 value = BooleanValue(false);
423 #endif
424 if (!JS_SetProperty(cx, info, "mips64-simulator", value)) {
425 return false;
426 }
427
428 #ifdef JS_SIMULATOR
429 value = BooleanValue(true);
430 #else
431 value = BooleanValue(false);
432 #endif
433 if (!JS_SetProperty(cx, info, "simulator", value)) {
434 return false;
435 }
436
437 #ifdef __wasi__
438 value = BooleanValue(true);
439 #else
440 value = BooleanValue(false);
441 #endif
442 if (!JS_SetProperty(cx, info, "wasi", value)) {
443 return false;
444 }
445
446 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
447 value = BooleanValue(true);
448 #else
449 value = BooleanValue(false);
450 #endif
451 if (!JS_SetProperty(cx, info, "pbl", value)) {
452 return false;
453 }
454
455 #ifdef JS_CODEGEN_LOONG64
456 value = BooleanValue(true);
457 #else
458 value = BooleanValue(false);
459 #endif
460 if (!JS_SetProperty(cx, info, "loong64", value)) {
461 return false;
462 }
463
464 #ifdef JS_SIMULATOR_LOONG64
465 value = BooleanValue(true);
466 #else
467 value = BooleanValue(false);
468 #endif
469 if (!JS_SetProperty(cx, info, "loong64-simulator", value)) {
470 return false;
471 }
472
473 #ifdef JS_CODEGEN_RISCV64
474 value = BooleanValue(true);
475 #else
476 value = BooleanValue(false);
477 #endif
478 if (!JS_SetProperty(cx, info, "riscv64", value)) {
479 return false;
480 }
481
482 #ifdef JS_SIMULATOR_RISCV64
483 value = BooleanValue(true);
484 #else
485 value = BooleanValue(false);
486 #endif
487 if (!JS_SetProperty(cx, info, "riscv64-simulator", value)) {
488 return false;
489 }
490
491 #ifdef MOZ_ASAN
492 value = BooleanValue(true);
493 #else
494 value = BooleanValue(false);
495 #endif
496 if (!JS_SetProperty(cx, info, "asan", value)) {
497 return false;
498 }
499
500 #ifdef MOZ_TSAN
501 value = BooleanValue(true);
502 #else
503 value = BooleanValue(false);
504 #endif
505 if (!JS_SetProperty(cx, info, "tsan", value)) {
506 return false;
507 }
508
509 #ifdef MOZ_UBSAN
510 value = BooleanValue(true);
511 #else
512 value = BooleanValue(false);
513 #endif
514 if (!JS_SetProperty(cx, info, "ubsan", value)) {
515 return false;
516 }
517
518 #ifdef JS_GC_ZEAL
519 value = BooleanValue(true);
520 #else
521 value = BooleanValue(false);
522 #endif
523 if (!JS_SetProperty(cx, info, "has-gczeal", value)) {
524 return false;
525 }
526
527 #ifdef MOZ_PROFILING
528 value = BooleanValue(true);
529 #else
530 value = BooleanValue(false);
531 #endif
532 if (!JS_SetProperty(cx, info, "profiling", value)) {
533 return false;
534 }
535
536 #ifdef INCLUDE_MOZILLA_DTRACE
537 value = BooleanValue(true);
538 #else
539 value = BooleanValue(false);
540 #endif
541 if (!JS_SetProperty(cx, info, "dtrace", value)) {
542 return false;
543 }
544
545 #ifdef MOZ_VALGRIND
546 value = BooleanValue(true);
547 #else
548 value = BooleanValue(false);
549 #endif
550 if (!JS_SetProperty(cx, info, "valgrind", value)) {
551 return false;
552 }
553
554 #ifdef JS_HAS_INTL_API
555 value = BooleanValue(true);
556 #else
557 value = BooleanValue(false);
558 #endif
559 if (!JS_SetProperty(cx, info, "intl-api", value)) {
560 return false;
561 }
562
563 #if defined(SOLARIS)
564 value = BooleanValue(false);
565 #else
566 value = BooleanValue(true);
567 #endif
568 if (!JS_SetProperty(cx, info, "mapped-array-buffer", value)) {
569 return false;
570 }
571
572 #ifdef MOZ_MEMORY
573 value = BooleanValue(true);
574 #else
575 value = BooleanValue(false);
576 #endif
577 if (!JS_SetProperty(cx, info, "moz-memory", value)) {
578 return false;
579 }
580
581 value.setInt32(sizeof(void*));
582 if (!JS_SetProperty(cx, info, "pointer-byte-size", value)) {
583 return false;
584 }
585
586 #ifdef ENABLE_DECORATORS
587 value = BooleanValue(true);
588 #else
589 value = BooleanValue(false);
590 #endif
591 if (!JS_SetProperty(cx, info, "decorators", value)) {
592 return false;
593 }
594
595 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
596 value = BooleanValue(true);
597 #else
598 value = BooleanValue(false);
599 #endif
600 if (!JS_SetProperty(cx, info, "explicit-resource-management", value)) {
601 return false;
602 }
603
604 #ifdef FUZZING
605 value = BooleanValue(true);
606 #else
607 value = BooleanValue(false);
608 #endif
609 if (!JS_SetProperty(cx, info, "fuzzing-defined", value)) {
610 return false;
611 }
612
613 #if (defined(__GNUC__) && defined(__SSE__) && defined(__x86_64__)) || \
614 defined(__arm__) || defined(__aarch64__)
615 // See js.cpp "disable-main-thread-denormals" command line option.
616 value = BooleanValue(true);
617 #else
618 value = BooleanValue(false);
619 #endif
620 if (!JS_SetProperty(cx, info, "can-disable-main-thread-denormals", value)) {
621 return false;
622 }
623
624 value = Int32Value(JSFatInlineString::MAX_LENGTH_LATIN1);
625 if (!JS_SetProperty(cx, info, "inline-latin1-chars", value)) {
626 return false;
627 }
628
629 value = Int32Value(JSFatInlineString::MAX_LENGTH_TWO_BYTE);
630 if (!JS_SetProperty(cx, info, "inline-two-byte-chars", value)) {
631 return false;
632 }
633
634 value = Int32Value(JSThinInlineString::MAX_LENGTH_LATIN1);
635 if (!JS_SetProperty(cx, info, "thin-inline-latin1-chars", value)) {
636 return false;
637 }
638
639 value = Int32Value(JSThinInlineString::MAX_LENGTH_TWO_BYTE);
640 if (!JS_SetProperty(cx, info, "thin-inline-two-byte-chars", value)) {
641 return false;
642 }
643
644 if (js::ThinInlineAtom::EverInstantiated) {
645 value = Int32Value(js::ThinInlineAtom::MAX_LENGTH_LATIN1);
646 if (!JS_SetProperty(cx, info, "thin-inline-atom-latin1-chars", value)) {
647 return false;
648 }
649
650 value = Int32Value(js::ThinInlineAtom::MAX_LENGTH_TWO_BYTE);
651 if (!JS_SetProperty(cx, info, "thin-inline-atom-two-byte-chars", value)) {
652 return false;
653 }
654 }
655
656 value = Int32Value(js::FatInlineAtom::MAX_LENGTH_LATIN1);
657 if (!JS_SetProperty(cx, info, "fat-inline-atom-latin1-chars", value)) {
658 return false;
659 }
660
661 value = Int32Value(js::FatInlineAtom::MAX_LENGTH_TWO_BYTE);
662 if (!JS_SetProperty(cx, info, "fat-inline-atom-two-byte-chars", value)) {
663 return false;
664 }
665
666 if (args.length() == 1) {
667 RootedString str(cx, ToString(cx, args[0]));
668 if (!str) {
669 return false;
670 }
671 RootedId id(cx);
672 if (!JS_StringToId(cx, str, &id)) {
673 return false;
674 }
675
676 bool hasProperty;
677 if (JS_HasPropertyById(cx, info, id, &hasProperty) && hasProperty) {
678 // Returning a true/false from GetProperty
679 return GetProperty(cx, info, info, id, args.rval());
680 }
681
682 ReportUsageErrorASCII(cx, callee, "Invalid option name");
683 return false;
684 }
685
686 args.rval().setObject(*info);
687 return true;
688 }
689
690 static bool IsLCovEnabled(JSContext* cx, unsigned argc, Value* vp) {
691 CallArgs args = CallArgsFromVp(argc, vp);
692 args.rval().setBoolean(coverage::IsLCovEnabled());
693 return true;
694 }
695
696 static bool TrialInline(JSContext* cx, unsigned argc, Value* vp) {
697 CallArgs args = CallArgsFromVp(argc, vp);
698 args.rval().setUndefined();
699
700 FrameIter iter(cx);
701 if (iter.done() || !iter.isBaseline() || iter.realm() != cx->realm()) {
702 return true;
703 }
704
705 jit::BaselineFrame* frame = iter.abstractFramePtr().asBaselineFrame();
706 if (!jit::CanIonCompileScript(cx, frame->script())) {
707 return true;
708 }
709
710 return jit::DoTrialInlining(cx, frame);
711 }
712
713 static bool ReturnStringCopy(JSContext* cx, CallArgs& args,
714 const char* message) {
715 JSString* str = JS_NewStringCopyZ(cx, message);
716 if (!str) {
717 return false;
718 }
719
720 args.rval().setString(str);
721 return true;
722 }
723
724 static bool MaybeGC(JSContext* cx, unsigned argc, Value* vp) {
725 CallArgs args = CallArgsFromVp(argc, vp);
726 JS_MaybeGC(cx);
727 args.rval().setUndefined();
728 return true;
729 }
730
731 static bool GC(JSContext* cx, unsigned argc, Value* vp) {
732 CallArgs args = CallArgsFromVp(argc, vp);
733
734 /*
735 * If the first argument is 'zone', we collect any zones previously
736 * scheduled for GC via schedulegc. If the first argument is an object, we
737 * collect the object's zone (and any other zones scheduled for
738 * GC). Otherwise, we collect all zones.
739 */
740 bool zone = false;
741 if (args.length() >= 1) {
742 Value arg = args[0];
743 if (arg.isString()) {
744 if (!JS_StringEqualsLiteral(cx, arg.toString(), "zone", &zone)) {
745 return false;
746 }
747 } else if (arg.isObject()) {
748 PrepareZoneForGC(cx, UncheckedUnwrap(&arg.toObject())->zone());
749 zone = true;
750 }
751 }
752
753 JS::GCOptions options = JS::GCOptions::Normal;
754 JS::GCReason reason = JS::GCReason::API;
755 if (args.length() >= 2) {
756 Value arg = args[1];
757 if (arg.isString()) {
758 bool shrinking = false;
759 bool last_ditch = false;
760 if (!JS_StringEqualsLiteral(cx, arg.toString(), "shrinking",
761 &shrinking)) {
762 return false;
763 }
764 if (!JS_StringEqualsLiteral(cx, arg.toString(), "last-ditch",
765 &last_ditch)) {
766 return false;
767 }
768 if (shrinking) {
769 options = JS::GCOptions::Shrink;
770 } else if (last_ditch) {
771 options = JS::GCOptions::Shrink;
772 reason = JS::GCReason::LAST_DITCH;
773 }
774 }
775 }
776
777 size_t preBytes = cx->runtime()->gc.heapSize.bytes();
778
779 if (zone) {
780 PrepareForDebugGC(cx->runtime());
781 } else {
782 JS::PrepareForFullGC(cx);
783 }
784
785 JS::NonIncrementalGC(cx, options, reason);
786
787 char buf[256] = {'\0'};
788 if (!js::SupportDifferentialTesting()) {
789 SprintfLiteral(buf, "before %zu, after %zu\n", preBytes,
790 cx->runtime()->gc.heapSize.bytes());
791 }
792 return ReturnStringCopy(cx, args, buf);
793 }
794
795 static bool MinorGC(JSContext* cx, unsigned argc, Value* vp) {
796 CallArgs args = CallArgsFromVp(argc, vp);
797 if (args.get(0) == BooleanValue(true)) {
798 gc::GCRuntime& gc = cx->runtime()->gc;
799 if (gc.nursery().isEnabled()) {
800 gc.storeBuffer().setAboutToOverflow(JS::GCReason::FULL_GENERIC_BUFFER);
801 }
802 }
803
804 cx->minorGC(JS::GCReason::API);
805 args.rval().setUndefined();
806 return true;
807 }
808
809 #define PARAM_NAME_LIST_ENTRY(name, key, writable) " " name
810 #define GC_PARAMETER_ARGS_LIST FOR_EACH_GC_PARAM(PARAM_NAME_LIST_ENTRY)
811
812 static bool GCParameter(JSContext* cx, unsigned argc, Value* vp) {
813 CallArgs args = CallArgsFromVp(argc, vp);
814
815 JSString* str = ToString(cx, args.get(0));
816 if (!str) {
817 return false;
818 }
819
820 UniqueChars name = EncodeLatin1(cx, str);
821 if (!name) {
822 return false;
823 }
824
825 JSGCParamKey param;
826 bool writable;
827 if (!GetGCParameterInfo(name.get(), &param, &writable)) {
828 JS_ReportErrorASCII(
829 cx, "the first argument must be one of:" GC_PARAMETER_ARGS_LIST);
830 return false;
831 }
832
833 // Request mode.
834 if (args.length() == 1) {
835 uint32_t value = JS_GetGCParameter(cx, param);
836 args.rval().setNumber(value);
837 return true;
838 }
839
840 if (!writable) {
841 JS_ReportErrorASCII(cx, "Attempt to change read-only parameter %s",
842 name.get());
843 return false;
844 }
845
846 if (fuzzingSafe) {
847 // Some Params are not yet fuzzing safe and so we silently skip
848 // changing said parameters.
849 switch (param) {
850 case JSGC_SEMISPACE_NURSERY_ENABLED:
851 args.rval().setUndefined();
852 return true;
853 default:
854 break;
855 }
856 }
857
858 if (disableOOMFunctions) {
859 switch (param) {
860 case JSGC_MAX_BYTES:
861 case JSGC_MAX_NURSERY_BYTES:
862 args.rval().setUndefined();
863 return true;
864 default:
865 break;
866 }
867 }
868
869 double d;
870 if (!ToNumber(cx, args[1], &d)) {
871 return false;
872 }
873
874 if (d < 0 || d > UINT32_MAX) {
875 JS_ReportErrorASCII(cx, "Parameter value out of range");
876 return false;
877 }
878
879 uint32_t value = floor(d);
880 bool ok = cx->runtime()->gc.setParameter(cx, param, value);
881 if (!ok) {
882 JS_ReportErrorASCII(cx, "Parameter value out of range");
883 return false;
884 }
885
886 args.rval().setUndefined();
887 return true;
888 }
889
890 static bool FinishBackgroundFree(JSContext* cx, unsigned argc, Value* vp) {
891 CallArgs args = CallArgsFromVp(argc, vp);
892 cx->runtime()->gc.waitBackgroundFreeEnd();
893 args.rval().setUndefined();
894 return true;
895 }
896
897 static bool RelazifyFunctions(JSContext* cx, unsigned argc, Value* vp) {
898 // Relazifying functions on GC is usually only done for compartments that are
899 // not active. To aid fuzzing, this testing function allows us to relazify
900 // even if the compartment is active.
901
902 CallArgs args = CallArgsFromVp(argc, vp);
903
904 // Disable relazification of all scripts on stack. It is a pervasive
905 // assumption in the engine that running scripts still have bytecode.
906 for (AllScriptFramesIter i(cx); !i.done(); ++i) {
907 i.script()->clearAllowRelazify();
908 }
909
910 cx->runtime()->allowRelazificationForTesting = true;
911
912 JS::PrepareForFullGC(cx);
913 JS::NonIncrementalGC(cx, JS::GCOptions::Shrink, JS::GCReason::API);
914
915 cx->runtime()->allowRelazificationForTesting = false;
916
917 args.rval().setUndefined();
918 return true;
919 }
920
921 static bool IsProxy(JSContext* cx, unsigned argc, Value* vp) {
922 CallArgs args = CallArgsFromVp(argc, vp);
923 if (args.length() != 1) {
924 JS_ReportErrorASCII(cx, "the function takes exactly one argument");
925 return false;
926 }
927 if (!args[0].isObject()) {
928 args.rval().setBoolean(false);
929 return true;
930 }
931 args.rval().setBoolean(args[0].toObject().is<ProxyObject>());
932 return true;
933 }
934
935 static bool WasmIsSupported(JSContext* cx, unsigned argc, Value* vp) {
936 CallArgs args = CallArgsFromVp(argc, vp);
937 args.rval().setBoolean(wasm::HasSupport(cx) &&
938 wasm::AnyCompilerAvailable(cx));
939 return true;
940 }
941
942 static bool WasmIsSupportedByHardware(JSContext* cx, unsigned argc, Value* vp) {
943 CallArgs args = CallArgsFromVp(argc, vp);
944 args.rval().setBoolean(wasm::HasPlatformSupport());
945 return true;
946 }
947
948 static bool WasmDebuggingEnabled(JSContext* cx, unsigned argc, Value* vp) {
949 CallArgs args = CallArgsFromVp(argc, vp);
950 args.rval().setBoolean(wasm::HasSupport(cx) && wasm::BaselineAvailable(cx));
951 return true;
952 }
953
954 static bool WasmStreamingEnabled(JSContext* cx, unsigned argc, Value* vp) {
955 CallArgs args = CallArgsFromVp(argc, vp);
956 args.rval().setBoolean(wasm::StreamingCompilationAvailable(cx));
957 return true;
958 }
959
960 static bool WasmCachingEnabled(JSContext* cx, unsigned argc, Value* vp) {
961 CallArgs args = CallArgsFromVp(argc, vp);
962 args.rval().setBoolean(wasm::CodeCachingAvailable(cx));
963 return true;
964 }
965
966 static bool WasmHugeMemorySupported(JSContext* cx, unsigned argc, Value* vp) {
967 CallArgs args = CallArgsFromVp(argc, vp);
968 #ifdef WASM_SUPPORTS_HUGE_MEMORY
969 args.rval().setBoolean(true);
970 #else
971 args.rval().setBoolean(false);
972 #endif
973 return true;
974 }
975
976 static bool WasmMaxMemoryPages(JSContext* cx, unsigned argc, Value* vp) {
977 CallArgs args = CallArgsFromVp(argc, vp);
978 if (args.length() < 1) {
979 JS_ReportErrorASCII(cx, "not enough arguments");
980 return false;
981 }
982 if (!args.get(0).isString()) {
983 JS_ReportErrorASCII(cx, "address type must be a string");
984 return false;
985 }
986 RootedString s(cx, args.get(0).toString());
987 Rooted<JSLinearString*> ls(cx, s->ensureLinear(cx));
988 if (!ls) {
989 return false;
990 }
991 if (StringEqualsLiteral(ls, "i32")) {
992 args.rval().setInt32(
993 int32_t(wasm::MaxMemoryPages(wasm::AddressType::I32).value()));
994 return true;
995 }
996 if (StringEqualsLiteral(ls, "i64")) {
997 #ifdef ENABLE_WASM_MEMORY64
998 if (wasm::Memory64Available(cx)) {
999 args.rval().setInt32(
1000 int32_t(wasm::MaxMemoryPages(wasm::AddressType::I64).value()));
1001 return true;
1002 }
1003 #endif
1004 JS_ReportErrorASCII(cx, "memory64 not enabled");
1005 return false;
1006 }
1007 JS_ReportErrorASCII(cx, "bad address type");
1008 return false;
1009 }
1010
1011 static bool WasmThreadsEnabled(JSContext* cx, unsigned argc, Value* vp) {
1012 CallArgs args = CallArgsFromVp(argc, vp);
1013 args.rval().setBoolean(wasm::ThreadsAvailable(cx));
1014 return true;
1015 }
1016
1017 #define WASM_FEATURE(NAME, ...) \
1018 static bool Wasm##NAME##Enabled(JSContext* cx, unsigned argc, Value* vp) { \
1019 CallArgs args = CallArgsFromVp(argc, vp); \
1020 args.rval().setBoolean(wasm::NAME##Available(cx)); \
1021 return true; \
1022 }
1023 JS_FOR_WASM_FEATURES(WASM_FEATURE);
1024 #undef WASM_FEATURE
1025
1026 static bool WasmSimdEnabled(JSContext* cx, unsigned argc, Value* vp) {
1027 CallArgs args = CallArgsFromVp(argc, vp);
1028 args.rval().setBoolean(wasm::SimdAvailable(cx));
1029 return true;
1030 }
1031
1032 static bool WasmCompilersPresent(JSContext* cx, unsigned argc, Value* vp) {
1033 CallArgs args = CallArgsFromVp(argc, vp);
1034
1035 char buf[256];
1036 *buf = 0;
1037 if (wasm::BaselinePlatformSupport()) {
1038 strcat(buf, "baseline");
1039 }
1040 if (wasm::IonPlatformSupport()) {
1041 if (*buf) {
1042 strcat(buf, ",");
1043 }
1044 strcat(buf, "ion");
1045 }
1046
1047 JSString* result = JS_NewStringCopyZ(cx, buf);
1048 if (!result) {
1049 return false;
1050 }
1051
1052 args.rval().setString(result);
1053 return true;
1054 }
1055
1056 static bool WasmCompileMode(JSContext* cx, unsigned argc, Value* vp) {
1057 CallArgs args = CallArgsFromVp(argc, vp);
1058
1059 // This triplet of predicates will select zero or one baseline compiler and
1060 // zero or one optimizing compiler.
1061 bool baseline = wasm::BaselineAvailable(cx);
1062 bool ion = wasm::IonAvailable(cx);
1063 bool none = !baseline && !ion;
1064 bool tiered = baseline && ion;
1065
1066 JSStringBuilder result(cx);
1067 if (none && !result.append("none")) {
1068 return false;
1069 }
1070 if (baseline && !result.append("baseline")) {
1071 return false;
1072 }
1073 if (tiered && !result.append("+")) {
1074 return false;
1075 }
1076 if (ion && !result.append("ion")) {
1077 return false;
1078 }
1079 if (JSString* str = result.finishString()) {
1080 args.rval().setString(str);
1081 return true;
1082 }
1083 return false;
1084 }
1085
1086 static bool WasmLazyTieringEnabled(JSContext* cx, unsigned argc, Value* vp) {
1087 // Note: ensure this function stays in sync with `PlatformCanTier()`.
1088 CallArgs args = CallArgsFromVp(argc, vp);
1089 bool baseline = wasm::BaselineAvailable(cx);
1090 bool ion = wasm::IonAvailable(cx);
1091
1092 bool enabled =
1093 baseline && ion && JS::Prefs::wasm_lazy_tiering() &&
1094 (JS::Prefs::wasm_lazy_tiering_synchronous() ||
1095 (CanUseExtraThreads() && jit::CanFlushExecutionContextForAllThreads()));
1096
1097 args.rval().setBoolean(enabled);
1098 return true;
1099 }
1100
1101 static bool WasmBaselineDisabledByFeatures(JSContext* cx, unsigned argc,
1102 Value* vp) {
1103 CallArgs args = CallArgsFromVp(argc, vp);
1104 bool isDisabled = false;
1105 JSStringBuilder reason(cx);
1106 if (!wasm::BaselineDisabledByFeatures(cx, &isDisabled, &reason)) {
1107 return false;
1108 }
1109 if (isDisabled) {
1110 JSString* result = reason.finishString();
1111 if (!result) {
1112 return false;
1113 }
1114 args.rval().setString(result);
1115 } else {
1116 args.rval().setBoolean(false);
1117 }
1118 return true;
1119 }
1120
1121 static bool WasmIonDisabledByFeatures(JSContext* cx, unsigned argc, Value* vp) {
1122 CallArgs args = CallArgsFromVp(argc, vp);
1123 bool isDisabled = false;
1124 JSStringBuilder reason(cx);
1125 if (!wasm::IonDisabledByFeatures(cx, &isDisabled, &reason)) {
1126 return false;
1127 }
1128 if (isDisabled) {
1129 JSString* result = reason.finishString();
1130 if (!result) {
1131 return false;
1132 }
1133 args.rval().setString(result);
1134 } else {
1135 args.rval().setBoolean(false);
1136 }
1137 return true;
1138 }
1139
1140 #ifdef ENABLE_WASM_SIMD
1141 # ifdef DEBUG
1142 static char lastAnalysisResult[1024];
1143
1144 namespace js {
1145 namespace wasm {
1146 void ReportSimdAnalysis(const char* data) {
1147 strncpy(lastAnalysisResult, data, sizeof(lastAnalysisResult));
1148 lastAnalysisResult[sizeof(lastAnalysisResult) - 1] = 0;
1149 }
1150 } // namespace wasm
1151 } // namespace js
1152
1153 // Unstable API for white-box testing of SIMD optimizations.
1154 //
1155 // Current API: takes no arguments, returns a string describing the last Simd
1156 // simplification applied.
1157
1158 static bool WasmSimdAnalysis(JSContext* cx, unsigned argc, Value* vp) {
1159 CallArgs args = CallArgsFromVp(argc, vp);
1160 JSString* result =
1161 JS_NewStringCopyZ(cx, *lastAnalysisResult ? lastAnalysisResult : "none");
1162 if (!result) {
1163 return false;
1164 }
1165 args.rval().setString(result);
1166 *lastAnalysisResult = (char)0;
1167 return true;
1168 }
1169 # endif
1170 #endif
1171
1172 static bool WasmGlobalFromArrayBuffer(JSContext* cx, unsigned argc, Value* vp) {
1173 if (!wasm::HasSupport(cx)) {
1174 JS_ReportErrorASCII(cx, "wasm support unavailable");
1175 return false;
1176 }
1177 CallArgs args = CallArgsFromVp(argc, vp);
1178
1179 if (args.length() < 2) {
1180 JS_ReportErrorASCII(cx, "not enough arguments");
1181 return false;
1182 }
1183
1184 // Get the type of the value
1185 wasm::ValType valType;
1186 if (!wasm::ToValType(cx, args.get(0), &valType)) {
1187 return false;
1188 }
1189
1190 // Get the array buffer for the value
1191 if (!args.get(1).isObject() ||
1192 !args.get(1).toObject().is<ArrayBufferObject>()) {
1193 JS_ReportErrorASCII(cx, "argument is not an array buffer");
1194 return false;
1195 }
1196 Rooted<ArrayBufferObject*> buffer(
1197 cx, &args.get(1).toObject().as<ArrayBufferObject>());
1198
1199 // Only allow POD to be created from bytes
1200 switch (valType.kind()) {
1201 case wasm::ValType::I32:
1202 case wasm::ValType::I64:
1203 case wasm::ValType::F32:
1204 case wasm::ValType::F64:
1205 case wasm::ValType::V128:
1206 break;
1207 default:
1208 JS_ReportErrorASCII(
1209 cx, "invalid valtype for creating WebAssembly.Global from bytes");
1210 return false;
1211 }
1212
1213 // Check we have all the bytes we need
1214 if (valType.size() != buffer->byteLength()) {
1215 JS_ReportErrorASCII(cx, "array buffer has incorrect size");
1216 return false;
1217 }
1218
1219 // Copy the bytes from buffer into a tagged val
1220 wasm::RootedVal val(cx);
1221 val.get().initFromRootedLocation(valType, buffer->dataPointer());
1222
1223 // Create the global object
1224 RootedObject proto(
1225 cx, GlobalObject::getOrCreatePrototype(cx, JSProto_WasmGlobal));
1226 if (!proto) {
1227 return false;
1228 }
1229 Rooted<WasmGlobalObject*> result(
1230 cx, WasmGlobalObject::create(cx, val, false, proto));
1231 if (!result) {
1232 return false;
1233 }
1234
1235 args.rval().setObject(*result.get());
1236 return true;
1237 }
1238
1239 enum class LaneInterp {
1240 I32x4,
1241 I64x2,
1242 F32x4,
1243 F64x2,
1244 };
1245
1246 size_t LaneInterpLanes(LaneInterp interp) {
1247 switch (interp) {
1248 case LaneInterp::I32x4:
1249 return 4;
1250 case LaneInterp::I64x2:
1251 return 2;
1252 case LaneInterp::F32x4:
1253 return 4;
1254 case LaneInterp::F64x2:
1255 return 2;
1256 default:
1257 MOZ_ASSERT_UNREACHABLE();
1258 return 0;
1259 }
1260 }
1261
1262 static bool ToLaneInterp(JSContext* cx, HandleValue v, LaneInterp* out) {
1263 RootedString interpStr(cx, ToString(cx, v));
1264 if (!interpStr) {
1265 return false;
1266 }
1267 Rooted<JSLinearString*> interpLinearStr(cx, interpStr->ensureLinear(cx));
1268 if (!interpLinearStr) {
1269 return false;
1270 }
1271
1272 if (StringEqualsLiteral(interpLinearStr, "i32x4")) {
1273 *out = LaneInterp::I32x4;
1274 return true;
1275 } else if (StringEqualsLiteral(interpLinearStr, "i64x2")) {
1276 *out = LaneInterp::I64x2;
1277 return true;
1278 } else if (StringEqualsLiteral(interpLinearStr, "f32x4")) {
1279 *out = LaneInterp::F32x4;
1280 return true;
1281 } else if (StringEqualsLiteral(interpLinearStr, "f64x2")) {
1282 *out = LaneInterp::F64x2;
1283 return true;
1284 }
1285
1286 JS_ReportErrorASCII(cx, "invalid lane interpretation");
1287 return false;
1288 }
1289
1290 static bool WasmGlobalExtractLane(JSContext* cx, unsigned argc, Value* vp) {
1291 if (!wasm::HasSupport(cx)) {
1292 JS_ReportErrorASCII(cx, "wasm support unavailable");
1293 return false;
1294 }
1295 CallArgs args = CallArgsFromVp(argc, vp);
1296
1297 if (args.length() < 3) {
1298 JS_ReportErrorASCII(cx, "not enough arguments");
1299 return false;
1300 }
1301
1302 // Get the global value
1303 if (!args.get(0).isObject() ||
1304 !args.get(0).toObject().is<WasmGlobalObject>()) {
1305 JS_ReportErrorASCII(cx, "argument is not wasm value");
1306 return false;
1307 }
1308 Rooted<WasmGlobalObject*> global(
1309 cx, &args.get(0).toObject().as<WasmGlobalObject>());
1310
1311 // Check that we have a v128 value
1312 if (global->type().kind() != wasm::ValType::V128) {
1313 JS_ReportErrorASCII(cx, "global is not a v128 value");
1314 return false;
1315 }
1316 wasm::V128 v128 = global->val().get().v128();
1317
1318 // Get the passed interpretation of lanes
1319 LaneInterp interp;
1320 if (!ToLaneInterp(cx, args.get(1), &interp)) {
1321 return false;
1322 }
1323
1324 // Get the lane to extract
1325 int32_t lane;
1326 if (!ToInt32(cx, args.get(2), &lane)) {
1327 return false;
1328 }
1329
1330 // Check that the lane interp is valid
1331 if (lane < 0 || size_t(lane) >= LaneInterpLanes(interp)) {
1332 JS_ReportErrorASCII(cx, "invalid lane for interp");
1333 return false;
1334 }
1335
1336 wasm::RootedVal val(cx);
1337 switch (interp) {
1338 case LaneInterp::I32x4: {
1339 uint32_t i;
1340 v128.extractLane<uint32_t>(lane, &i);
1341 val.set(wasm::Val(i));
1342 break;
1343 }
1344 case LaneInterp::I64x2: {
1345 uint64_t i;
1346 v128.extractLane<uint64_t>(lane, &i);
1347 val.set(wasm::Val(i));
1348 break;
1349 }
1350 case LaneInterp::F32x4: {
1351 float f;
1352 v128.extractLane<float>(lane, &f);
1353 val.set(wasm::Val(f));
1354 break;
1355 }
1356 case LaneInterp::F64x2: {
1357 double d;
1358 v128.extractLane<double>(lane, &d);
1359 val.set(wasm::Val(d));
1360 break;
1361 }
1362 default:
1363 MOZ_ASSERT_UNREACHABLE();
1364 }
1365
1366 RootedObject proto(
1367 cx, GlobalObject::getOrCreatePrototype(cx, JSProto_WasmGlobal));
1368 Rooted<WasmGlobalObject*> result(
1369 cx, WasmGlobalObject::create(cx, val, false, proto));
1370 args.rval().setObject(*result.get());
1371 return true;
1372 }
1373
1374 static bool WasmGlobalsEqual(JSContext* cx, unsigned argc, Value* vp) {
1375 if (!wasm::HasSupport(cx)) {
1376 JS_ReportErrorASCII(cx, "wasm support unavailable");
1377 return false;
1378 }
1379 CallArgs args = CallArgsFromVp(argc, vp);
1380
1381 if (args.length() < 2) {
1382 JS_ReportErrorASCII(cx, "not enough arguments");
1383 return false;
1384 }
1385
1386 if (!args.get(0).isObject() ||
1387 !args.get(0).toObject().is<WasmGlobalObject>() ||
1388 !args.get(1).isObject() ||
1389 !args.get(1).toObject().is<WasmGlobalObject>()) {
1390 JS_ReportErrorASCII(cx, "argument is not wasm value");
1391 return false;
1392 }
1393
1394 Rooted<WasmGlobalObject*> a(cx,
1395 &args.get(0).toObject().as<WasmGlobalObject>());
1396 Rooted<WasmGlobalObject*> b(cx,
1397 &args.get(1).toObject().as<WasmGlobalObject>());
1398
1399 if (a->type().kind() != b->type().kind()) {
1400 JS_ReportErrorASCII(cx, "globals are of different kind");
1401 return false;
1402 }
1403
1404 bool result;
1405 const wasm::Val& aVal = a->val().get();
1406 const wasm::Val& bVal = b->val().get();
1407 switch (a->type().kind()) {
1408 case wasm::ValType::I32: {
1409 result = aVal.i32() == bVal.i32();
1410 break;
1411 }
1412 case wasm::ValType::I64: {
1413 result = aVal.i64() == bVal.i64();
1414 break;
1415 }
1416 case wasm::ValType::F32: {
1417 result = mozilla::BitwiseCast<uint32_t>(aVal.f32()) ==
1418 mozilla::BitwiseCast<uint32_t>(bVal.f32());
1419 break;
1420 }
1421 case wasm::ValType::F64: {
1422 result = mozilla::BitwiseCast<uint64_t>(aVal.f64()) ==
1423 mozilla::BitwiseCast<uint64_t>(bVal.f64());
1424 break;
1425 }
1426 case wasm::ValType::V128: {
1427 // Don't know the interpretation of the v128, so we only can do an exact
1428 // bitwise equality. Testing code can use wasmGlobalExtractLane to
1429 // workaround this if needed.
1430 result = aVal.v128() == bVal.v128();
1431 break;
1432 }
1433 case wasm::ValType::Ref: {
1434 result = aVal.ref() == bVal.ref();
1435 break;
1436 }
1437 default:
1438 JS_ReportErrorASCII(cx, "unsupported type");
1439 return false;
1440 }
1441 args.rval().setBoolean(result);
1442 return true;
1443 }
1444
1445 // Flavors of NaN values for WebAssembly.
1446 // See
1447 // https://webassembly.github.io/spec/core/syntax/values.html#floating-point.
1448 enum class NaNFlavor {
1449 // A canonical NaN value.
1450 // - the sign bit is unspecified,
1451 // - the 8-bit exponent is set to all 1s
1452 // - the MSB of the payload is set to 1 (a quieted NaN) and all others to 0.
1453 Canonical,
1454 // An arithmetic NaN. This is the same as a canonical NaN including that the
1455 // payload MSB is set to 1, but one or more of the remaining payload bits MAY
1456 // BE set to 1 (a canonical NaN specifies all 0s).
1457 Arithmetic,
1458 };
1459
1460 static bool IsNaNFlavor(uint32_t bits, NaNFlavor flavor) {
1461 switch (flavor) {
1462 case NaNFlavor::Canonical: {
1463 return (bits & 0x7fffffff) == 0x7fc00000;
1464 }
1465 case NaNFlavor::Arithmetic: {
1466 const uint32_t ArithmeticNaN = 0x7f800000;
1467 const uint32_t ArithmeticPayloadMSB = 0x00400000;
1468 bool isNaN = (bits & ArithmeticNaN) == ArithmeticNaN;
1469 bool isMSBSet = (bits & ArithmeticPayloadMSB) == ArithmeticPayloadMSB;
1470 return isNaN && isMSBSet;
1471 }
1472 default:
1473 MOZ_CRASH();
1474 }
1475 }
1476
1477 static bool IsNaNFlavor(uint64_t bits, NaNFlavor flavor) {
1478 switch (flavor) {
1479 case NaNFlavor::Canonical: {
1480 return (bits & 0x7fffffffffffffff) == 0x7ff8000000000000;
1481 }
1482 case NaNFlavor::Arithmetic: {
1483 uint64_t ArithmeticNaN = 0x7ff0000000000000;
1484 uint64_t ArithmeticPayloadMSB = 0x0008000000000000;
1485 bool isNaN = (bits & ArithmeticNaN) == ArithmeticNaN;
1486 bool isMsbSet = (bits & ArithmeticPayloadMSB) == ArithmeticPayloadMSB;
1487 return isNaN && isMsbSet;
1488 }
1489 default:
1490 MOZ_CRASH();
1491 }
1492 }
1493
1494 static bool ToNaNFlavor(JSContext* cx, HandleValue v, NaNFlavor* out) {
1495 RootedString flavorStr(cx, ToString(cx, v));
1496 if (!flavorStr) {
1497 return false;
1498 }
1499 Rooted<JSLinearString*> flavorLinearStr(cx, flavorStr->ensureLinear(cx));
1500 if (!flavorLinearStr) {
1501 return false;
1502 }
1503
1504 if (StringEqualsLiteral(flavorLinearStr, "canonical_nan")) {
1505 *out = NaNFlavor::Canonical;
1506 return true;
1507 } else if (StringEqualsLiteral(flavorLinearStr, "arithmetic_nan")) {
1508 *out = NaNFlavor::Arithmetic;
1509 return true;
1510 }
1511
1512 JS_ReportErrorASCII(cx, "invalid nan flavor");
1513 return false;
1514 }
1515
1516 static bool WasmGlobalIsNaN(JSContext* cx, unsigned argc, Value* vp) {
1517 if (!wasm::HasSupport(cx)) {
1518 JS_ReportErrorASCII(cx, "wasm support unavailable");
1519 return false;
1520 }
1521 CallArgs args = CallArgsFromVp(argc, vp);
1522
1523 if (args.length() < 2) {
1524 JS_ReportErrorASCII(cx, "not enough arguments");
1525 return false;
1526 }
1527
1528 if (!args.get(0).isObject() ||
1529 !args.get(0).toObject().is<WasmGlobalObject>()) {
1530 JS_ReportErrorASCII(cx, "argument is not wasm value");
1531 return false;
1532 }
1533 Rooted<WasmGlobalObject*> global(
1534 cx, &args.get(0).toObject().as<WasmGlobalObject>());
1535
1536 NaNFlavor flavor;
1537 if (!ToNaNFlavor(cx, args.get(1), &flavor)) {
1538 return false;
1539 }
1540
1541 bool result;
1542 const wasm::Val& val = global->val().get();
1543 switch (global->type().kind()) {
1544 case wasm::ValType::F32: {
1545 result = IsNaNFlavor(mozilla::BitwiseCast<uint32_t>(val.f32()), flavor);
1546 break;
1547 }
1548 case wasm::ValType::F64: {
1549 result = IsNaNFlavor(mozilla::BitwiseCast<uint64_t>(val.f64()), flavor);
1550 break;
1551 }
1552 default:
1553 JS_ReportErrorASCII(cx, "global is not a floating point value");
1554 return false;
1555 }
1556 args.rval().setBoolean(result);
1557 return true;
1558 }
1559
1560 static bool WasmGlobalToString(JSContext* cx, unsigned argc, Value* vp) {
1561 if (!wasm::HasSupport(cx)) {
1562 JS_ReportErrorASCII(cx, "wasm support unavailable");
1563 return false;
1564 }
1565 CallArgs args = CallArgsFromVp(argc, vp);
1566
1567 if (args.length() < 1) {
1568 JS_ReportErrorASCII(cx, "not enough arguments");
1569 return false;
1570 }
1571 if (!args.get(0).isObject() ||
1572 !args.get(0).toObject().is<WasmGlobalObject>()) {
1573 JS_ReportErrorASCII(cx, "argument is not wasm value");
1574 return false;
1575 }
1576 Rooted<WasmGlobalObject*> global(
1577 cx, &args.get(0).toObject().as<WasmGlobalObject>());
1578 const wasm::Val& globalVal = global->val().get();
1579
1580 UniqueChars result;
1581 switch (globalVal.type().kind()) {
1582 case wasm::ValType::I32: {
1583 result = JS_smprintf("i32:%" PRIx32, globalVal.i32());
1584 break;
1585 }
1586 case wasm::ValType::I64: {
1587 result = JS_smprintf("i64:%" PRIx64, globalVal.i64());
1588 break;
1589 }
1590 case wasm::ValType::F32: {
1591 result = JS_smprintf("f32:%f", globalVal.f32());
1592 break;
1593 }
1594 case wasm::ValType::F64: {
1595 result = JS_smprintf("f64:%lf", globalVal.f64());
1596 break;
1597 }
1598 case wasm::ValType::V128: {
1599 wasm::V128 v128 = globalVal.v128();
1600 result = JS_smprintf(
1601 "v128:%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x", v128.bytes[0],
1602 v128.bytes[1], v128.bytes[2], v128.bytes[3], v128.bytes[4],
1603 v128.bytes[5], v128.bytes[6], v128.bytes[7], v128.bytes[8],
1604 v128.bytes[9], v128.bytes[10], v128.bytes[11], v128.bytes[12],
1605 v128.bytes[13], v128.bytes[14], v128.bytes[15]);
1606 break;
1607 }
1608 case wasm::ValType::Ref: {
1609 result = JS_smprintf("ref:%" PRIxPTR, globalVal.ref().rawValue());
1610 break;
1611 }
1612 default:
1613 MOZ_ASSERT_UNREACHABLE();
1614 }
1615
1616 args.rval().setString(JS_NewStringCopyZ(cx, result.get()));
1617 return true;
1618 }
1619
1620 static bool WasmLosslessInvoke(JSContext* cx, unsigned argc, Value* vp) {
1621 if (!wasm::HasSupport(cx)) {
1622 JS_ReportErrorASCII(cx, "wasm support unavailable");
1623 return false;
1624 }
1625 CallArgs args = CallArgsFromVp(argc, vp);
1626
1627 if (args.length() < 1) {
1628 JS_ReportErrorASCII(cx, "not enough arguments");
1629 return false;
1630 }
1631 if (!args.get(0).isObject() || !args.get(0).toObject().is<JSFunction>()) {
1632 JS_ReportErrorASCII(cx, "argument is not an object");
1633 return false;
1634 }
1635
1636 RootedFunction func(cx, &args[0].toObject().as<JSFunction>());
1637 if (!func || !func->isWasm()) {
1638 JS_ReportErrorASCII(cx, "argument is not an exported wasm function");
1639 return false;
1640 }
1641
1642 // Switch to the function's realm
1643 AutoRealm ar(cx, func);
1644
1645 // Get the instance and funcIndex for calling the function
1646 wasm::Instance& instance = func->wasmInstance();
1647 uint32_t funcIndex = func->wasmFuncIndex();
1648
1649 // Set up a modified call frame following the standard JS
1650 // [callee, this, arguments...] convention.
1651 RootedValueVector wasmCallFrame(cx);
1652 size_t len = 2 + args.length();
1653 if (!wasmCallFrame.resize(len)) {
1654 return false;
1655 }
1656 wasmCallFrame[0].set(ObjectValue(*func));
1657 wasmCallFrame[1].set(args.thisv());
1658 // Copy over the arguments needed to invoke the provided wasm function,
1659 // skipping the wasm function we're calling that is at `args.get(0)`.
1660 for (size_t i = 1; i < args.length(); i++) {
1661 size_t wasmArg = i - 1;
1662 wasmCallFrame[2 + wasmArg].set(args.get(i));
1663 }
1664 size_t wasmArgc = argc - 1;
1665 CallArgs wasmCallArgs(CallArgsFromVp(wasmArgc, wasmCallFrame.begin()));
1666
1667 // Invoke the function with the new call frame
1668 bool result = instance.callExport(cx, funcIndex, wasmCallArgs,
1669 wasm::CoercionLevel::Lossless);
1670 // Assign the wasm rval to our rval
1671 args.rval().set(wasmCallArgs.rval());
1672 return result;
1673 }
1674
1675 static bool ConvertToTier(JSContext* cx, HandleValue value,
1676 const wasm::Code& code, wasm::Tier* tier) {
1677 RootedString option(cx, JS::ToString(cx, value));
1678
1679 if (!option) {
1680 return false;
1681 }
1682
1683 bool stableTier = false;
1684 bool bestTier = false;
1685 bool baselineTier = false;
1686 bool ionTier = false;
1687
1688 if (!JS_StringEqualsLiteral(cx, option, "stable", &stableTier) ||
1689 !JS_StringEqualsLiteral(cx, option, "best", &bestTier) ||
1690 !JS_StringEqualsLiteral(cx, option, "baseline", &baselineTier) ||
1691 !JS_StringEqualsLiteral(cx, option, "ion", &ionTier)) {
1692 return false;
1693 }
1694
1695 if (stableTier) {
1696 *tier = code.stableCompleteTier();
1697 } else if (bestTier) {
1698 *tier = code.bestCompleteTier();
1699 } else if (baselineTier) {
1700 *tier = wasm::Tier::Baseline;
1701 } else if (ionTier) {
1702 *tier = wasm::Tier::Optimized;
1703 } else {
1704 // You can omit the argument but you can't pass just anything you like
1705 return false;
1706 }
1707
1708 return true;
1709 }
1710
1711 static bool WasmExtractCode(JSContext* cx, unsigned argc, Value* vp) {
1712 if (!wasm::HasSupport(cx)) {
1713 JS_ReportErrorASCII(cx, "wasm support unavailable");
1714 return false;
1715 }
1716
1717 CallArgs args = CallArgsFromVp(argc, vp);
1718
1719 if (!args.get(0).isObject()) {
1720 JS_ReportErrorASCII(cx, "argument is not an object");
1721 return false;
1722 }
1723
1724 Rooted<WasmModuleObject*> module(
1725 cx, args[0].toObject().maybeUnwrapIf<WasmModuleObject>());
1726 if (!module) {
1727 JS_ReportErrorASCII(cx, "argument is not a WebAssembly.Module");
1728 return false;
1729 }
1730
1731 wasm::Tier tier = module->module().code().stableCompleteTier();
1732 if (args.length() > 1 &&
1733 !ConvertToTier(cx, args[1], module->module().code(), &tier)) {
1734 args.rval().setNull();
1735 return false;
1736 }
1737
1738 RootedValue result(cx);
1739 if (!module->module().extractCode(cx, tier, &result)) {
1740 return false;
1741 }
1742
1743 args.rval().set(result);
1744 return true;
1745 }
1746
1747 static bool HasDisassembler(JSContext* cx, unsigned argc, Value* vp) {
1748 CallArgs args = CallArgsFromVp(argc, vp);
1749 args.rval().setBoolean(jit::HasDisassembler());
1750 return true;
1751 }
1752
1753 MOZ_THREAD_LOCAL(JSSprinter*) disasmPrinter;
1754
1755 static void captureDisasmText(const char* text) {
1756 JSSprinter* printer = disasmPrinter.get();
1757 printer->put(text);
1758 printer->printf("\n");
1759 }
1760
1761 static bool DisassembleNative(JSContext* cx, unsigned argc, Value* vp) {
1762 CallArgs args = CallArgsFromVp(argc, vp);
1763
1764 if (args.length() < 1) {
1765 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1766 JSMSG_MORE_ARGS_NEEDED, "disnative", "1", "",
1767 "0");
1768 return false;
1769 }
1770
1771 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
1772 JS_ReportErrorASCII(cx, "The first argument must be a function.");
1773 return false;
1774 }
1775
1776 JSSprinter sprinter(cx);
1777 if (!sprinter.init()) {
1778 return false;
1779 }
1780
1781 RootedFunction fun(cx, &args[0].toObject().as<JSFunction>());
1782
1783 uint8_t* jit_begin = nullptr;
1784 uint8_t* jit_end = nullptr;
1785
1786 if (fun->isAsmJSNative() || fun->isWasmWithJitEntry()) {
1787 if (IsAsmJSModule(fun)) {
1788 JS_ReportErrorASCII(cx, "Can't disassemble asm.js module function.");
1789 return false;
1790 }
1791 if (fun->isAsmJSNative()) {
1792 sprinter.printf("; backend=asmjs\n");
1793 }
1794 sprinter.printf("; backend=wasm\n");
1795
1796 js::wasm::Instance& inst = fun->wasmInstance();
1797 const uint32_t funcIndex = fun->wasmFuncIndex();
1798 const js::wasm::CodeBlock& codeBlock = inst.code().funcCodeBlock(funcIndex);
1799 const js::wasm::FuncExport& func = codeBlock.lookupFuncExport(funcIndex);
1800 const js::wasm::CodeRange& codeRange = codeBlock.codeRange(func);
1801
1802 jit_begin = codeBlock.base() + codeRange.begin();
1803 jit_end = codeBlock.base() + codeRange.end();
1804 } else if (fun->hasJitScript() && fun->nonLazyScript()->hasIonScript()) {
1805 sprinter.printf("; backend=ion\n");
1806 jit_begin = fun->nonLazyScript()->ionScript()->method()->raw();
1807 jit_end = fun->nonLazyScript()->ionScript()->method()->rawEnd();
1808 } else if (fun->hasJitScript() && fun->nonLazyScript()->hasBaselineScript()) {
1809 sprinter.printf("; backend=baseline\n");
1810 jit_begin = fun->nonLazyScript()->baselineScript()->method()->raw();
1811 jit_end = fun->nonLazyScript()->baselineScript()->method()->rawEnd();
1812 } else {
1813 JS_ReportErrorASCII(cx,
1814 "The function hasn't been warmed up, hence no JIT code "
1815 "to disassemble.");
1816 return false;
1817 }
1818
1819 MOZ_ASSERT(jit_begin);
1820 MOZ_ASSERT(jit_end);
1821
1822 #ifdef JS_CODEGEN_ARM
1823 // The ARM32 disassembler is currently not fuzzing-safe because it doesn't
1824 // handle constant pools correctly (bug 1875363).
1825 if (fuzzingSafe) {
1826 JS_ReportErrorASCII(cx, "disnative is not fuzzing-safe on ARM32");
1827 return false;
1828 }
1829 #endif
1830
1831 // Dump the raw code to a file before disassembling in case
1832 // finishString triggers a GC and discards the jitcode.
1833 if (!fuzzingSafe && args.length() > 1 && args[1].isString()) {
1834 RootedString str(cx, args[1].toString());
1835 JS::UniqueChars fileNameBytes = JS_EncodeStringToUTF8(cx, str);
1836
1837 const char* fileName = fileNameBytes.get();
1838 if (!fileName) {
1839 ReportOutOfMemory(cx);
1840 return false;
1841 }
1842
1843 FILE* f = fopen(fileName, "w");
1844 if (!f) {
1845 JS_ReportErrorASCII(cx, "Could not open file for writing.");
1846 return false;
1847 }
1848
1849 uintptr_t expected_length = reinterpret_cast<uintptr_t>(jit_end) -
1850 reinterpret_cast<uintptr_t>(jit_begin);
1851 if (expected_length != fwrite(jit_begin, jit_end - jit_begin, 1, f)) {
1852 JS_ReportErrorASCII(cx, "Did not write all function bytes to the file.");
1853 fclose(f);
1854 return false;
1855 }
1856 fclose(f);
1857 }
1858
1859 disasmPrinter.set(&sprinter);
1860 auto onFinish = mozilla::MakeScopeExit([&] { disasmPrinter.set(nullptr); });
1861
1862 jit::Disassemble(jit_begin, jit_end - jit_begin, &captureDisasmText);
1863
1864 JSString* str = sprinter.release(cx);
1865 if (!str) {
1866 return false;
1867 }
1868
1869 args.rval().setString(str);
1870 return true;
1871 }
1872
1873 static bool DisassembleBaselineICs(JSContext* cx, unsigned argc, Value* vp) {
1874 CallArgs args = CallArgsFromVp(argc, vp);
1875 args.rval().setUndefined();
1876
1877 if (!args.requireAtLeast(cx, "disblic", 1)) {
1878 return false;
1879 }
1880
1881 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
1882 JS_ReportErrorASCII(cx, "The first argument must be a function.");
1883 return false;
1884 }
1885
1886 JSSprinter sprinter(cx);
1887 if (!sprinter.init()) {
1888 return false;
1889 }
1890
1891 disasmPrinter.set(&sprinter);
1892 auto onFinish = mozilla::MakeScopeExit([&] { disasmPrinter.set(nullptr); });
1893
1894 RootedFunction fun(cx, &args[0].toObject().as<JSFunction>());
1895
1896 if (!fun->hasJitScript()) {
1897 args.rval().setUndefined();
1898 return true;
1899 }
1900
1901 #ifdef JS_CODEGEN_ARM
1902 // The ARM32 disassembler is currently not fuzzing-safe because it doesn't
1903 // handle constant pools correctly (bug 1875363).
1904 if (fuzzingSafe) {
1905 JS_ReportErrorASCII(cx, "disblic is not fuzzing-safe on ARM32");
1906 return false;
1907 }
1908 #endif
1909
1910 RootedScript script(cx, fun->nonLazyScript());
1911 jit::ICScript* icScript = script->jitScript()->icScript();
1912 for (uint32_t i = 0; i < icScript->numICEntries(); i++) {
1913 jit::ICEntry& entry = icScript->icEntry(i);
1914 jit::ICStub* stub = entry.firstStub();
1915
1916 jit::ICStub* fallbackStub = stub;
1917 while (!fallbackStub->isFallback()) {
1918 fallbackStub = fallbackStub->toCacheIRStub()->next();
1919 }
1920 uint32_t pcOffset = fallbackStub->toFallbackStub()->pcOffset();
1921 sprinter.printf("; %s (pcOffset %05u)\n",
1922 CodeName(JSOp(*script->offsetToPC(pcOffset))), pcOffset);
1923
1924 uint32_t stubNum = 1;
1925 while (!stub->isFallback()) {
1926 sprinter.printf("; Stub #%d (entry count: %d)\n", stubNum,
1927 stub->enteredCount());
1928 jit::ICCacheIRStub* cacheIRStub = stub->toCacheIRStub();
1929 uint8_t* jit_begin = stub->jitCode()->raw();
1930 uint8_t* jit_end = stub->jitCode()->rawEnd();
1931 #ifdef JS_CACHEIR_SPEW
1932 sprinter.printf("; IR:\n");
1933 SpewCacheIROps(sprinter, "; ", cacheIRStub->stubInfo());
1934 #endif
1935
1936 jit::Disassemble(jit_begin, jit_end - jit_begin, &captureDisasmText);
1937 stub = cacheIRStub->next();
1938 stubNum++;
1939 }
1940 }
1941
1942 JSString* str = sprinter.release(cx);
1943 if (!str) {
1944 return false;
1945 }
1946
1947 args.rval().setString(str);
1948 return true;
1949 }
1950
1951 static bool ComputeTier(JSContext* cx, const wasm::Code& code,
1952 HandleValue tierSelection, wasm::Tier* tier) {
1953 *tier = code.stableCompleteTier();
1954 if (!tierSelection.isUndefined() &&
1955 !ConvertToTier(cx, tierSelection, code, tier)) {
1956 JS_ReportErrorASCII(cx, "invalid tier");
1957 return false;
1958 }
1959
1960 return true;
1961 }
1962
1963 template <typename DisasmFunction>
1964 static bool DisassembleIt(JSContext* cx, bool asString, MutableHandleValue rval,
1965 DisasmFunction&& disassembleIt) {
1966 if (asString) {
1967 JSSprinter sprinter(cx);
1968 if (!sprinter.init()) {
1969 return false;
1970 }
1971 disasmPrinter.set(&sprinter);
1972 auto onFinish = mozilla::MakeScopeExit([&] { disasmPrinter.set(nullptr); });
1973 disassembleIt(captureDisasmText);
1974
1975 JSString* sresult = sprinter.release(cx);
1976 if (!sresult) {
1977 return false;
1978 }
1979 rval.setString(sresult);
1980 return true;
1981 }
1982
1983 disassembleIt([](const char* text) { fprintf(stderr, "%s\n", text); });
1984 return true;
1985 }
1986
1987 static bool WasmDisassembleFunction(JSContext* cx, const HandleFunction& func,
1988 HandleValue tierSelection, bool asString,
1989 MutableHandleValue rval) {
1990 wasm::Instance& instance = func->wasmInstance();
1991 uint32_t funcIndex = func->wasmFuncIndex();
1992 wasm::Tier tier;
1993
1994 if (!ComputeTier(cx, instance.code(), tierSelection, &tier)) {
1995 return false;
1996 }
1997
1998 if (!instance.code().funcHasTier(funcIndex, tier)) {
1999 JS_ReportErrorASCII(cx, "function missing selected tier");
2000 return false;
2001 }
2002
2003 return DisassembleIt(
2004 cx, asString, rval, [&](void (*captureText)(const char*)) {
2005 instance.disassembleExport(cx, funcIndex, tier, captureText);
2006 });
2007 }
2008
2009 static bool WasmDisassembleCode(JSContext* cx, const wasm::Code& code,
2010 HandleValue tierSelection, int kindSelection,
2011 bool asString, MutableHandleValue rval) {
2012 wasm::Tier tier;
2013 if (!ComputeTier(cx, code, tierSelection, &tier)) {
2014 return false;
2015 }
2016
2017 return DisassembleIt(cx, asString, rval,
2018 [&](void (*captureText)(const char*)) {
2019 code.disassemble(cx, tier, kindSelection, captureText);
2020 });
2021 }
2022
2023 static bool WasmDisassemble(JSContext* cx, unsigned argc, Value* vp) {
2024 if (!wasm::HasSupport(cx)) {
2025 JS_ReportErrorASCII(cx, "wasm support unavailable");
2026 return false;
2027 }
2028
2029 CallArgs args = CallArgsFromVp(argc, vp);
2030
2031 args.rval().set(UndefinedValue());
2032
2033 if (!args.get(0).isObject()) {
2034 JS_ReportErrorASCII(cx, "argument is not an object");
2035 return false;
2036 }
2037
2038 bool asString = false;
2039 RootedValue tierSelection(cx);
2040 int kindSelection = (1 << wasm::CodeRange::Function);
2041 if (args.length() > 1 && args[1].isObject()) {
2042 RootedObject options(cx, &args[1].toObject());
2043 RootedValue val(cx);
2044
2045 if (!JS_GetProperty(cx, options, "asString", &val)) {
2046 return false;
2047 }
2048 asString = val.isBoolean() && val.toBoolean();
2049
2050 if (!JS_GetProperty(cx, options, "tier", &tierSelection)) {
2051 return false;
2052 }
2053
2054 if (!JS_GetProperty(cx, options, "kinds", &val)) {
2055 return false;
2056 }
2057 if (val.isString() && val.toString()->hasLatin1Chars()) {
2058 AutoStableStringChars stable(cx);
2059 if (!stable.init(cx, val.toString())) {
2060 return false;
2061 }
2062 const char* p = (const char*)(stable.latin1Chars());
2063 const char* end = p + val.toString()->length();
2064 int selection = 0;
2065 for (;;) {
2066 if (strncmp(p, "Function", 8) == 0) {
2067 selection |= (1 << wasm::CodeRange::Function);
2068 p += 8;
2069 } else if (strncmp(p, "InterpEntry", 11) == 0) {
2070 selection |= (1 << wasm::CodeRange::InterpEntry);
2071 p += 11;
2072 } else if (strncmp(p, "JitEntry", 8) == 0) {
2073 selection |= (1 << wasm::CodeRange::JitEntry);
2074 p += 8;
2075 } else if (strncmp(p, "ImportInterpExit", 16) == 0) {
2076 selection |= (1 << wasm::CodeRange::ImportInterpExit);
2077 p += 16;
2078 } else if (strncmp(p, "ImportJitExit", 13) == 0) {
2079 selection |= (1 << wasm::CodeRange::ImportJitExit);
2080 p += 13;
2081 } else if (strncmp(p, "all", 3) == 0) {
2082 selection = ~0;
2083 p += 3;
2084 } else {
2085 break;
2086 }
2087 if (p == end || *p != ',') {
2088 break;
2089 }
2090 p++;
2091 }
2092 if (p == end) {
2093 kindSelection = selection;
2094 } else {
2095 JS_ReportErrorASCII(cx, "argument object has invalid `kinds`");
2096 return false;
2097 }
2098 }
2099 }
2100
2101 RootedFunction func(cx, args[0].toObject().maybeUnwrapIf<JSFunction>());
2102 if (func && func->isWasm()) {
2103 return WasmDisassembleFunction(cx, func, tierSelection, asString,
2104 args.rval());
2105 }
2106 if (args[0].toObject().is<WasmModuleObject>()) {
2107 return WasmDisassembleCode(
2108 cx, args[0].toObject().as<WasmModuleObject>().module().code(),
2109 tierSelection, kindSelection, asString, args.rval());
2110 }
2111 if (args[0].toObject().is<WasmInstanceObject>()) {
2112 return WasmDisassembleCode(
2113 cx, args[0].toObject().as<WasmInstanceObject>().instance().code(),
2114 tierSelection, kindSelection, asString, args.rval());
2115 }
2116 JS_ReportErrorASCII(
2117 cx, "argument is not an exported wasm function or a wasm module");
2118 return false;
2119 }
2120
2121 static bool WasmModuleToText(JSContext* cx, unsigned argc, Value* vp) {
2122 if (!wasm::HasSupport(cx)) {
2123 JS_ReportErrorASCII(cx, "wasm support unavailable");
2124 return false;
2125 }
2126
2127 CallArgs args = CallArgsFromVp(argc, vp);
2128
2129 if (!args.get(0).isObject()) {
2130 JS_ReportErrorASCII(cx, "argument is not an object");
2131 return false;
2132 }
2133
2134 if (!args[0].toObject().is<WasmModuleObject>()) {
2135 JS_ReportErrorASCII(cx, "argument is not a wasm module");
2136 return false;
2137 }
2138
2139 const wasm::Module& mod = args[0].toObject().as<WasmModuleObject>().module();
2140 JSSprinter out(cx);
2141 if (!out.init()) {
2142 ReportOutOfMemory(cx);
2143 return false;
2144 }
2145 wasm::DumpModule(mod, out);
2146
2147 JSString* str = out.release(cx);
2148 if (!str) {
2149 ReportOutOfMemory(cx);
2150 return false;
2151 }
2152 args.rval().set(StringValue(str));
2153 return true;
2154 }
2155
2156 static bool WasmFunctionTier(JSContext* cx, unsigned argc, Value* vp) {
2157 if (!wasm::HasSupport(cx)) {
2158 JS_ReportErrorASCII(cx, "wasm support unavailable");
2159 return false;
2160 }
2161
2162 CallArgs args = CallArgsFromVp(argc, vp);
2163
2164 args.rval().set(UndefinedValue());
2165
2166 if (!args.get(0).isObject()) {
2167 JS_ReportErrorASCII(cx, "argument is not an object");
2168 return false;
2169 }
2170
2171 RootedFunction func(cx, args[0].toObject().maybeUnwrapIf<JSFunction>());
2172 if (func && func->isWasm()) {
2173 uint32_t funcIndex = func->wasmFuncIndex();
2174 wasm::Instance& instance = func->wasmInstance();
2175 if (funcIndex < instance.code().funcImports().length()) {
2176 JS_ReportErrorASCII(cx, "argument is an imported function");
2177 return false;
2178 }
2179 wasm::Tier tier = instance.code().funcTier(funcIndex);
2180 RootedString tierString(cx, JS_NewStringCopyZ(cx, wasm::ToString(tier)));
2181 if (!tierString) {
2182 ReportOutOfMemory(cx);
2183 return false;
2184 }
2185 args.rval().set(StringValue(tierString));
2186 return true;
2187 }
2188 JS_ReportErrorASCII(cx, "argument is not an exported wasm function");
2189 return false;
2190 }
2191
2192 static bool ToIonDumpContents(JSContext* cx, HandleValue value,
2193 wasm::IonDumpContents* contents) {
2194 RootedString option(cx, JS::ToString(cx, value));
2195
2196 if (!option) {
2197 return false;
2198 }
2199
2200 bool isEqual = false;
2201 if (!JS_StringEqualsLiteral(cx, option, "mir", &isEqual) || isEqual) {
2202 *contents = wasm::IonDumpContents::UnoptimizedMIR;
2203 return isEqual;
2204 } else if (!JS_StringEqualsLiteral(cx, option, "unopt-mir", &isEqual) ||
2205 isEqual) {
2206 *contents = wasm::IonDumpContents::UnoptimizedMIR;
2207 return isEqual;
2208 } else if (!JS_StringEqualsLiteral(cx, option, "opt-mir", &isEqual) ||
2209 isEqual) {
2210 *contents = wasm::IonDumpContents::OptimizedMIR;
2211 return isEqual;
2212 } else if (!JS_StringEqualsLiteral(cx, option, "lir", &isEqual) || isEqual) {
2213 *contents = wasm::IonDumpContents::LIR;
2214 return isEqual;
2215 } else {
2216 return false;
2217 }
2218 }
2219
2220 static bool WasmDumpIon(JSContext* cx, unsigned argc, Value* vp) {
2221 if (!wasm::HasSupport(cx)) {
2222 JS_ReportErrorASCII(cx, "wasm support unavailable");
2223 return false;
2224 }
2225
2226 CallArgs args = CallArgsFromVp(argc, vp);
2227
2228 args.rval().set(UndefinedValue());
2229
2230 if (!args.get(0).isObject()) {
2231 JS_ReportErrorASCII(cx, "argument is not an object");
2232 return false;
2233 }
2234
2235 uint32_t targetFuncIndex;
2236 if (!ToUint32(cx, args.get(1), &targetFuncIndex)) {
2237 JS_ReportErrorASCII(cx, "argument is not a func index");
2238 return false;
2239 }
2240
2241 wasm::IonDumpContents contents = wasm::IonDumpContents::Default;
2242 if (args.length() > 2 && !ToIonDumpContents(cx, args.get(2), &contents)) {
2243 JS_ReportErrorASCII(cx, "argument is not a valid dump contents");
2244 return false;
2245 }
2246
2247 SharedMem<uint8_t*> dataPointer;
2248 size_t byteLength;
2249 if (!IsBufferSource(cx, args.get(0).toObjectOrNull(), /*allowShared*/ false,
2250 /*allowResizable*/ false, &dataPointer, &byteLength)) {
2251 JS_ReportErrorASCII(cx, "argument is not a buffer source");
2252 return false;
2253 }
2254
2255 wasm::MutableBytes bytecode = cx->new_<wasm::ShareableBytes>();
2256 if (!bytecode) {
2257 return false;
2258 }
2259 if (!bytecode->append(dataPointer.unwrap(), byteLength)) {
2260 ReportOutOfMemory(cx);
2261 return false;
2262 }
2263
2264 UniqueChars error;
2265 JSSprinter out(cx);
2266 if (!out.init()) {
2267 ReportOutOfMemory(cx);
2268 return false;
2269 }
2270
2271 if (!wasm::DumpIonFunctionInModule(*bytecode, targetFuncIndex, contents, out,
2272 &error)) {
2273 if (error) {
2274 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
2275 JSMSG_WASM_COMPILE_ERROR, error.get());
2276 return false;
2277 }
2278 ReportOutOfMemory(cx);
2279 return false;
2280 }
2281
2282 JSString* str = out.release(cx);
2283 if (!str) {
2284 ReportOutOfMemory(cx);
2285 return false;
2286 }
2287 args.rval().set(StringValue(str));
2288 return true;
2289 }
2290
2291 enum class Flag { Tier2Complete, Deserialized, ParsedBranchHints };
2292
2293 static bool WasmReturnFlag(JSContext* cx, unsigned argc, Value* vp, Flag flag) {
2294 CallArgs args = CallArgsFromVp(argc, vp);
2295
2296 if (!args.get(0).isObject()) {
2297 JS_ReportErrorASCII(cx, "argument is not an object");
2298 return false;
2299 }
2300
2301 Rooted<WasmModuleObject*> module(
2302 cx, args[0].toObject().maybeUnwrapIf<WasmModuleObject>());
2303 if (!module) {
2304 JS_ReportErrorASCII(cx, "argument is not a WebAssembly.Module");
2305 return false;
2306 }
2307
2308 bool b;
2309 switch (flag) {
2310 case Flag::Tier2Complete:
2311 b = !module->module().testingTier2Active();
2312 break;
2313 case Flag::Deserialized:
2314 b = module->module().loggingDeserialized();
2315 break;
2316 case Flag::ParsedBranchHints:
2317 b = !module->module().codeMeta().branchHints.failedParse();
2318 break;
2319 }
2320
2321 args.rval().set(BooleanValue(b));
2322 return true;
2323 }
2324
2325 static bool wasmMetadataAnalysis(JSContext* cx, unsigned argc, Value* vp) {
2326 CallArgs args = CallArgsFromVp(argc, vp);
2327
2328 if (!args.get(0).isObject()) {
2329 JS_ReportErrorASCII(cx, "argument is not an object");
2330 return false;
2331 }
2332
2333 if (args[0].toObject().is<WasmModuleObject>()) {
2334 HashMap<const char*, uint32_t, mozilla::CStringHasher, SystemAllocPolicy>
2335 hashmap = args[0]
2336 .toObject()
2337 .as<WasmModuleObject>()
2338 .module()
2339 .code()
2340 .metadataAnalysis(cx);
2341 if (hashmap.empty()) {
2342 JS_ReportErrorASCII(cx, "Metadata analysis has failed");
2343 return false;
2344 }
2345
2346 // metadataAnalysis returned a map of {key, value} with various statistics
2347 // convert it into a dictionary to be used by JS
2348 Rooted<IdValueVector> props(cx, IdValueVector(cx));
2349
2350 for (auto iter = hashmap.iter(); !iter.done(); iter.next()) {
2351 const auto* key = iter.get().key();
2352 auto value = iter.get().value();
2353
2354 JSString* string = JS_NewStringCopyZ(cx, key);
2355 if (!string) {
2356 return false;
2357 }
2358
2359 if (!props.append(
2360 IdValuePair(NameToId(string->asLinear().toPropertyName(cx)),
2361 NumberValue(value)))) {
2362 return false;
2363 }
2364 }
2365
2366 JSObject* results = NewPlainObjectWithUniqueNames(cx, props);
2367 if (!results) {
2368 return false;
2369 }
2370 args.rval().setObject(*results);
2371
2372 return true;
2373 }
2374
2375 JS_ReportErrorASCII(
2376 cx, "argument is not an exported wasm function or a wasm module");
2377
2378 return false;
2379 }
2380
2381 static bool WasmHasTier2CompilationCompleted(JSContext* cx, unsigned argc,
2382 Value* vp) {
2383 return WasmReturnFlag(cx, argc, vp, Flag::Tier2Complete);
2384 }
2385
2386 static bool WasmLoadedFromCache(JSContext* cx, unsigned argc, Value* vp) {
2387 return WasmReturnFlag(cx, argc, vp, Flag::Deserialized);
2388 }
2389
2390 #ifdef ENABLE_WASM_BRANCH_HINTING
2391 static bool WasmParsedBranchHints(JSContext* cx, unsigned argc, Value* vp) {
2392 return WasmReturnFlag(cx, argc, vp, Flag::ParsedBranchHints);
2393 }
2394 #endif // ENABLE_WASM_BRANCH_HINTING
2395
2396 static bool WasmBuiltinI8VecMul(JSContext* cx, unsigned argc, Value* vp) {
2397 if (!wasm::HasSupport(cx)) {
2398 JS_ReportErrorASCII(cx, "wasm support unavailable");
2399 return false;
2400 }
2401
2402 CallArgs args = CallArgsFromVp(argc, vp);
2403
2404 Rooted<WasmModuleObject*> module(cx);
2405 if (!wasm::CompileBuiltinModule(cx, wasm::BuiltinModuleId::SelfTest,
2406 &module)) {
2407 return false;
2408 }
2409 args.rval().set(ObjectValue(*module.get()));
2410 return true;
2411 }
2412
2413 static bool WasmGcReadField(JSContext* cx, unsigned argc, Value* vp) {
2414 CallArgs args = CallArgsFromVp(argc, vp);
2415 RootedObject callee(cx, &args.callee());
2416
2417 if (!args.requireAtLeast(cx, "wasmGcReadField", 2)) {
2418 return false;
2419 }
2420
2421 if (!args[0].isObject() || !args[0].toObject().is<WasmGcObject>()) {
2422 ReportUsageErrorASCII(cx, callee,
2423 "First argument must be a WebAssembly GC object");
2424 return false;
2425 }
2426
2427 int32_t fieldIndex;
2428 if (!JS::ToInt32(cx, args[1], &fieldIndex) || fieldIndex < 0) {
2429 ReportUsageErrorASCII(cx, callee,
2430 "Second argument must be a non-negative integer");
2431 return false;
2432 }
2433
2434 Rooted<WasmGcObject*> gcObject(cx, &args[0].toObject().as<WasmGcObject>());
2435 Rooted<Value> gcValue(cx);
2436 if (!WasmGcObject::loadValue(cx, gcObject, jsid::Int(int32_t(fieldIndex)),
2437 &gcValue)) {
2438 return false;
2439 }
2440
2441 args.rval().set(gcValue);
2442 return true;
2443 }
2444
2445 static bool WasmGcArrayLength(JSContext* cx, unsigned argc, Value* vp) {
2446 CallArgs args = CallArgsFromVp(argc, vp);
2447 RootedObject callee(cx, &args.callee());
2448
2449 if (!args.requireAtLeast(cx, "wasmGcArrayLength", 1)) {
2450 return false;
2451 }
2452
2453 if (!args[0].isObject() || !args[0].toObject().is<WasmArrayObject>()) {
2454 ReportUsageErrorASCII(cx, callee,
2455 "First argument must be a WebAssembly GC array");
2456 return false;
2457 }
2458
2459 WasmArrayObject& arr = args[0].toObject().as<WasmArrayObject>();
2460 args.rval().setInt32(int32_t(arr.numElements_));
2461 return true;
2462 }
2463
2464 static bool LargeArrayBufferSupported(JSContext* cx, unsigned argc, Value* vp) {
2465 CallArgs args = CallArgsFromVp(argc, vp);
2466 args.rval().setBoolean(ArrayBufferObject::ByteLengthLimit >
2467 ArrayBufferObject::ByteLengthLimitForSmallBuffer);
2468 return true;
2469 }
2470
2471 static bool IsLazyFunction(JSContext* cx, unsigned argc, Value* vp) {
2472 CallArgs args = CallArgsFromVp(argc, vp);
2473 if (args.length() != 1) {
2474 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
2475 return false;
2476 }
2477 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
2478 JS_ReportErrorASCII(cx, "The first argument should be a function.");
2479 return false;
2480 }
2481 JSFunction* fun = &args[0].toObject().as<JSFunction>();
2482 args.rval().setBoolean(fun->isInterpreted() && !fun->hasBytecode());
2483 return true;
2484 }
2485
2486 static bool IsRelazifiableFunction(JSContext* cx, unsigned argc, Value* vp) {
2487 CallArgs args = CallArgsFromVp(argc, vp);
2488 if (args.length() != 1) {
2489 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
2490 return false;
2491 }
2492 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
2493 JS_ReportErrorASCII(cx, "The first argument should be a function.");
2494 return false;
2495 }
2496
2497 JSFunction* fun = &args[0].toObject().as<JSFunction>();
2498 args.rval().setBoolean(fun->hasBytecode() &&
2499 fun->nonLazyScript()->allowRelazify());
2500 return true;
2501 }
2502
2503 static bool IsCollectingDelazifications(JSContext* cx, unsigned argc,
2504 Value* vp) {
2505 CallArgs args = CallArgsFromVp(argc, vp);
2506 if (args.length() != 1) {
2507 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
2508 return false;
2509 }
2510
2511 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
2512 JS_ReportErrorASCII(cx, "The first argument should be a function.");
2513 return false;
2514 }
2515
2516 if (fuzzingSafe) {
2517 // When running code concurrently to fill-up the stencil cache, the content
2518 // is not garanteed to be present.
2519 args.rval().setBoolean(false);
2520 return true;
2521 }
2522
2523 JSFunction* fun = &args[0].toObject().as<JSFunction>();
2524 BaseScript* script = fun->baseScript();
2525 args.rval().setBoolean(
2526 bool(script->sourceObject()->isCollectingDelazifications()));
2527 return true;
2528 }
2529
2530 static bool IsDelazificationsPopulated(JSContext* cx, unsigned argc,
2531 Value* vp) {
2532 CallArgs args = CallArgsFromVp(argc, vp);
2533 if (args.length() != 1) {
2534 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
2535 return false;
2536 }
2537
2538 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
2539 JS_ReportErrorASCII(cx, "The first argument should be a function.");
2540 return false;
2541 }
2542
2543 if (fuzzingSafe) {
2544 // When running code concurrently to fill-up the stencil cache, the content
2545 // is not garanteed to be present.
2546 args.rval().setBoolean(false);
2547 return true;
2548 }
2549
2550 JSFunction* fun = &args[0].toObject().as<JSFunction>();
2551 BaseScript* script = fun->baseScript();
2552 RefPtr<frontend::InitialStencilAndDelazifications> stencils =
2553 script->sourceObject()->maybeGetStencils();
2554 if (!stencils) {
2555 args.rval().setBoolean(false);
2556 return true;
2557 }
2558
2559 const frontend::CompilationStencil* stencil =
2560 stencils->getDelazificationFor(script->extent());
2561 args.rval().setBoolean(bool(stencil));
2562 return true;
2563 }
2564
2565 static bool WaitForDelazificationOf(JSContext* cx, unsigned argc, Value* vp) {
2566 CallArgs args = CallArgsFromVp(argc, vp);
2567 if (args.length() != 1) {
2568 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
2569 return false;
2570 }
2571
2572 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
2573 JS_ReportErrorASCII(cx, "The first argument should be a function.");
2574 return false;
2575 }
2576 args.rval().setUndefined();
2577
2578 JSFunction* fun = &args[0].toObject().as<JSFunction>();
2579 BaseScript* script = fun->baseScript();
2580
2581 if (!script->sourceObject()->isSharingDelazifications()) {
2582 return true;
2583 }
2584
2585 RefPtr<frontend::InitialStencilAndDelazifications> stencils =
2586 script->sourceObject()->maybeGetStencils();
2587
2588 AutoLockHelperThreadState lock;
2589 if (!HelperThreadState().isInitialized(lock)) {
2590 return true;
2591 }
2592
2593 while (true) {
2594 const frontend::CompilationStencil* stencil =
2595 stencils->getDelazificationFor(script->extent());
2596 if (stencil) {
2597 break;
2598 }
2599
2600 HelperThreadState().wait(lock);
2601 }
2602 return true;
2603 }
2604
2605 static bool HasSameBytecodeData(JSContext* cx, unsigned argc, Value* vp) {
2606 CallArgs args = CallArgsFromVp(argc, vp);
2607 if (args.length() != 2) {
2608 JS_ReportErrorASCII(cx, "The function takes exactly two argument.");
2609 return false;
2610 }
2611
2612 auto GetSharedData = [](JSContext* cx,
2613 HandleValue v) -> SharedImmutableScriptData* {
2614 if (!v.isObject()) {
2615 JS_ReportErrorASCII(cx, "The arguments must be interpreted functions.");
2616 return nullptr;
2617 }
2618
2619 RootedObject obj(cx, CheckedUnwrapDynamic(&v.toObject(), cx));
2620 if (!obj) {
2621 return nullptr;
2622 }
2623
2624 if (!obj->is<JSFunction>() || !obj->as<JSFunction>().isInterpreted()) {
2625 JS_ReportErrorASCII(cx, "The arguments must be interpreted functions.");
2626 return nullptr;
2627 }
2628
2629 AutoRealm ar(cx, obj);
2630 RootedFunction fun(cx, &obj->as<JSFunction>());
2631 RootedScript script(cx, JSFunction::getOrCreateScript(cx, fun));
2632 if (!script) {
2633 return nullptr;
2634 }
2635
2636 MOZ_ASSERT(script->sharedData());
2637 return script->sharedData();
2638 };
2639
2640 // NOTE: We use RefPtr below to keep the data alive across possible GC since
2641 // the functions may be in different Zones.
2642
2643 RefPtr<SharedImmutableScriptData> sharedData1 = GetSharedData(cx, args[0]);
2644 if (!sharedData1) {
2645 return false;
2646 }
2647
2648 RefPtr<SharedImmutableScriptData> sharedData2 = GetSharedData(cx, args[1]);
2649 if (!sharedData2) {
2650 return false;
2651 }
2652
2653 args.rval().setBoolean(sharedData1 == sharedData2);
2654 return true;
2655 }
2656
2657 static bool InternalConst(JSContext* cx, unsigned argc, Value* vp) {
2658 CallArgs args = CallArgsFromVp(argc, vp);
2659 if (args.length() == 0) {
2660 JS_ReportErrorASCII(cx, "the function takes exactly one argument");
2661 return false;
2662 }
2663
2664 JSString* str = ToString(cx, args[0]);
2665 if (!str) {
2666 return false;
2667 }
2668 JSLinearString* linear = JS_EnsureLinearString(cx, str);
2669 if (!linear) {
2670 return false;
2671 }
2672
2673 if (JS_LinearStringEqualsLiteral(linear, "MARK_STACK_BASE_CAPACITY")) {
2674 args.rval().setNumber(uint32_t(js::MARK_STACK_BASE_CAPACITY));
2675 } else {
2676 JS_ReportErrorASCII(cx, "unknown const name");
2677 return false;
2678 }
2679 return true;
2680 }
2681
2682 static bool GCPreserveCode(JSContext* cx, unsigned argc, Value* vp) {
2683 CallArgs args = CallArgsFromVp(argc, vp);
2684
2685 if (args.length() != 0) {
2686 RootedObject callee(cx, &args.callee());
2687 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
2688 return false;
2689 }
2690
2691 cx->runtime()->gc.setAlwaysPreserveCode();
2692
2693 args.rval().setUndefined();
2694 return true;
2695 }
2696
2697 #ifdef JS_GC_ZEAL
2698
2699 static bool ParseGCZealMode(JSContext* cx, const CallArgs& args,
2700 js::gc::GCRuntime::ZealSettings* zeal) {
2701 JSString* modestr = ToString(cx, args.get(0));
2702 if (!modestr) {
2703 return false;
2704 }
2705
2706 UniqueChars mode = EncodeLatin1(cx, modestr);
2707 if (!mode) {
2708 return false;
2709 }
2710 bool invalid;
2711 if (!cx->runtime()->gc.parseZeal(mode.get(), strlen(mode.get()), zeal,
2712 &invalid)) {
2713 js::ReportOutOfMemory(cx);
2714 return false;
2715 }
2716 if (invalid) {
2717 JS_ReportErrorASCII(cx, "invalid gczeal argument");
2718 return false;
2719 }
2720
2721 return true;
2722 }
2723
2724 static bool GCZeal(JSContext* cx, unsigned argc, Value* vp) {
2725 CallArgs args = CallArgsFromVp(argc, vp);
2726
2727 if (args.length() > 2) {
2728 RootedObject callee(cx, &args.callee());
2729 ReportUsageErrorASCII(cx, callee, "Too many arguments");
2730 return false;
2731 }
2732
2733 if (args.length() == 0) {
2734 uint32_t zealBits, unused1, unused2;
2735 cx->runtime()->gc.getZealBits(&zealBits, &unused1, &unused2);
2736 args.rval().setNumber(zealBits);
2737 return true;
2738 }
2739
2740 js::gc::GCRuntime::ZealSettings zeal;
2741 if (!ParseGCZealMode(cx, args, &zeal)) {
2742 return false;
2743 }
2744
2745 Maybe<uint32_t> forceFrequency;
2746 if (args.length() >= 2) {
2747 uint32_t frequency;
2748 if (!ToUint32(cx, args.get(1), &frequency)) {
2749 return false;
2750 }
2751 forceFrequency.emplace(frequency);
2752 }
2753
2754 for (auto [mode, frequency] : zeal) {
2755 JS::SetGCZeal(cx, mode, forceFrequency.valueOr(frequency));
2756 }
2757
2758 args.rval().setUndefined();
2759 return true;
2760 }
2761
2762 static bool UnsetGCZeal(JSContext* cx, unsigned argc, Value* vp) {
2763 CallArgs args = CallArgsFromVp(argc, vp);
2764
2765 if (args.length() > 1) {
2766 RootedObject callee(cx, &args.callee());
2767 ReportUsageErrorASCII(cx, callee, "Too many arguments");
2768 return false;
2769 }
2770
2771 js::gc::GCRuntime::ZealSettings zeal;
2772 if (!ParseGCZealMode(cx, args, &zeal)) {
2773 return false;
2774 }
2775
2776 for (auto [mode, _frequency] : zeal) {
2777 JS::UnsetGCZeal(cx, mode);
2778 }
2779
2780 args.rval().setUndefined();
2781 return true;
2782 }
2783
2784 static bool ScheduleGC(JSContext* cx, unsigned argc, Value* vp) {
2785 CallArgs args = CallArgsFromVp(argc, vp);
2786
2787 if (args.length() > 1) {
2788 RootedObject callee(cx, &args.callee());
2789 ReportUsageErrorASCII(cx, callee, "Too many arguments");
2790 return false;
2791 }
2792
2793 if (args.length() == 0) {
2794 /* Fetch next zeal trigger only. */
2795 } else if (args[0].isNumber()) {
2796 /* Schedule a GC to happen after |arg| allocations. */
2797 JS::ScheduleGC(cx, std::max(int(args[0].toNumber()), 0));
2798 } else {
2799 RootedObject callee(cx, &args.callee());
2800 ReportUsageErrorASCII(cx, callee, "Bad argument - expecting number");
2801 return false;
2802 }
2803
2804 uint32_t zealBits;
2805 uint32_t freq;
2806 uint32_t next;
2807 JS::GetGCZealBits(cx, &zealBits, &freq, &next);
2808 args.rval().setInt32(next);
2809 return true;
2810 }
2811
2812 static bool SelectForGC(JSContext* cx, unsigned argc, Value* vp) {
2813 CallArgs args = CallArgsFromVp(argc, vp);
2814
2815 /*
2816 * The selectedForMarking set is intended to be manually marked at slice
2817 * start to detect missing pre-barriers. It is invalid for nursery things
2818 * to be in the set, so evict the nursery before adding items.
2819 */
2820 cx->runtime()->gc.evictNursery();
2821
2822 for (unsigned i = 0; i < args.length(); i++) {
2823 if (args[i].isObject()) {
2824 if (!cx->runtime()->gc.selectForMarking(&args[i].toObject())) {
2825 ReportOutOfMemory(cx);
2826 return false;
2827 }
2828 }
2829 }
2830
2831 args.rval().setUndefined();
2832 return true;
2833 }
2834
2835 static bool VerifyPreBarriers(JSContext* cx, unsigned argc, Value* vp) {
2836 CallArgs args = CallArgsFromVp(argc, vp);
2837
2838 if (args.length() > 0) {
2839 RootedObject callee(cx, &args.callee());
2840 ReportUsageErrorASCII(cx, callee, "Too many arguments");
2841 return false;
2842 }
2843
2844 gc::VerifyBarriers(cx->runtime(), gc::PreBarrierVerifier);
2845 args.rval().setUndefined();
2846 return true;
2847 }
2848
2849 static bool VerifyPostBarriers(JSContext* cx, unsigned argc, Value* vp) {
2850 CallArgs args = CallArgsFromVp(argc, vp);
2851
2852 if (args.length()) {
2853 RootedObject callee(cx, &args.callee());
2854 ReportUsageErrorASCII(cx, callee, "Too many arguments");
2855 return false;
2856 }
2857
2858 gc::VerifyBarriers(cx->runtime(), gc::PostBarrierVerifier);
2859 args.rval().setUndefined();
2860 return true;
2861 }
2862
2863 static bool CurrentGC(JSContext* cx, unsigned argc, Value* vp) {
2864 CallArgs args = CallArgsFromVp(argc, vp);
2865
2866 if (args.length() != 0) {
2867 RootedObject callee(cx, &args.callee());
2868 ReportUsageErrorASCII(cx, callee, "Too many arguments");
2869 return false;
2870 }
2871
2872 RootedObject result(cx, JS_NewPlainObject(cx));
2873 if (!result) {
2874 return false;
2875 }
2876
2877 js::gc::GCRuntime& gc = cx->runtime()->gc;
2878 const char* state = StateName(gc.state());
2879
2880 RootedString str(cx, JS_NewStringCopyZ(cx, state));
2881 if (!str) {
2882 return false;
2883 }
2884 RootedValue val(cx, StringValue(str));
2885 if (!JS_DefineProperty(cx, result, "incrementalState", val,
2886 JSPROP_ENUMERATE)) {
2887 return false;
2888 }
2889
2890 if (gc.state() == js::gc::State::Sweep) {
2891 val = Int32Value(gc.getCurrentSweepGroupIndex());
2892 if (!JS_DefineProperty(cx, result, "sweepGroup", val, JSPROP_ENUMERATE)) {
2893 return false;
2894 }
2895 }
2896
2897 val = BooleanValue(gc.isIncrementalGCInProgress() && gc.isShrinkingGC());
2898 if (!JS_DefineProperty(cx, result, "isShrinking", val, JSPROP_ENUMERATE)) {
2899 return false;
2900 }
2901
2902 val = Int32Value(gc.gcNumber());
2903 if (!JS_DefineProperty(cx, result, "number", val, JSPROP_ENUMERATE)) {
2904 return false;
2905 }
2906
2907 val = Int32Value(gc.minorGCCount());
2908 if (!JS_DefineProperty(cx, result, "minorCount", val, JSPROP_ENUMERATE)) {
2909 return false;
2910 }
2911
2912 val = Int32Value(gc.majorGCCount());
2913 if (!JS_DefineProperty(cx, result, "majorCount", val, JSPROP_ENUMERATE)) {
2914 return false;
2915 }
2916
2917 val = BooleanValue(gc.isFullGc());
2918 if (!JS_DefineProperty(cx, result, "isFull", val, JSPROP_ENUMERATE)) {
2919 return false;
2920 }
2921
2922 val = BooleanValue(gc.isCompactingGc());
2923 if (!JS_DefineProperty(cx, result, "isCompacting", val, JSPROP_ENUMERATE)) {
2924 return false;
2925 }
2926
2927 # ifdef DEBUG
2928 val = Int32Value(gc.testMarkQueuePos());
2929 if (!JS_DefineProperty(cx, result, "queuePos", val, JSPROP_ENUMERATE)) {
2930 return false;
2931 }
2932 # endif
2933
2934 args.rval().setObject(*result);
2935 return true;
2936 }
2937
2938 static bool DeterministicGC(JSContext* cx, unsigned argc, Value* vp) {
2939 CallArgs args = CallArgsFromVp(argc, vp);
2940
2941 if (args.length() != 1) {
2942 RootedObject callee(cx, &args.callee());
2943 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
2944 return false;
2945 }
2946
2947 cx->runtime()->gc.setDeterministic(ToBoolean(args[0]));
2948 args.rval().setUndefined();
2949 return true;
2950 }
2951
2952 static bool DumpGCArenaInfo(JSContext* cx, unsigned argc, Value* vp) {
2953 CallArgs args = CallArgsFromVp(argc, vp);
2954 js::gc::DumpArenaInfo();
2955 args.rval().setUndefined();
2956 return true;
2957 }
2958
2959 static bool SetMarkStackLimit(JSContext* cx, unsigned argc, Value* vp) {
2960 CallArgs args = CallArgsFromVp(argc, vp);
2961 if (args.length() != 1) {
2962 RootedObject callee(cx, &args.callee());
2963 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
2964 return false;
2965 }
2966
2967 int32_t value;
2968 if (!ToInt32(cx, args[0], &value) || value <= 0) {
2969 JS_ReportErrorASCII(cx, "Bad argument to SetMarkStackLimit");
2970 return false;
2971 }
2972
2973 if (JS::IsIncrementalGCInProgress(cx)) {
2974 JS_ReportErrorASCII(
2975 cx, "Attempt to set markStackLimit while a GC is in progress");
2976 return false;
2977 }
2978
2979 JSRuntime* runtime = cx->runtime();
2980 AutoLockGC lock(runtime);
2981 runtime->gc.setMarkStackLimit(value, lock);
2982 args.rval().setUndefined();
2983 return true;
2984 }
2985
2986 #endif /* JS_GC_ZEAL */
2987
2988 static bool SetMallocMaxDirtyPageModifier(JSContext* cx, unsigned argc,
2989 Value* vp) {
2990 CallArgs args = CallArgsFromVp(argc, vp);
2991 if (args.length() != 1) {
2992 RootedObject callee(cx, &args.callee());
2993 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
2994 return false;
2995 }
2996
2997 constexpr int32_t MinSupportedValue = -5;
2998 constexpr int32_t MaxSupportedValue = 16;
2999
3000 int32_t value;
3001 if (!ToInt32(cx, args[0], &value)) {
3002 return false;
3003 }
3004 if (value < MinSupportedValue || value > MaxSupportedValue) {
3005 JS_ReportErrorASCII(cx, "Bad argument to setMallocMaxDirtyPageModifier");
3006 return false;
3007 }
3008
3009 #ifdef MOZ_MEMORY
3010 moz_set_max_dirty_page_modifier(value);
3011 #endif
3012
3013 args.rval().setUndefined();
3014 return true;
3015 }
3016
3017 static bool GCState(JSContext* cx, unsigned argc, Value* vp) {
3018 CallArgs args = CallArgsFromVp(argc, vp);
3019
3020 if (args.length() > 1) {
3021 RootedObject callee(cx, &args.callee());
3022 ReportUsageErrorASCII(cx, callee, "Too many arguments");
3023 return false;
3024 }
3025
3026 const char* state;
3027
3028 if (args.length() == 1) {
3029 if (!args[0].isObject()) {
3030 RootedObject callee(cx, &args.callee());
3031 ReportUsageErrorASCII(cx, callee, "Expected object");
3032 return false;
3033 }
3034
3035 JSObject* obj = UncheckedUnwrap(&args[0].toObject());
3036 state = gc::StateName(obj->zone()->gcState());
3037 } else {
3038 state = gc::StateName(cx->runtime()->gc.state());
3039 }
3040
3041 return ReturnStringCopy(cx, args, state);
3042 }
3043
3044 static bool ScheduleZoneForGC(JSContext* cx, unsigned argc, Value* vp) {
3045 CallArgs args = CallArgsFromVp(argc, vp);
3046
3047 if (args.length() != 1) {
3048 RootedObject callee(cx, &args.callee());
3049 ReportUsageErrorASCII(cx, callee, "Expecting a single argument");
3050 return false;
3051 }
3052
3053 if (args[0].isObject()) {
3054 // Ensure that |zone| is collected during the next GC.
3055 Zone* zone = UncheckedUnwrap(&args[0].toObject())->zone();
3056 PrepareZoneForGC(cx, zone);
3057 } else if (args[0].isString()) {
3058 // This allows us to schedule the atoms zone for GC.
3059 Zone* zone = args[0].toString()->zoneFromAnyThread();
3060 if (!CurrentThreadCanAccessZone(zone)) {
3061 RootedObject callee(cx, &args.callee());
3062 ReportUsageErrorASCII(cx, callee, "Specified zone not accessible for GC");
3063 return false;
3064 }
3065 PrepareZoneForGC(cx, zone);
3066 } else {
3067 RootedObject callee(cx, &args.callee());
3068 ReportUsageErrorASCII(cx, callee,
3069 "Bad argument - expecting object or string");
3070 return false;
3071 }
3072
3073 args.rval().setUndefined();
3074 return true;
3075 }
3076
3077 static bool StartGC(JSContext* cx, unsigned argc, Value* vp) {
3078 CallArgs args = CallArgsFromVp(argc, vp);
3079
3080 if (args.length() > 2) {
3081 RootedObject callee(cx, &args.callee());
3082 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
3083 return false;
3084 }
3085
3086 auto budget = SliceBudget::unlimited();
3087 if (args.length() >= 1) {
3088 uint32_t work = 0;
3089 if (!ToUint32(cx, args[0], &work)) {
3090 return false;
3091 }
3092 budget = SliceBudget(WorkBudget(work));
3093 }
3094
3095 bool shrinking = false;
3096 if (args.length() >= 2) {
3097 Value arg = args[1];
3098 if (arg.isString()) {
3099 if (!JS_StringEqualsLiteral(cx, arg.toString(), "shrinking",
3100 &shrinking)) {
3101 return false;
3102 }
3103 }
3104 }
3105
3106 JSRuntime* rt = cx->runtime();
3107 if (rt->gc.isIncrementalGCInProgress()) {
3108 RootedObject callee(cx, &args.callee());
3109 JS_ReportErrorASCII(cx, "Incremental GC already in progress");
3110 return false;
3111 }
3112
3113 JS::GCOptions options =
3114 shrinking ? JS::GCOptions::Shrink : JS::GCOptions::Normal;
3115 rt->gc.startDebugGC(options, budget);
3116
3117 args.rval().setUndefined();
3118 return true;
3119 }
3120
3121 static bool FinishGC(JSContext* cx, unsigned argc, Value* vp) {
3122 CallArgs args = CallArgsFromVp(argc, vp);
3123
3124 if (args.length() > 0) {
3125 RootedObject callee(cx, &args.callee());
3126 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
3127 return false;
3128 }
3129
3130 JSRuntime* rt = cx->runtime();
3131 if (rt->gc.isIncrementalGCInProgress()) {
3132 rt->gc.finishGC(JS::GCReason::DEBUG_GC);
3133 }
3134
3135 args.rval().setUndefined();
3136 return true;
3137 }
3138
3139 static bool GCSlice(JSContext* cx, unsigned argc, Value* vp) {
3140 CallArgs args = CallArgsFromVp(argc, vp);
3141
3142 if (args.length() > 2) {
3143 RootedObject callee(cx, &args.callee());
3144 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
3145 return false;
3146 }
3147
3148 auto budget = SliceBudget::unlimited();
3149 if (args.length() >= 1) {
3150 uint32_t work = 0;
3151 if (!ToUint32(cx, args[0], &work)) {
3152 return false;
3153 }
3154 budget = SliceBudget(WorkBudget(work));
3155 }
3156
3157 bool dontStart = false;
3158 if (args.get(1).isObject()) {
3159 RootedObject options(cx, &args[1].toObject());
3160 RootedValue v(cx);
3161 if (!JS_GetProperty(cx, options, "dontStart", &v)) {
3162 return false;
3163 }
3164 dontStart = ToBoolean(v);
3165 }
3166
3167 JSRuntime* rt = cx->runtime();
3168 if (rt->gc.isIncrementalGCInProgress()) {
3169 rt->gc.debugGCSlice(budget);
3170 } else if (!dontStart) {
3171 rt->gc.startDebugGC(JS::GCOptions::Normal, budget);
3172 }
3173
3174 args.rval().setUndefined();
3175 return true;
3176 }
3177
3178 static bool AbortGC(JSContext* cx, unsigned argc, Value* vp) {
3179 CallArgs args = CallArgsFromVp(argc, vp);
3180
3181 if (args.length() != 0) {
3182 RootedObject callee(cx, &args.callee());
3183 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
3184 return false;
3185 }
3186
3187 JS::AbortIncrementalGC(cx);
3188 args.rval().setUndefined();
3189 return true;
3190 }
3191
3192 static bool FullCompartmentChecks(JSContext* cx, unsigned argc, Value* vp) {
3193 CallArgs args = CallArgsFromVp(argc, vp);
3194
3195 if (args.length() != 1) {
3196 RootedObject callee(cx, &args.callee());
3197 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
3198 return false;
3199 }
3200
3201 cx->runtime()->gc.setFullCompartmentChecks(ToBoolean(args[0]));
3202 args.rval().setUndefined();
3203 return true;
3204 }
3205
3206 static bool NondeterministicGetWeakMapKeys(JSContext* cx, unsigned argc,
3207 Value* vp) {
3208 CallArgs args = CallArgsFromVp(argc, vp);
3209
3210 if (args.length() != 1) {
3211 RootedObject callee(cx, &args.callee());
3212 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
3213 return false;
3214 }
3215 if (!args[0].isObject()) {
3216 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3217 JSMSG_NOT_EXPECTED_TYPE,
3218 "nondeterministicGetWeakMapKeys", "WeakMap",
3219 InformalValueTypeName(args[0]));
3220 return false;
3221 }
3222 RootedObject arr(cx);
3223 RootedObject mapObj(cx, &args[0].toObject());
3224 if (!JS_NondeterministicGetWeakMapKeys(cx, mapObj, &arr)) {
3225 return false;
3226 }
3227 if (!arr) {
3228 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3229 JSMSG_NOT_EXPECTED_TYPE,
3230 "nondeterministicGetWeakMapKeys", "WeakMap",
3231 args[0].toObject().getClass()->name);
3232 return false;
3233 }
3234 args.rval().setObject(*arr);
3235 return true;
3236 }
3237
3238 class HasChildTracer final : public JS::CallbackTracer {
3239 RootedValue child_;
3240 bool found_;
3241
3242 void onChild(JS::GCCellPtr thing, const char* name) override {
3243 if (thing.asCell() == child_.toGCThing()) {
3244 found_ = true;
3245 }
3246 }
3247
3248 public:
3249 HasChildTracer(JSContext* cx, HandleValue child)
3250 : JS::CallbackTracer(cx, JS::TracerKind::Callback,
3251 JS::WeakMapTraceAction::TraceKeysAndValues),
3252 child_(cx, child),
3253 found_(false) {}
3254
3255 bool found() const { return found_; }
3256 };
3257
3258 static bool HasChild(JSContext* cx, unsigned argc, Value* vp) {
3259 CallArgs args = CallArgsFromVp(argc, vp);
3260 RootedValue parent(cx, args.get(0));
3261 RootedValue child(cx, args.get(1));
3262
3263 if (!parent.isGCThing() || !child.isGCThing()) {
3264 args.rval().setBoolean(false);
3265 return true;
3266 }
3267
3268 HasChildTracer trc(cx, child);
3269 TraceChildren(&trc, JS::GCCellPtr(parent.toGCThing(), parent.traceKind()));
3270 args.rval().setBoolean(trc.found());
3271 return true;
3272 }
3273
3274 static bool SetSavedStacksRNGState(JSContext* cx, unsigned argc, Value* vp) {
3275 CallArgs args = CallArgsFromVp(argc, vp);
3276 if (!args.requireAtLeast(cx, "setSavedStacksRNGState", 1)) {
3277 return false;
3278 }
3279
3280 int32_t seed;
3281 if (!ToInt32(cx, args[0], &seed)) {
3282 return false;
3283 }
3284
3285 // Either one or the other of the seed arguments must be non-zero;
3286 // make this true no matter what value 'seed' has.
3287 cx->realm()->savedStacks().setRNGState(seed, (seed + 1) * 33);
3288 return true;
3289 }
3290
3291 static bool GetSavedFrameCount(JSContext* cx, unsigned argc, Value* vp) {
3292 CallArgs args = CallArgsFromVp(argc, vp);
3293 args.rval().setNumber(cx->realm()->savedStacks().count());
3294 return true;
3295 }
3296
3297 static bool ClearSavedFrames(JSContext* cx, unsigned argc, Value* vp) {
3298 CallArgs args = CallArgsFromVp(argc, vp);
3299
3300 js::SavedStacks& savedStacks = cx->realm()->savedStacks();
3301 savedStacks.clear();
3302
3303 for (ActivationIterator iter(cx); !iter.done(); ++iter) {
3304 iter->clearLiveSavedFrameCache();
3305 }
3306
3307 args.rval().setUndefined();
3308 return true;
3309 }
3310
3311 static bool SaveStack(JSContext* cx, unsigned argc, Value* vp) {
3312 CallArgs args = CallArgsFromVp(argc, vp);
3313
3314 JS::StackCapture capture((JS::AllFrames()));
3315 if (args.length() >= 1) {
3316 double maxDouble;
3317 if (!ToNumber(cx, args[0], &maxDouble)) {
3318 return false;
3319 }
3320 if (std::isnan(maxDouble) || maxDouble < 0 || maxDouble > UINT32_MAX) {
3321 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[0],
3322 nullptr, "not a valid maximum frame count");
3323 return false;
3324 }
3325 uint32_t max = uint32_t(maxDouble);
3326 if (max > 0) {
3327 capture = JS::StackCapture(JS::MaxFrames(max));
3328 }
3329 }
3330
3331 RootedObject compartmentObject(cx);
3332 if (args.length() >= 2) {
3333 if (!args[1].isObject()) {
3334 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[0],
3335 nullptr, "not an object");
3336 return false;
3337 }
3338 compartmentObject = UncheckedUnwrap(&args[1].toObject());
3339 if (!compartmentObject) {
3340 return false;
3341 }
3342 }
3343
3344 RootedObject stack(cx);
3345 {
3346 Maybe<AutoRealm> ar;
3347 if (compartmentObject) {
3348 ar.emplace(cx, compartmentObject);
3349 }
3350 if (!JS::CaptureCurrentStack(cx, &stack, std::move(capture))) {
3351 return false;
3352 }
3353 }
3354
3355 if (stack && !cx->compartment()->wrap(cx, &stack)) {
3356 return false;
3357 }
3358
3359 args.rval().setObjectOrNull(stack);
3360 return true;
3361 }
3362
3363 static bool CaptureFirstSubsumedFrame(JSContext* cx, unsigned argc,
3364 JS::Value* vp) {
3365 CallArgs args = CallArgsFromVp(argc, vp);
3366 if (!args.requireAtLeast(cx, "captureFirstSubsumedFrame", 1)) {
3367 return false;
3368 }
3369
3370 if (!args[0].isObject()) {
3371 JS_ReportErrorASCII(cx, "The argument must be an object");
3372 return false;
3373 }
3374
3375 RootedObject obj(cx, &args[0].toObject());
3376 obj = CheckedUnwrapStatic(obj);
3377 if (!obj) {
3378 JS_ReportErrorASCII(cx, "Denied permission to object.");
3379 return false;
3380 }
3381
3382 JS::StackCapture capture(
3383 JS::FirstSubsumedFrame(cx, obj->nonCCWRealm()->principals()));
3384 if (args.length() > 1) {
3385 capture.as<JS::FirstSubsumedFrame>().ignoreSelfHosted =
3386 JS::ToBoolean(args[1]);
3387 }
3388
3389 JS::RootedObject capturedStack(cx);
3390 if (!JS::CaptureCurrentStack(cx, &capturedStack, std::move(capture))) {
3391 return false;
3392 }
3393
3394 args.rval().setObjectOrNull(capturedStack);
3395 return true;
3396 }
3397
3398 static bool CallFunctionFromNativeFrame(JSContext* cx, unsigned argc,
3399 Value* vp) {
3400 CallArgs args = CallArgsFromVp(argc, vp);
3401
3402 if (args.length() != 1) {
3403 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
3404 return false;
3405 }
3406 if (!args[0].isObject() || !IsCallable(args[0])) {
3407 JS_ReportErrorASCII(cx, "The first argument should be a function.");
3408 return false;
3409 }
3410
3411 RootedObject function(cx, &args[0].toObject());
3412 return Call(cx, UndefinedHandleValue, function, JS::HandleValueArray::empty(),
3413 args.rval());
3414 }
3415
3416 static bool CallFunctionWithAsyncStack(JSContext* cx, unsigned argc,
3417 Value* vp) {
3418 CallArgs args = CallArgsFromVp(argc, vp);
3419
3420 if (args.length() != 3) {
3421 JS_ReportErrorASCII(cx, "The function takes exactly three arguments.");
3422 return false;
3423 }
3424 if (!args[0].isObject() || !IsCallable(args[0])) {
3425 JS_ReportErrorASCII(cx, "The first argument should be a function.");
3426 return false;
3427 }
3428 if (!args[1].isObject() || !args[1].toObject().is<SavedFrame>()) {
3429 JS_ReportErrorASCII(cx, "The second argument should be a SavedFrame.");
3430 return false;
3431 }
3432 if (!args[2].isString() || args[2].toString()->empty()) {
3433 JS_ReportErrorASCII(cx, "The third argument should be a non-empty string.");
3434 return false;
3435 }
3436
3437 RootedObject function(cx, &args[0].toObject());
3438 RootedObject stack(cx, &args[1].toObject());
3439 RootedString asyncCause(cx, args[2].toString());
3440 UniqueChars utf8Cause = JS_EncodeStringToUTF8(cx, asyncCause);
3441 if (!utf8Cause) {
3442 MOZ_ASSERT(cx->isExceptionPending());
3443 return false;
3444 }
3445
3446 JS::AutoSetAsyncStackForNewCalls sas(
3447 cx, stack, utf8Cause.get(),
3448 JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::EXPLICIT);
3449 return Call(cx, UndefinedHandleValue, function, JS::HandleValueArray::empty(),
3450 args.rval());
3451 }
3452
3453 static bool EnableTrackAllocations(JSContext* cx, unsigned argc, Value* vp) {
3454 SetAllocationMetadataBuilder(cx, &SavedStacks::metadataBuilder);
3455 return true;
3456 }
3457
3458 static bool DisableTrackAllocations(JSContext* cx, unsigned argc, Value* vp) {
3459 SetAllocationMetadataBuilder(cx, nullptr);
3460 return true;
3461 }
3462
3463 static bool SetTestFilenameValidationCallback(JSContext* cx, unsigned argc,
3464 Value* vp) {
3465 CallArgs args = CallArgsFromVp(argc, vp);
3466
3467 // Accept all filenames that start with "safe". In system code also accept
3468 // filenames starting with "system".
3469 auto testCb = [](JSContext* cx, const char* filename) -> bool {
3470 if (strstr(filename, "safe") == filename) {
3471 return true;
3472 }
3473 if (cx->realm()->isSystem() && strstr(filename, "system") == filename) {
3474 return true;
3475 }
3476
3477 return false;
3478 };
3479 JS::SetFilenameValidationCallback(testCb);
3480
3481 args.rval().setUndefined();
3482 return true;
3483 }
3484
3485 static JSAtom* GetPropertiesAddedName(JSContext* cx) {
3486 const char* propName = "_propertiesAdded";
3487 return Atomize(cx, propName, strlen(propName));
3488 }
3489
3490 static bool NewObjectWithAddPropertyHook(JSContext* cx, unsigned argc,
3491 Value* vp) {
3492 CallArgs args = CallArgsFromVp(argc, vp);
3493
3494 auto addPropHook = [](JSContext* cx, HandleObject obj, HandleId id,
3495 HandleValue v) -> bool {
3496 Rooted<JSAtom*> propName(cx, GetPropertiesAddedName(cx));
3497 if (!propName) {
3498 return false;
3499 }
3500 // Don't do anything if we're adding the _propertiesAdded property.
3501 RootedId propId(cx, AtomToId(propName));
3502 if (id == propId) {
3503 return true;
3504 }
3505 // Increment _propertiesAdded.
3506 RootedValue val(cx);
3507 if (!JS_GetPropertyById(cx, obj, propId, &val)) {
3508 return false;
3509 }
3510 if (!val.isInt32() || val.toInt32() == INT32_MAX) {
3511 return true;
3512 }
3513 val.setInt32(val.toInt32() + 1);
3514 return JS_DefinePropertyById(cx, obj, propId, val, 0);
3515 };
3516
3517 static const JSClassOps classOps = {
3518 addPropHook, // addProperty
3519 nullptr, // delProperty
3520 nullptr, // enumerate
3521 nullptr, // newEnumerate
3522 nullptr, // resolve
3523 nullptr, // mayResolve
3524 nullptr, // finalize
3525 nullptr, // call
3526 nullptr, // construct
3527 nullptr, // trace
3528 };
3529 static const JSClass cls = {
3530 "ObjectWithAddPropHook",
3531 0,
3532 &classOps,
3533 };
3534
3535 RootedObject obj(cx, JS_NewObject(cx, &cls));
3536 if (!obj) {
3537 return false;
3538 }
3539
3540 // Initialize _propertiesAdded to 0.
3541 Rooted<JSAtom*> propName(cx, GetPropertiesAddedName(cx));
3542 if (!propName) {
3543 return false;
3544 }
3545 RootedId propId(cx, AtomToId(propName));
3546 RootedValue val(cx, Int32Value(0));
3547 if (!JS_DefinePropertyById(cx, obj, propId, val, 0)) {
3548 return false;
3549 }
3550
3551 args.rval().setObject(*obj);
3552 return true;
3553 }
3554
3555 static bool NewObjectWithCallHook(JSContext* cx, unsigned argc, Value* vp) {
3556 CallArgs args = CallArgsFromVp(argc, vp);
3557
3558 static auto hookShared = [](JSContext* cx, CallArgs& args) {
3559 Rooted<PlainObject*> obj(cx, NewPlainObject(cx));
3560 if (!obj) {
3561 return false;
3562 }
3563
3564 // Define |this|. We can't expose the MagicValue to JS, so we use
3565 // "<is_constructing>" in that case.
3566 Rooted<Value> thisv(cx, args.thisv());
3567 if (thisv.isMagic(JS_IS_CONSTRUCTING)) {
3568 JSString* str = NewStringCopyZ<CanGC>(cx, "<is_constructing>");
3569 if (!str) {
3570 return false;
3571 }
3572 thisv.setString(str);
3573 }
3574 if (!DefineDataProperty(cx, obj, cx->names().this_, thisv,
3575 JSPROP_ENUMERATE)) {
3576 return false;
3577 }
3578
3579 // Define |callee|.
3580 if (!DefineDataProperty(cx, obj, cx->names().callee, args.calleev(),
3581 JSPROP_ENUMERATE)) {
3582 return false;
3583 }
3584
3585 // Define |arguments| array.
3586 Rooted<ArrayObject*> arr(
3587 cx, NewDenseCopiedArray(cx, args.length(), args.array()));
3588 if (!arr) {
3589 return false;
3590 }
3591 Rooted<Value> arrVal(cx, ObjectValue(*arr));
3592 if (!DefineDataProperty(cx, obj, cx->names().arguments, arrVal,
3593 JSPROP_ENUMERATE)) {
3594 return false;
3595 }
3596
3597 // Define |newTarget| if constructing.
3598 if (args.isConstructing()) {
3599 const char* propName = "newTarget";
3600 Rooted<JSAtom*> name(cx, Atomize(cx, propName, strlen(propName)));
3601 if (!name) {
3602 return false;
3603 }
3604 Rooted<PropertyKey> key(cx, NameToId(name->asPropertyName()));
3605 if (!DefineDataProperty(cx, obj, key, args.newTarget(),
3606 JSPROP_ENUMERATE)) {
3607 return false;
3608 }
3609 }
3610
3611 args.rval().setObject(*obj);
3612 return true;
3613 };
3614
3615 static auto callHook = [](JSContext* cx, unsigned argc, Value* vp) {
3616 CallArgs args = CallArgsFromVp(argc, vp);
3617 MOZ_ASSERT(!args.isConstructing());
3618 return hookShared(cx, args);
3619 };
3620 static auto constructHook = [](JSContext* cx, unsigned argc, Value* vp) {
3621 CallArgs args = CallArgsFromVp(argc, vp);
3622 MOZ_ASSERT(args.isConstructing());
3623 return hookShared(cx, args);
3624 };
3625
3626 static const JSClassOps classOps = {
3627 nullptr, // addProperty
3628 nullptr, // delProperty
3629 nullptr, // enumerate
3630 nullptr, // newEnumerate
3631 nullptr, // resolve
3632 nullptr, // mayResolve
3633 nullptr, // finalize
3634 callHook, // call
3635 constructHook, // construct
3636 nullptr, // trace
3637 };
3638 static const JSClass cls = {
3639 "ObjectWithCallHook",
3640 0,
3641 &classOps,
3642 };
3643
3644 Rooted<JSObject*> obj(cx, JS_NewObject(cx, &cls));
3645 if (!obj) {
3646 return false;
3647 }
3648
3649 args.rval().setObject(*obj);
3650 return true;
3651 }
3652
3653 static constexpr JSClass ObjectWithManyReservedSlotsClass = {
3654 "ObjectWithManyReservedSlots",
3655 JSCLASS_HAS_RESERVED_SLOTS(40),
3656 };
3657
3658 static bool NewObjectWithManyReservedSlots(JSContext* cx, unsigned argc,
3659 Value* vp) {
3660 CallArgs args = CallArgsFromVp(argc, vp);
3661
3662 static constexpr size_t NumReservedSlots =
3663 JSCLASS_RESERVED_SLOTS(&ObjectWithManyReservedSlotsClass);
3664 static_assert(NumReservedSlots > NativeObject::MAX_FIXED_SLOTS);
3665
3666 RootedObject obj(cx, JS_NewObject(cx, &ObjectWithManyReservedSlotsClass));
3667 if (!obj) {
3668 return false;
3669 }
3670
3671 for (size_t i = 0; i < NumReservedSlots; i++) {
3672 JS_SetReservedSlot(obj, i, Int32Value(i));
3673 }
3674
3675 args.rval().setObject(*obj);
3676 return true;
3677 }
3678
3679 static bool CheckObjectWithManyReservedSlots(JSContext* cx, unsigned argc,
3680 Value* vp) {
3681 CallArgs args = CallArgsFromVp(argc, vp);
3682
3683 if (args.length() != 1 || !args[0].isObject() ||
3684 args[0].toObject().getClass() != &ObjectWithManyReservedSlotsClass) {
3685 JS_ReportErrorASCII(cx,
3686 "Expected object from newObjectWithManyReservedSlots");
3687 return false;
3688 }
3689
3690 JSObject* obj = &args[0].toObject();
3691
3692 static constexpr size_t NumReservedSlots =
3693 JSCLASS_RESERVED_SLOTS(&ObjectWithManyReservedSlotsClass);
3694
3695 for (size_t i = 0; i < NumReservedSlots; i++) {
3696 MOZ_RELEASE_ASSERT(JS::GetReservedSlot(obj, i).toInt32() == int32_t(i));
3697 }
3698
3699 args.rval().setUndefined();
3700 return true;
3701 }
3702
3703 static bool GetWatchtowerLog(JSContext* cx, unsigned argc, Value* vp) {
3704 CallArgs args = CallArgsFromVp(argc, vp);
3705
3706 Rooted<GCVector<Value>> values(cx, GCVector<Value>(cx));
3707
3708 if (auto* log = cx->runtime()->watchtowerTestingLog.ref().get()) {
3709 Rooted<JSObject*> elem(cx);
3710 for (PlainObject* obj : *log) {
3711 elem = obj;
3712 if (!cx->compartment()->wrap(cx, &elem)) {
3713 return false;
3714 }
3715 if (!values.append(ObjectValue(*elem))) {
3716 return false;
3717 }
3718 }
3719 log->clearAndFree();
3720 }
3721
3722 ArrayObject* arr = NewDenseCopiedArray(cx, values.length(), values.begin());
3723 if (!arr) {
3724 return false;
3725 }
3726
3727 args.rval().setObject(*arr);
3728 return true;
3729 }
3730
3731 static bool AddWatchtowerTarget(JSContext* cx, unsigned argc, Value* vp) {
3732 CallArgs args = CallArgsFromVp(argc, vp);
3733
3734 if (args.length() != 1 || !args[0].isObject()) {
3735 JS_ReportErrorASCII(cx, "Expected a single object argument.");
3736 return false;
3737 }
3738
3739 if (!cx->runtime()->watchtowerTestingLog.ref()) {
3740 auto vec = cx->make_unique<JSRuntime::RootedPlainObjVec>(cx);
3741 if (!vec) {
3742 return false;
3743 }
3744 cx->runtime()->watchtowerTestingLog = std::move(vec);
3745 }
3746
3747 RootedObject obj(cx, &args[0].toObject());
3748 if (!JSObject::setUseWatchtowerTestingLog(cx, obj)) {
3749 return false;
3750 }
3751
3752 args.rval().setUndefined();
3753 return true;
3754 }
3755
3756 struct TestExternalString : public JSExternalStringCallbacks {
3757 void finalize(JS::Latin1Char* chars) const override { js_free(chars); }
3758 void finalize(char16_t* chars) const override { js_free(chars); }
3759 size_t sizeOfBuffer(const JS::Latin1Char* chars,
3760 mozilla::MallocSizeOf mallocSizeOf) const override {
3761 return mallocSizeOf(chars);
3762 }
3763 size_t sizeOfBuffer(const char16_t* chars,
3764 mozilla::MallocSizeOf mallocSizeOf) const override {
3765 return mallocSizeOf(chars);
3766 }
3767 };
3768
3769 static constexpr TestExternalString TestExternalStringCallbacks;
3770
3771 static bool NewString(JSContext* cx, unsigned argc, Value* vp) {
3772 CallArgs args = CallArgsFromVp(argc, vp);
3773
3774 RootedString src(cx, ToString(cx, args.get(0)));
3775 if (!src) {
3776 return false;
3777 }
3778
3779 gc::Heap heap = gc::Heap::Default;
3780 bool wantTwoByte = false;
3781 bool forceExternal = false;
3782 bool maybeExternal = false;
3783 bool newStringBuffer = false;
3784 bool shareStringBuffer = false;
3785 uint32_t capacity = 0;
3786
3787 if (args.get(1).isObject()) {
3788 RootedObject options(cx, &args[1].toObject());
3789 RootedValue v(cx);
3790 bool requestTenured = false;
3791 struct BoolSetting {
3792 const char* name;
3793 bool* value;
3794 };
3795 for (auto [name, setting] :
3796 {BoolSetting{"tenured", &requestTenured},
3797 BoolSetting{"twoByte", &wantTwoByte},
3798 BoolSetting{"external", &forceExternal},
3799 BoolSetting{"maybeExternal", &maybeExternal},
3800 BoolSetting{"newStringBuffer", &newStringBuffer},
3801 BoolSetting{"shareStringBuffer", &shareStringBuffer}}) {
3802 if (!JS_GetProperty(cx, options, name, &v)) {
3803 return false;
3804 }
3805 *setting = ToBoolean(v); // false if not given (or otherwise undefined)
3806 }
3807 struct Uint32Setting {
3808 const char* name;
3809 uint32_t* value;
3810 };
3811 for (auto [name, setting] : {Uint32Setting{"capacity", &capacity}}) {
3812 if (!JS_GetProperty(cx, options, name, &v)) {
3813 return false;
3814 }
3815 int32_t i32;
3816 if (!ToInt32(cx, v, &i32)) {
3817 return false;
3818 }
3819 if (i32 < 0) {
3820 JS_ReportErrorASCII(cx, "nonnegative value required");
3821 return false;
3822 }
3823 *setting = static_cast<uint32_t>(i32);
3824 }
3825
3826 heap = requestTenured ? gc::Heap::Tenured : gc::Heap::Default;
3827 if (forceExternal || maybeExternal) {
3828 wantTwoByte = true;
3829 }
3830 unsigned kinds = forceExternal + maybeExternal + (capacity != 0) +
3831 newStringBuffer + shareStringBuffer;
3832 if (kinds > 1) {
3833 JS_ReportErrorASCII(cx,
3834 "external, capacity, and stringBuffer options can "
3835 "not be used at the same time");
3836 return false;
3837 }
3838 }
3839
3840 auto len = src->length();
3841 RootedString dest(cx);
3842
3843 if (forceExternal || maybeExternal) {
3844 auto buf = cx->make_pod_array<char16_t>(len);
3845 if (!buf) {
3846 return false;
3847 }
3848
3849 if (!JS_CopyStringChars(cx, mozilla::Range<char16_t>(buf.get(), len),
3850 src)) {
3851 return false;
3852 }
3853
3854 bool isExternal = true;
3855 if (forceExternal) {
3856 dest = JSExternalString::new_(cx, buf.get(), len,
3857 &TestExternalStringCallbacks);
3858 } else {
3859 dest = NewMaybeExternalString(
3860 cx, buf.get(), len, &TestExternalStringCallbacks, &isExternal, heap);
3861 }
3862 if (dest && isExternal) {
3863 (void)buf.release(); // Ownership was transferred.
3864 }
3865 } else if (shareStringBuffer) {
3866 if (!src->isLinear() || !src->asLinear().hasStringBuffer()) {
3867 JS_ReportErrorASCII(cx, "source string must have a string buffer");
3868 return false;
3869 }
3870 RefPtr<mozilla::StringBuffer> buffer = src->asLinear().stringBuffer();
3871 if (src->hasLatin1Chars()) {
3872 Rooted<JSString::OwnedChars<Latin1Char>> owned(cx, std::move(buffer),
3873 len);
3874 dest =
3875 JSLinearString::newValidLength<CanGC, Latin1Char>(cx, &owned, heap);
3876 } else {
3877 Rooted<JSString::OwnedChars<char16_t>> owned(cx, std::move(buffer), len);
3878 dest = JSLinearString::newValidLength<CanGC, char16_t>(cx, &owned, heap);
3879 }
3880 } else {
3881 AutoStableStringChars stable(cx);
3882 if (!wantTwoByte && src->hasLatin1Chars()) {
3883 if (!stable.init(cx, src)) {
3884 return false;
3885 }
3886 } else {
3887 if (!stable.initTwoByte(cx, src)) {
3888 return false;
3889 }
3890 }
3891 if (newStringBuffer) {
3892 auto allocString = [&](const auto* chars) -> JSLinearString* {
3893 using CharT =
3894 std::remove_const_t<std::remove_pointer_t<decltype(chars)>>;
3895
3896 if (JSInlineString::lengthFits<CharT>(len)) {
3897 JS_ReportErrorASCII(cx, "Cannot create small non-inline strings");
3898 return nullptr;
3899 }
3900
3901 RefPtr<mozilla::StringBuffer> buffer =
3902 mozilla::StringBuffer::Create(chars, len);
3903 if (!buffer) {
3904 ReportOutOfMemory(cx);
3905 return nullptr;
3906 }
3907
3908 Rooted<JSString::OwnedChars<CharT>> owned(cx, std::move(buffer), len);
3909 return JSLinearString::newValidLength<CanGC, CharT>(cx, &owned, heap);
3910 };
3911 if (stable.isLatin1()) {
3912 dest = allocString(stable.latin1Chars());
3913 } else {
3914 dest = allocString(stable.twoByteChars());
3915 }
3916 } else if (capacity) {
3917 if (capacity < len) {
3918 capacity = len;
3919 }
3920 if (len == 0) {
3921 JS_ReportErrorASCII(cx, "Cannot set capacity of empty string");
3922 return false;
3923 }
3924
3925 auto createLinearString = [&](const auto* chars) -> JSLinearString* {
3926 using CharT =
3927 std::remove_const_t<std::remove_pointer_t<decltype(chars)>>;
3928
3929 if (JSInlineString::lengthFits<CharT>(len)) {
3930 JS_ReportErrorASCII(cx, "Cannot create small non-inline strings");
3931 return nullptr;
3932 }
3933
3934 auto news =
3935 cx->make_pod_arena_array<CharT>(js::StringBufferArena, capacity);
3936 if (!news) {
3937 return nullptr;
3938 }
3939 mozilla::PodCopy(news.get(), chars, len);
3940 Rooted<JSString::OwnedChars<CharT>> owned(cx, std::move(news), len);
3941 return JSLinearString::newValidLength<CanGC, CharT>(cx, &owned, heap);
3942 };
3943
3944 if (stable.isLatin1()) {
3945 dest = createLinearString(stable.latin1Chars());
3946 } else {
3947 dest = createLinearString(stable.twoByteChars());
3948 }
3949 if (dest) {
3950 dest->asLinear().makeExtensible(capacity);
3951 }
3952 } else if (wantTwoByte) {
3953 dest = NewStringCopyNDontDeflate<CanGC>(cx, stable.twoByteChars(), len,
3954 heap);
3955 } else if (stable.isLatin1()) {
3956 dest = NewStringCopyN<CanGC>(cx, stable.latin1Chars(), len, heap);
3957 } else {
3958 // Normal behavior: auto-deflate to latin1 if possible.
3959 dest = NewStringCopyN<CanGC>(cx, stable.twoByteChars(), len, heap);
3960 }
3961 }
3962
3963 if (!dest) {
3964 return false;
3965 }
3966
3967 args.rval().setString(dest);
3968 return true;
3969 }
3970
3971 static bool NewDependentString(JSContext* cx, unsigned argc, Value* vp) {
3972 CallArgs args = CallArgsFromVp(argc, vp);
3973
3974 RootedString src(cx, ToString(cx, args.get(0)));
3975 if (!src) {
3976 return false;
3977 }
3978
3979 uint64_t indexStart = 0;
3980 mozilla::Maybe<uint64_t> indexEnd;
3981 gc::Heap heap = gc::Heap::Default;
3982 mozilla::Maybe<gc::Heap> requiredHeap;
3983 bool suppressContraction = false;
3984
3985 if (!ToIndex(cx, args.get(1), &indexStart)) {
3986 return false;
3987 }
3988
3989 Rooted<Value> options(cx);
3990 if (args.get(2).isObject()) {
3991 options = args[2];
3992 } else {
3993 uint64_t idx;
3994 if (args.hasDefined(2)) {
3995 if (!ToIndex(cx, args.get(2), &idx)) {
3996 return false;
3997 }
3998 indexEnd.emplace(idx);
3999 }
4000 options = args.get(3);
4001 }
4002
4003 if (options.isObject()) {
4004 Rooted<Value> v(cx);
4005 Rooted<JSObject*> optObj(cx, &options.toObject());
4006 if (!JS_GetProperty(cx, optObj, "tenured", &v)) {
4007 return false;
4008 }
4009 if (v.isBoolean()) {
4010 requiredHeap.emplace(v.toBoolean() ? gc::Heap::Tenured
4011 : gc::Heap::Default);
4012 heap = *requiredHeap;
4013 }
4014 if (!JS_GetProperty(cx, optObj, "suppress-contraction", &v)) {
4015 return false;
4016 }
4017 suppressContraction = ToBoolean(v);
4018 }
4019
4020 if (indexEnd.isNothing()) {
4021 // Read the length now that no more JS code can run.
4022 indexEnd.emplace(src->length());
4023 }
4024 if (indexStart > src->length() || *indexEnd > src->length() ||
4025 indexStart >= *indexEnd) {
4026 JS_ReportErrorASCII(cx, "invalid dependent string bounds");
4027 return false;
4028 }
4029 if (!src->ensureLinear(cx)) {
4030 return false;
4031 }
4032 Rooted<JSString*> result(
4033 cx, js::NewDependentStringForTesting(
4034 cx, src, indexStart, *indexEnd - indexStart,
4035 suppressContraction ? JS::ContractBaseChain::AllowLong
4036 : JS::ContractBaseChain::Contract,
4037 heap));
4038 if (!result) {
4039 return false;
4040 }
4041 if (!result->isDependent()) {
4042 JS_ReportErrorASCII(cx, "resulting string is not dependent (too short?)");
4043 return false;
4044 }
4045
4046 if (requiredHeap.isSome()) {
4047 if ((*requiredHeap == gc::Heap::Tenured) != result->isTenured()) {
4048 if (result->isTenured()) {
4049 JS_ReportErrorASCII(cx, "nursery string created in tenured heap");
4050 return false;
4051 } else {
4052 JS_ReportErrorASCII(cx, "tenured string created in nursery heap");
4053 return false;
4054 }
4055 }
4056 }
4057
4058 args.rval().setString(result);
4059 return true;
4060 }
4061
4062 // Warning! This will let you create ropes that I'm not sure would be possible
4063 // otherwise, specifically:
4064 //
4065 // - a rope with a zero-length child
4066 // - a rope that would fit into an inline string
4067 //
4068 static bool NewRope(JSContext* cx, unsigned argc, Value* vp) {
4069 CallArgs args = CallArgsFromVp(argc, vp);
4070
4071 if (!args.get(0).isString() || !args.get(1).isString()) {
4072 JS_ReportErrorASCII(cx, "newRope requires two string arguments.");
4073 return false;
4074 }
4075
4076 gc::Heap heap = js::gc::Heap::Default;
4077 if (args.get(2).isObject()) {
4078 RootedObject options(cx, &args[2].toObject());
4079 RootedValue v(cx);
4080 if (!JS_GetProperty(cx, options, "nursery", &v)) {
4081 return false;
4082 }
4083 if (!v.isUndefined() && !ToBoolean(v)) {
4084 heap = js::gc::Heap::Tenured;
4085 }
4086 }
4087
4088 RootedString left(cx, args[0].toString());
4089 RootedString right(cx, args[1].toString());
4090 size_t length = JS_GetStringLength(left) + JS_GetStringLength(right);
4091 if (length > JSString::MAX_LENGTH) {
4092 JS_ReportErrorASCII(cx, "rope length exceeds maximum string length");
4093 return false;
4094 }
4095
4096 // Disallow creating ropes where one side is empty.
4097 if (left->empty() || right->empty()) {
4098 JS_ReportErrorASCII(cx, "rope child mustn't be the empty string");
4099 return false;
4100 }
4101
4102 // Disallow creating ropes which fit into inline strings.
4103 if (left->hasLatin1Chars() && right->hasLatin1Chars()) {
4104 if (JSInlineString::lengthFits<JS::Latin1Char>(length)) {
4105 JS_ReportErrorASCII(cx, "Cannot create small non-inline ropes");
4106 return false;
4107 }
4108 } else {
4109 if (JSInlineString::lengthFits<char16_t>(length)) {
4110 JS_ReportErrorASCII(cx, "Cannot create small non-inline ropes");
4111 return false;
4112 }
4113 }
4114
4115 auto* str = JSRope::new_<CanGC>(cx, left, right, length, heap);
4116 if (!str) {
4117 return false;
4118 }
4119
4120 args.rval().setString(str);
4121 return true;
4122 }
4123
4124 static bool IsRope(JSContext* cx, unsigned argc, Value* vp) {
4125 CallArgs args = CallArgsFromVp(argc, vp);
4126
4127 if (!args.get(0).isString()) {
4128 JS_ReportErrorASCII(cx, "isRope requires a string argument.");
4129 return false;
4130 }
4131
4132 JSString* str = args[0].toString();
4133 args.rval().setBoolean(str->isRope());
4134 return true;
4135 }
4136
4137 static bool EnsureLinearString(JSContext* cx, unsigned argc, Value* vp) {
4138 CallArgs args = CallArgsFromVp(argc, vp);
4139
4140 if (args.length() != 1 || !args[0].isString()) {
4141 JS_ReportErrorASCII(
4142 cx, "ensureLinearString takes exactly one string argument.");
4143 return false;
4144 }
4145
4146 JSLinearString* linear = args[0].toString()->ensureLinear(cx);
4147 if (!linear) {
4148 return false;
4149 }
4150
4151 args.rval().setString(linear);
4152 return true;
4153 }
4154
4155 static bool RepresentativeStringArray(JSContext* cx, unsigned argc, Value* vp) {
4156 CallArgs args = CallArgsFromVp(argc, vp);
4157
4158 RootedObject array(cx, JS::NewArrayObject(cx, 0));
4159 if (!array) {
4160 return false;
4161 }
4162
4163 if (!JSString::fillWithRepresentatives(cx, array.as<ArrayObject>())) {
4164 return false;
4165 }
4166
4167 args.rval().setObject(*array);
4168 return true;
4169 }
4170
4171 #if defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
4172
4173 static bool OOMThreadTypes(JSContext* cx, unsigned argc, Value* vp) {
4174 CallArgs args = CallArgsFromVp(argc, vp);
4175 args.rval().setInt32(js::THREAD_TYPE_MAX);
4176 return true;
4177 }
4178
4179 static bool CheckCanSimulateOOM(JSContext* cx) {
4180 if (js::oom::GetThreadType() != js::THREAD_TYPE_MAIN) {
4181 JS_ReportErrorASCII(
4182 cx, "Simulated OOM failure is only supported on the main thread");
4183 return false;
4184 }
4185
4186 return true;
4187 }
4188
4189 static bool SetupOOMFailure(JSContext* cx, bool failAlways, unsigned argc,
4190 Value* vp) {
4191 CallArgs args = CallArgsFromVp(argc, vp);
4192
4193 if (disableOOMFunctions) {
4194 args.rval().setUndefined();
4195 return true;
4196 }
4197
4198 if (args.length() < 1) {
4199 JS_ReportErrorASCII(cx, "Count argument required");
4200 return false;
4201 }
4202
4203 if (args.length() > 2) {
4204 JS_ReportErrorASCII(cx, "Too many arguments");
4205 return false;
4206 }
4207
4208 int32_t count;
4209 if (!JS::ToInt32(cx, args.get(0), &count)) {
4210 return false;
4211 }
4212
4213 if (count <= 0) {
4214 JS_ReportErrorASCII(cx, "OOM cutoff should be positive");
4215 return false;
4216 }
4217
4218 uint32_t targetThread = js::THREAD_TYPE_MAIN;
4219 if (args.length() > 1 && !ToUint32(cx, args[1], &targetThread)) {
4220 return false;
4221 }
4222
4223 if (targetThread == js::THREAD_TYPE_NONE ||
4224 targetThread == js::THREAD_TYPE_WORKER ||
4225 targetThread >= js::THREAD_TYPE_MAX) {
4226 JS_ReportErrorASCII(cx, "Invalid thread type specified");
4227 return false;
4228 }
4229
4230 if (!CheckCanSimulateOOM(cx)) {
4231 return false;
4232 }
4233
4234 js::oom::simulator.simulateFailureAfter(js::oom::FailureSimulator::Kind::OOM,
4235 count, targetThread, failAlways);
4236 args.rval().setUndefined();
4237 return true;
4238 }
4239
4240 static bool OOMAfterAllocations(JSContext* cx, unsigned argc, Value* vp) {
4241 return SetupOOMFailure(cx, true, argc, vp);
4242 }
4243
4244 static bool OOMAtAllocation(JSContext* cx, unsigned argc, Value* vp) {
4245 return SetupOOMFailure(cx, false, argc, vp);
4246 }
4247
4248 static bool ResetOOMFailure(JSContext* cx, unsigned argc, Value* vp) {
4249 CallArgs args = CallArgsFromVp(argc, vp);
4250
4251 if (!CheckCanSimulateOOM(cx)) {
4252 return false;
4253 }
4254
4255 args.rval().setBoolean(js::oom::HadSimulatedOOM());
4256 js::oom::simulator.reset();
4257 return true;
4258 }
4259
4260 static size_t CountCompartments(JSContext* cx) {
4261 size_t count = 0;
4262 for (auto zone : cx->runtime()->gc.zones()) {
4263 count += zone->compartments().length();
4264 }
4265 return count;
4266 }
4267
4268 // Iterative failure testing: test a function by simulating failures at indexed
4269 // locations throughout the normal execution path and checking that the
4270 // resulting state of the environment is consistent with the error result.
4271 //
4272 // For example, trigger OOM at every allocation point and test that the function
4273 // either recovers and succeeds or raises an exception and fails.
4274
4275 class MOZ_STACK_CLASS IterativeFailureTest {
4276 public:
4277 struct FailureSimulator {
4278 virtual void setup(JSContext* cx) {}
4279 virtual void teardown(JSContext* cx) {}
4280 virtual void startSimulating(JSContext* cx, unsigned iteration,
4281 unsigned thread, bool keepFailing) = 0;
4282 virtual bool stopSimulating() = 0;
4283 virtual void cleanup(JSContext* cx) {}
4284 };
4285
4286 IterativeFailureTest(JSContext* cx, FailureSimulator& simulator);
4287 bool initParams(const CallArgs& args);
4288 bool test();
4289
4290 private:
4291 bool setup();
4292 bool testThread(unsigned thread);
4293 bool testIteration(unsigned thread, unsigned iteration,
4294 bool& failureWasSimulated, MutableHandleValue exception);
4295 void cleanup();
4296 void teardown();
4297
4298 JSContext* const cx;
4299 FailureSimulator& simulator;
4300 size_t compartmentCount;
4301
4302 // Test parameters set by initParams.
4303 RootedFunction testFunction;
4304 unsigned threadStart = 0;
4305 unsigned threadEnd = 0;
4306 bool expectExceptionOnFailure = true;
4307 bool keepFailing = false;
4308 bool verbose = false;
4309 };
4310
4311 bool RunIterativeFailureTest(
4312 JSContext* cx, const CallArgs& args,
4313 IterativeFailureTest::FailureSimulator& simulator) {
4314 IterativeFailureTest test(cx, simulator);
4315 return test.initParams(args) && test.test();
4316 }
4317
4318 IterativeFailureTest::IterativeFailureTest(JSContext* cx,
4319 FailureSimulator& simulator)
4320 : cx(cx), simulator(simulator), testFunction(cx) {}
4321
4322 bool IterativeFailureTest::test() {
4323 if (disableOOMFunctions) {
4324 return true;
4325 }
4326
4327 if (!setup()) {
4328 return false;
4329 }
4330
4331 auto onExit = mozilla::MakeScopeExit([this] { teardown(); });
4332
4333 for (unsigned thread = threadStart; thread <= threadEnd; thread++) {
4334 if (!testThread(thread)) {
4335 return false;
4336 }
4337 }
4338
4339 return true;
4340 }
4341
4342 bool IterativeFailureTest::setup() {
4343 if (!CheckCanSimulateOOM(cx)) {
4344 return false;
4345 }
4346
4347 // Disallow nested tests.
4348 if (cx->runningOOMTest) {
4349 JS_ReportErrorASCII(
4350 cx, "Nested call to iterative failure test is not allowed.");
4351 return false;
4352 }
4353 cx->runningOOMTest = true;
4354
4355 MOZ_ASSERT(!cx->isExceptionPending());
4356
4357 # ifdef JS_GC_ZEAL
4358 JS::SetGCZeal(cx, 0, JS::ShellDefaultGCZealFrequency);
4359 # endif
4360
4361 // Delazify the function here if necessary so we don't end up testing that.
4362 if (testFunction->isInterpreted() &&
4363 !JSFunction::getOrCreateScript(cx, testFunction)) {
4364 return false;
4365 }
4366
4367 compartmentCount = CountCompartments(cx);
4368
4369 simulator.setup(cx);
4370
4371 return true;
4372 }
4373
4374 bool IterativeFailureTest::testThread(unsigned thread) {
4375 if (verbose) {
4376 fprintf(stderr, "thread %u\n", thread);
4377 }
4378
4379 RootedValue exception(cx);
4380
4381 unsigned iteration = 1;
4382 bool failureWasSimulated;
4383 do {
4384 if (!testIteration(thread, iteration, failureWasSimulated, &exception)) {
4385 return false;
4386 }
4387
4388 iteration++;
4389 } while (failureWasSimulated);
4390
4391 if (verbose) {
4392 fprintf(stderr, " finished after %u iterations\n", iteration - 1);
4393 if (!exception.isUndefined()) {
4394 RootedString str(cx, JS::ToString(cx, exception));
4395 if (!str) {
4396 fprintf(stderr, " error while trying to print exception, giving up\n");
4397 return false;
4398 }
4399 UniqueChars bytes(JS_EncodeStringToUTF8(cx, str));
4400 if (!bytes) {
4401 return false;
4402 }
4403 fprintf(stderr, " threw %s\n", bytes.get());
4404 }
4405 }
4406
4407 return true;
4408 }
4409
4410 bool IterativeFailureTest::testIteration(unsigned thread, unsigned iteration,
4411 bool& failureWasSimulated,
4412 MutableHandleValue exception) {
4413 if (verbose) {
4414 fprintf(stderr, " iteration %u\n", iteration);
4415 }
4416
4417 MOZ_RELEASE_ASSERT(!cx->isExceptionPending());
4418
4419 simulator.startSimulating(cx, iteration, thread, keepFailing);
4420
4421 RootedValue result(cx);
4422 bool ok = JS_CallFunction(cx, cx->global(), testFunction,
4423 HandleValueArray::empty(), &result);
4424
4425 failureWasSimulated = simulator.stopSimulating();
4426
4427 if (ok && cx->isExceptionPending()) {
4428 MOZ_CRASH(
4429 "Thunk execution succeeded but an exception was raised - missing error "
4430 "check?");
4431 }
4432
4433 if (!ok && !cx->isExceptionPending() && expectExceptionOnFailure) {
4434 MOZ_CRASH(
4435 "Thunk execution failed but no exception was raised - missing call to "
4436 "js::ReportOutOfMemory()?");
4437 }
4438
4439 // Note that it is possible that the function throws an exception unconnected
4440 // to the simulated failure, in which case we ignore it. More correct would be
4441 // to have the caller pass some kind of exception specification and to check
4442 // the exception against it.
4443 if (!failureWasSimulated && cx->isExceptionPending()) {
4444 if (!cx->getPendingException(exception)) {
4445 return false;
4446 }
4447 }
4448 cx->clearPendingException();
4449
4450 cleanup();
4451
4452 return true;
4453 }
4454
4455 void IterativeFailureTest::cleanup() {
4456 simulator.cleanup(cx);
4457
4458 gc::FinishGC(cx);
4459
4460 // Some tests create a new compartment or zone on every iteration. Our GC is
4461 // triggered by GC allocations and not by number of compartments or zones, so
4462 // these won't normally get cleaned up. The check here stops some tests
4463 // running out of memory. ("Gentlemen, you can't fight in here! This is the
4464 // War oom!")
4465 if (CountCompartments(cx) > compartmentCount + 100) {
4466 JS_GC(cx);
4467 compartmentCount = CountCompartments(cx);
4468 }
4469 }
4470
4471 void IterativeFailureTest::teardown() {
4472 simulator.teardown(cx);
4473
4474 cx->runningOOMTest = false;
4475 }
4476
4477 bool IterativeFailureTest::initParams(const CallArgs& args) {
4478 if (args.length() < 1 || args.length() > 2) {
4479 JS_ReportErrorASCII(cx, "function takes between 1 and 2 arguments.");
4480 return false;
4481 }
4482
4483 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
4484 JS_ReportErrorASCII(cx, "The first argument must be the function to test.");
4485 return false;
4486 }
4487 testFunction = &args[0].toObject().as<JSFunction>();
4488
4489 if (args.length() == 2) {
4490 if (args[1].isBoolean()) {
4491 expectExceptionOnFailure = args[1].toBoolean();
4492 } else if (args[1].isObject()) {
4493 RootedObject options(cx, &args[1].toObject());
4494 RootedValue value(cx);
4495
4496 if (!JS_GetProperty(cx, options, "expectExceptionOnFailure", &value)) {
4497 return false;
4498 }
4499 if (!value.isUndefined()) {
4500 expectExceptionOnFailure = ToBoolean(value);
4501 }
4502
4503 if (!JS_GetProperty(cx, options, "keepFailing", &value)) {
4504 return false;
4505 }
4506 if (!value.isUndefined()) {
4507 keepFailing = ToBoolean(value);
4508 }
4509 } else {
4510 JS_ReportErrorASCII(
4511 cx, "The optional second argument must be an object or a boolean.");
4512 return false;
4513 }
4514 }
4515
4516 // There are some places where we do fail without raising an exception, so
4517 // we can't expose this to the fuzzers by default.
4518 if (fuzzingSafe) {
4519 expectExceptionOnFailure = false;
4520 }
4521
4522 // Test all threads by default except worker threads.
4523 threadStart = oom::FirstThreadTypeToTest;
4524 threadEnd = oom::LastThreadTypeToTest;
4525
4526 // Test a single thread type if specified by the OOM_THREAD environment
4527 // variable.
4528 int threadOption = 0;
4529 if (EnvVarAsInt("OOM_THREAD", &threadOption)) {
4530 if (threadOption < oom::FirstThreadTypeToTest ||
4531 threadOption > oom::LastThreadTypeToTest) {
4532 JS_ReportErrorASCII(cx, "OOM_THREAD value out of range.");
4533 return false;
4534 }
4535
4536 threadStart = threadOption;
4537 threadEnd = threadOption;
4538 }
4539
4540 verbose = EnvVarIsDefined("OOM_VERBOSE");
4541
4542 return true;
4543 }
4544
4545 struct OOMSimulator : public IterativeFailureTest::FailureSimulator {
4546 void setup(JSContext* cx) override { cx->runtime()->hadOutOfMemory = false; }
4547
4548 void startSimulating(JSContext* cx, unsigned i, unsigned thread,
4549 bool keepFailing) override {
4550 MOZ_ASSERT(!cx->runtime()->hadOutOfMemory);
4551 js::oom::simulator.simulateFailureAfter(
4552 js::oom::FailureSimulator::Kind::OOM, i, thread, keepFailing);
4553 }
4554
4555 bool stopSimulating() override {
4556 bool handledOOM = js::oom::HadSimulatedOOM();
4557 js::oom::simulator.reset();
4558 return handledOOM;
4559 }
4560
4561 void cleanup(JSContext* cx) override {
4562 cx->runtime()->hadOutOfMemory = false;
4563 }
4564 };
4565
4566 static bool OOMTest(JSContext* cx, unsigned argc, Value* vp) {
4567 CallArgs args = CallArgsFromVp(argc, vp);
4568
4569 OOMSimulator simulator;
4570 if (!RunIterativeFailureTest(cx, args, simulator)) {
4571 return false;
4572 }
4573
4574 args.rval().setUndefined();
4575 return true;
4576 }
4577
4578 struct StackOOMSimulator : public IterativeFailureTest::FailureSimulator {
4579 void startSimulating(JSContext* cx, unsigned i, unsigned thread,
4580 bool keepFailing) override {
4581 js::oom::simulator.simulateFailureAfter(
4582 js::oom::FailureSimulator::Kind::StackOOM, i, thread, keepFailing);
4583 }
4584
4585 bool stopSimulating() override {
4586 bool handledOOM = js::oom::HadSimulatedStackOOM();
4587 js::oom::simulator.reset();
4588 return handledOOM;
4589 }
4590 };
4591
4592 static bool StackTest(JSContext* cx, unsigned argc, Value* vp) {
4593 CallArgs args = CallArgsFromVp(argc, vp);
4594
4595 StackOOMSimulator simulator;
4596 if (!RunIterativeFailureTest(cx, args, simulator)) {
4597 return false;
4598 }
4599
4600 args.rval().setUndefined();
4601 return true;
4602 }
4603
4604 struct FailingIterruptSimulator
4605 : public IterativeFailureTest::FailureSimulator {
4606 JSInterruptCallback* prevEnd = nullptr;
4607
4608 static bool failingInterruptCallback(JSContext* cx) { return false; }
4609
4610 void setup(JSContext* cx) override {
4611 prevEnd = cx->interruptCallbacks().end();
4612 JS_AddInterruptCallback(cx, failingInterruptCallback);
4613 }
4614
4615 void teardown(JSContext* cx) override {
4616 cx->interruptCallbacks().erase(prevEnd, cx->interruptCallbacks().end());
4617 }
4618
4619 void startSimulating(JSContext* cx, unsigned i, unsigned thread,
4620 bool keepFailing) override {
4621 js::oom::simulator.simulateFailureAfter(
4622 js::oom::FailureSimulator::Kind::Interrupt, i, thread, keepFailing);
4623 }
4624
4625 bool stopSimulating() override {
4626 bool handledInterrupt = js::oom::HadSimulatedInterrupt();
4627 js::oom::simulator.reset();
4628 return handledInterrupt;
4629 }
4630 };
4631
4632 static bool InterruptTest(JSContext* cx, unsigned argc, Value* vp) {
4633 CallArgs args = CallArgsFromVp(argc, vp);
4634
4635 FailingIterruptSimulator simulator;
4636 if (!RunIterativeFailureTest(cx, args, simulator)) {
4637 return false;
4638 }
4639
4640 args.rval().setUndefined();
4641 return true;
4642 }
4643
4644 #endif // defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
4645
4646 static bool SettlePromiseNow(JSContext* cx, unsigned argc, Value* vp) {
4647 CallArgs args = CallArgsFromVp(argc, vp);
4648 if (!args.requireAtLeast(cx, "settlePromiseNow", 1)) {
4649 return false;
4650 }
4651 if (!args[0].isObject() || !args[0].toObject().is<PromiseObject>()) {
4652 JS_ReportErrorASCII(cx, "first argument must be a Promise object");
4653 return false;
4654 }
4655
4656 Rooted<PromiseObject*> promise(cx, &args[0].toObject().as<PromiseObject>());
4657 if (IsPromiseForAsyncFunctionOrGenerator(promise)) {
4658 JS_ReportErrorASCII(
4659 cx, "async function/generator's promise shouldn't be manually settled");
4660 return false;
4661 }
4662
4663 if (promise->state() != JS::PromiseState::Pending) {
4664 JS_ReportErrorASCII(cx, "cannot settle an already-resolved promise");
4665 return false;
4666 }
4667
4668 if (IsPromiseWithDefaultResolvingFunction(promise)) {
4669 SetAlreadyResolvedPromiseWithDefaultResolvingFunction(promise);
4670 }
4671
4672 int32_t flags = promise->flags();
4673 promise->setFixedSlot(
4674 PromiseSlot_Flags,
4675 Int32Value(flags | PROMISE_FLAG_RESOLVED | PROMISE_FLAG_FULFILLED));
4676 promise->setFixedSlot(PromiseSlot_ReactionsOrResult, UndefinedValue());
4677
4678 DebugAPI::onPromiseSettled(cx, promise);
4679 return true;
4680 }
4681
4682 static bool GetWaitForAllPromise(JSContext* cx, unsigned argc, Value* vp) {
4683 CallArgs args = CallArgsFromVp(argc, vp);
4684 if (!args.requireAtLeast(cx, "getWaitForAllPromise", 1)) {
4685 return false;
4686 }
4687 if (!args[0].isObject() || !args[0].toObject().is<ArrayObject>() ||
4688 args[0].toObject().as<NativeObject>().isIndexed()) {
4689 JS_ReportErrorASCII(
4690 cx, "first argument must be a dense Array of Promise objects");
4691 return false;
4692 }
4693 Rooted<NativeObject*> list(cx, &args[0].toObject().as<NativeObject>());
4694 RootedObjectVector promises(cx);
4695 uint32_t count = list->getDenseInitializedLength();
4696 if (!promises.resize(count)) {
4697 return false;
4698 }
4699
4700 for (uint32_t i = 0; i < count; i++) {
4701 RootedValue elem(cx, list->getDenseElement(i));
4702 if (!elem.isObject() || !elem.toObject().is<PromiseObject>()) {
4703 JS_ReportErrorASCII(
4704 cx, "Each entry in the passed-in Array must be a Promise");
4705 return false;
4706 }
4707 promises[i].set(&elem.toObject());
4708 }
4709
4710 RootedObject resultPromise(cx, JS::GetWaitForAllPromise(cx, promises));
4711 if (!resultPromise) {
4712 return false;
4713 }
4714
4715 args.rval().set(ObjectValue(*resultPromise));
4716 return true;
4717 }
4718
4719 static bool ResolvePromise(JSContext* cx, unsigned argc, Value* vp) {
4720 CallArgs args = CallArgsFromVp(argc, vp);
4721 if (!args.requireAtLeast(cx, "resolvePromise", 2)) {
4722 return false;
4723 }
4724 if (!args[0].isObject() ||
4725 !UncheckedUnwrap(&args[0].toObject())->is<PromiseObject>()) {
4726 JS_ReportErrorASCII(
4727 cx, "first argument must be a maybe-wrapped Promise object");
4728 return false;
4729 }
4730
4731 RootedObject promise(cx, &args[0].toObject());
4732 RootedValue resolution(cx, args[1]);
4733 mozilla::Maybe<AutoRealm> ar;
4734 if (IsWrapper(promise)) {
4735 promise = UncheckedUnwrap(promise);
4736 ar.emplace(cx, promise);
4737 if (!cx->compartment()->wrap(cx, &resolution)) {
4738 return false;
4739 }
4740 }
4741
4742 if (IsPromiseForAsyncFunctionOrGenerator(promise)) {
4743 JS_ReportErrorASCII(
4744 cx,
4745 "async function/generator's promise shouldn't be manually resolved");
4746 return false;
4747 }
4748
4749 bool result = JS::ResolvePromise(cx, promise, resolution);
4750 if (result) {
4751 args.rval().setUndefined();
4752 }
4753 return result;
4754 }
4755
4756 static bool RejectPromise(JSContext* cx, unsigned argc, Value* vp) {
4757 CallArgs args = CallArgsFromVp(argc, vp);
4758 if (!args.requireAtLeast(cx, "rejectPromise", 2)) {
4759 return false;
4760 }
4761 if (!args[0].isObject() ||
4762 !UncheckedUnwrap(&args[0].toObject())->is<PromiseObject>()) {
4763 JS_ReportErrorASCII(
4764 cx, "first argument must be a maybe-wrapped Promise object");
4765 return false;
4766 }
4767
4768 RootedObject promise(cx, &args[0].toObject());
4769 RootedValue reason(cx, args[1]);
4770 mozilla::Maybe<AutoRealm> ar;
4771 if (IsWrapper(promise)) {
4772 promise = UncheckedUnwrap(promise);
4773 ar.emplace(cx, promise);
4774 if (!cx->compartment()->wrap(cx, &reason)) {
4775 return false;
4776 }
4777 }
4778
4779 if (IsPromiseForAsyncFunctionOrGenerator(promise)) {
4780 JS_ReportErrorASCII(
4781 cx,
4782 "async function/generator's promise shouldn't be manually rejected");
4783 return false;
4784 }
4785
4786 bool result = JS::RejectPromise(cx, promise, reason);
4787 if (result) {
4788 args.rval().setUndefined();
4789 }
4790 return result;
4791 }
4792
4793 static unsigned finalizeCount = 0;
4794
4795 static void finalize_counter_finalize(JS::GCContext* gcx, JSObject* obj) {
4796 ++finalizeCount;
4797 }
4798
4799 static const JSClassOps FinalizeCounterClassOps = {
4800 nullptr, // addProperty
4801 nullptr, // delProperty
4802 nullptr, // enumerate
4803 nullptr, // newEnumerate
4804 nullptr, // resolve
4805 nullptr, // mayResolve
4806 finalize_counter_finalize, // finalize
4807 nullptr, // call
4808 nullptr, // construct
4809 nullptr, // trace
4810 };
4811
4812 static const JSClass FinalizeCounterClass = {
4813 "FinalizeCounter",
4814 JSCLASS_FOREGROUND_FINALIZE,
4815 &FinalizeCounterClassOps,
4816 };
4817
4818 static bool MakeFinalizeObserver(JSContext* cx, unsigned argc, Value* vp) {
4819 CallArgs args = CallArgsFromVp(argc, vp);
4820
4821 JSObject* obj =
4822 JS_NewObjectWithGivenProto(cx, &FinalizeCounterClass, nullptr);
4823 if (!obj) {
4824 return false;
4825 }
4826
4827 args.rval().setObject(*obj);
4828 return true;
4829 }
4830
4831 static bool FinalizeCount(JSContext* cx, unsigned argc, Value* vp) {
4832 CallArgs args = CallArgsFromVp(argc, vp);
4833 args.rval().setInt32(finalizeCount);
4834 return true;
4835 }
4836
4837 static bool ResetFinalizeCount(JSContext* cx, unsigned argc, Value* vp) {
4838 CallArgs args = CallArgsFromVp(argc, vp);
4839 finalizeCount = 0;
4840 args.rval().setUndefined();
4841 return true;
4842 }
4843
4844 static bool DumpHeap(JSContext* cx, unsigned argc, Value* vp) {
4845 CallArgs args = CallArgsFromVp(argc, vp);
4846
4847 FILE* dumpFile = stdout;
4848 auto closeFile = mozilla::MakeScopeExit([&dumpFile] {
4849 if (dumpFile && dumpFile != stdout) {
4850 fclose(dumpFile);
4851 }
4852 });
4853
4854 if (args.length() > 1) {
4855 RootedObject callee(cx, &args.callee());
4856 ReportUsageErrorASCII(cx, callee, "Too many arguments");
4857 return false;
4858 }
4859
4860 if (!args.get(0).isUndefined()) {
4861 RootedString str(cx, ToString(cx, args[0]));
4862 if (!str) {
4863 return false;
4864 }
4865 if (!fuzzingSafe) {
4866 UniqueChars fileNameBytes = JS_EncodeStringToUTF8(cx, str);
4867 if (!fileNameBytes) {
4868 return false;
4869 }
4870 #ifdef XP_WIN
4871 UniqueWideChars wideFileNameBytes =
4872 JS::EncodeUtf8ToWide(cx, fileNameBytes.get());
4873 if (!wideFileNameBytes) {
4874 return false;
4875 }
4876 dumpFile = _wfopen(wideFileNameBytes.get(), L"w");
4877 #else
4878 UniqueChars narrowFileNameBytes =
4879 JS::EncodeUtf8ToNarrow(cx, fileNameBytes.get());
4880 if (!narrowFileNameBytes) {
4881 return false;
4882 }
4883 dumpFile = fopen(narrowFileNameBytes.get(), "w");
4884 #endif
4885 if (!dumpFile) {
4886 JS_ReportErrorUTF8(cx, "can't open %s", fileNameBytes.get());
4887 return false;
4888 }
4889 }
4890 }
4891
4892 js::DumpHeap(cx, dumpFile, js::IgnoreNurseryObjects);
4893
4894 args.rval().setUndefined();
4895 return true;
4896 }
4897
4898 static bool Terminate(JSContext* cx, unsigned arg, Value* vp) {
4899 // Print a message to stderr in differential testing to help jsfunfuzz
4900 // find uncatchable-exception bugs.
4901 if (js::SupportDifferentialTesting()) {
4902 fprintf(stderr, "terminate called\n");
4903 }
4904
4905 JS::ReportUncatchableException(cx);
4906 return false;
4907 }
4908
4909 static bool ReadGeckoProfilingStack(JSContext* cx, unsigned argc, Value* vp) {
4910 CallArgs args = CallArgsFromVp(argc, vp);
4911 args.rval().setUndefined();
4912
4913 // Return boolean 'false' if profiler is not enabled.
4914 if (!cx->runtime()->geckoProfiler().enabled()) {
4915 args.rval().setBoolean(false);
4916 return true;
4917 }
4918
4919 // Array holding physical jit stack frames.
4920 RootedObject stack(cx, NewDenseEmptyArray(cx));
4921 if (!stack) {
4922 return false;
4923 }
4924
4925 // If profiler sampling has been suppressed, return an empty
4926 // stack.
4927 if (!cx->isProfilerSamplingEnabled()) {
4928 args.rval().setObject(*stack);
4929 return true;
4930 }
4931
4932 struct InlineFrameInfo {
4933 InlineFrameInfo(const char* kind, UniqueChars label)
4934 : kind(kind), label(std::move(label)) {}
4935 const char* kind;
4936 UniqueChars label;
4937 };
4938
4939 Vector<Vector<InlineFrameInfo, 0, TempAllocPolicy>, 0, TempAllocPolicy>
4940 frameInfo(cx);
4941
4942 JS::ProfilingFrameIterator::RegisterState state;
4943 for (JS::ProfilingFrameIterator i(cx, state); !i.done(); ++i) {
4944 MOZ_ASSERT(i.stackAddress() != nullptr);
4945
4946 if (!frameInfo.emplaceBack(cx)) {
4947 return false;
4948 }
4949
4950 const size_t MaxInlineFrames = 16;
4951 JS::ProfilingFrameIterator::Frame frames[MaxInlineFrames];
4952 uint32_t nframes = i.extractStack(frames, 0, MaxInlineFrames);
4953 MOZ_ASSERT(nframes <= MaxInlineFrames);
4954 for (uint32_t i = 0; i < nframes; i++) {
4955 const char* frameKindStr = nullptr;
4956 switch (frames[i].kind) {
4957 case JS::ProfilingFrameIterator::Frame_BaselineInterpreter:
4958 frameKindStr = "baseline-interpreter";
4959 break;
4960 case JS::ProfilingFrameIterator::Frame_Baseline:
4961 frameKindStr = "baseline-jit";
4962 break;
4963 case JS::ProfilingFrameIterator::Frame_Ion:
4964 frameKindStr = "ion";
4965 break;
4966 case JS::ProfilingFrameIterator::Frame_WasmBaseline:
4967 case JS::ProfilingFrameIterator::Frame_WasmIon:
4968 case JS::ProfilingFrameIterator::Frame_WasmOther:
4969 frameKindStr = "wasm";
4970 break;
4971 default:
4972 frameKindStr = "unknown";
4973 }
4974
4975 UniqueChars label =
4976 DuplicateStringToArena(js::StringBufferArena, cx, frames[i].label);
4977 if (!label) {
4978 return false;
4979 }
4980
4981 if (!frameInfo.back().emplaceBack(frameKindStr, std::move(label))) {
4982 return false;
4983 }
4984 }
4985 }
4986
4987 RootedObject inlineFrameInfo(cx);
4988 RootedString frameKind(cx);
4989 RootedString frameLabel(cx);
4990 RootedId idx(cx);
4991
4992 const unsigned propAttrs = JSPROP_ENUMERATE;
4993
4994 uint32_t physicalFrameNo = 0;
4995 for (auto& frame : frameInfo) {
4996 // Array holding all inline frames in a single physical jit stack frame.
4997 RootedObject inlineStack(cx, NewDenseEmptyArray(cx));
4998 if (!inlineStack) {
4999 return false;
5000 }
5001
5002 uint32_t inlineFrameNo = 0;
5003 for (auto& inlineFrame : frame) {
5004 // Object holding frame info.
5005 RootedObject inlineFrameInfo(cx, NewPlainObject(cx));
5006 if (!inlineFrameInfo) {
5007 return false;
5008 }
5009
5010 frameKind = NewStringCopyZ<CanGC>(cx, inlineFrame.kind);
5011 if (!frameKind) {
5012 return false;
5013 }
5014
5015 if (!JS_DefineProperty(cx, inlineFrameInfo, "kind", frameKind,
5016 propAttrs)) {
5017 return false;
5018 }
5019
5020 frameLabel = NewLatin1StringZ(cx, std::move(inlineFrame.label));
5021 if (!frameLabel) {
5022 return false;
5023 }
5024
5025 if (!JS_DefineProperty(cx, inlineFrameInfo, "label", frameLabel,
5026 propAttrs)) {
5027 return false;
5028 }
5029
5030 idx = PropertyKey::Int(inlineFrameNo);
5031 if (!JS_DefinePropertyById(cx, inlineStack, idx, inlineFrameInfo, 0)) {
5032 return false;
5033 }
5034
5035 ++inlineFrameNo;
5036 }
5037
5038 // Push inline array into main array.
5039 idx = PropertyKey::Int(physicalFrameNo);
5040 if (!JS_DefinePropertyById(cx, stack, idx, inlineStack, 0)) {
5041 return false;
5042 }
5043
5044 ++physicalFrameNo;
5045 }
5046
5047 args.rval().setObject(*stack);
5048 return true;
5049 }
5050
5051 static bool ReadGeckoInterpProfilingStack(JSContext* cx, unsigned argc,
5052 Value* vp) {
5053 CallArgs args = CallArgsFromVp(argc, vp);
5054 args.rval().setUndefined();
5055
5056 // Return boolean 'false' if profiler is not enabled.
5057 if (!cx->runtime()->geckoProfiler().enabled()) {
5058 args.rval().setBoolean(false);
5059 return true;
5060 }
5061
5062 // Array with information about each frame.
5063 Rooted<JSObject*> stack(cx, NewDenseEmptyArray(cx));
5064 if (!stack) {
5065 return false;
5066 }
5067 uint32_t stackIndex = 0;
5068
5069 ProfilingStack* profStack = cx->geckoProfiler().getProfilingStack();
5070 MOZ_ASSERT(profStack);
5071
5072 for (size_t i = 0; i < profStack->stackSize(); i++) {
5073 const auto& frame = profStack->frames[i];
5074 if (!frame.isJsFrame()) {
5075 continue;
5076 }
5077
5078 // Skip fake JS frame pushed for js::RunScript by GeckoProfilerEntryMarker.
5079 const char* dynamicStr = frame.dynamicString();
5080 if (!dynamicStr) {
5081 continue;
5082 }
5083
5084 Rooted<PlainObject*> frameInfo(cx, NewPlainObject(cx));
5085 if (!frameInfo) {
5086 return false;
5087 }
5088
5089 Rooted<JSString*> dynamicString(
5090 cx, JS_NewStringCopyUTF8Z(
5091 cx, JS::ConstUTF8CharsZ(dynamicStr, strlen(dynamicStr))));
5092 if (!dynamicString) {
5093 return false;
5094 }
5095 if (!JS_DefineProperty(cx, frameInfo, "dynamicString", dynamicString,
5096 JSPROP_ENUMERATE)) {
5097 return false;
5098 }
5099
5100 if (!JS_DefineElement(cx, stack, stackIndex, frameInfo, JSPROP_ENUMERATE)) {
5101 return false;
5102 }
5103 stackIndex++;
5104 }
5105
5106 args.rval().setObject(*stack);
5107 return true;
5108 }
5109
5110 static bool EnableOsiPointRegisterChecks(JSContext*, unsigned argc, Value* vp) {
5111 CallArgs args = CallArgsFromVp(argc, vp);
5112 #ifdef CHECK_OSIPOINT_REGISTERS
5113 jit::JitOptions.checkOsiPointRegisters = true;
5114 #endif
5115 args.rval().setUndefined();
5116 return true;
5117 }
5118
5119 static bool DisplayName(JSContext* cx, unsigned argc, Value* vp) {
5120 CallArgs args = CallArgsFromVp(argc, vp);
5121 if (!args.get(0).isObject() || !args[0].toObject().is<JSFunction>()) {
5122 RootedObject arg(cx, &args.callee());
5123 ReportUsageErrorASCII(cx, arg, "Must have one function argument");
5124 return false;
5125 }
5126
5127 JSFunction* fun = &args[0].toObject().as<JSFunction>();
5128 JS::Rooted<JSAtom*> str(cx);
5129 if (!fun->getDisplayAtom(cx, &str)) {
5130 return false;
5131 }
5132 args.rval().setString(str ? str : cx->runtime()->emptyString.ref());
5133 return true;
5134 }
5135
5136 static bool IsAvxPresent(JSContext* cx, unsigned argc, Value* vp) {
5137 CallArgs args = CallArgsFromVp(argc, vp);
5138 #if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86)
5139 int minVersion = 1;
5140 if (argc > 0 && args.get(0).isNumber()) {
5141 minVersion = std::max(1, int(args[0].toNumber()));
5142 }
5143 switch (minVersion) {
5144 case 1:
5145 args.rval().setBoolean(jit::Assembler::HasAVX());
5146 return true;
5147 case 2:
5148 args.rval().setBoolean(jit::Assembler::HasAVX2());
5149 return true;
5150 }
5151 #endif
5152 args.rval().setBoolean(false);
5153 return true;
5154 }
5155
5156 class ShellAllocationMetadataBuilder : public AllocationMetadataBuilder {
5157 public:
5158 ShellAllocationMetadataBuilder() = default;
5159
5160 virtual JSObject* build(JSContext* cx, HandleObject,
5161 AutoEnterOOMUnsafeRegion& oomUnsafe) const override;
5162
5163 static const ShellAllocationMetadataBuilder metadataBuilder;
5164 };
5165
5166 JSObject* ShellAllocationMetadataBuilder::build(
5167 JSContext* cx, HandleObject, AutoEnterOOMUnsafeRegion& oomUnsafe) const {
5168 RootedObject obj(cx, NewPlainObject(cx));
5169 if (!obj) {
5170 oomUnsafe.crash("ShellAllocationMetadataBuilder::build");
5171 }
5172
5173 RootedObject stack(cx, NewDenseEmptyArray(cx));
5174 if (!stack) {
5175 oomUnsafe.crash("ShellAllocationMetadataBuilder::build");
5176 }
5177
5178 static int createdIndex = 0;
5179 createdIndex++;
5180
5181 if (!JS_DefineProperty(cx, obj, "index", createdIndex, 0)) {
5182 oomUnsafe.crash("ShellAllocationMetadataBuilder::build");
5183 }
5184
5185 if (!JS_DefineProperty(cx, obj, "stack", stack, 0)) {
5186 oomUnsafe.crash("ShellAllocationMetadataBuilder::build");
5187 }
5188
5189 int stackIndex = 0;
5190 RootedId id(cx);
5191 RootedValue callee(cx);
5192 for (NonBuiltinScriptFrameIter iter(cx); !iter.done(); ++iter) {
5193 if (iter.isFunctionFrame() && iter.compartment() == cx->compartment()) {
5194 id = PropertyKey::Int(stackIndex);
5195 RootedObject callee(cx, iter.callee(cx));
5196 if (!JS_DefinePropertyById(cx, stack, id, callee, JSPROP_ENUMERATE)) {
5197 oomUnsafe.crash("ShellAllocationMetadataBuilder::build");
5198 }
5199 stackIndex++;
5200 }
5201 }
5202
5203 return obj;
5204 }
5205
5206 const ShellAllocationMetadataBuilder
5207 ShellAllocationMetadataBuilder::metadataBuilder;
5208
5209 static bool EnableShellAllocationMetadataBuilder(JSContext* cx, unsigned argc,
5210 Value* vp) {
5211 CallArgs args = CallArgsFromVp(argc, vp);
5212
5213 SetAllocationMetadataBuilder(
5214 cx, &ShellAllocationMetadataBuilder::metadataBuilder);
5215
5216 args.rval().setUndefined();
5217 return true;
5218 }
5219
5220 static bool GetAllocationMetadata(JSContext* cx, unsigned argc, Value* vp) {
5221 CallArgs args = CallArgsFromVp(argc, vp);
5222 if (args.length() != 1 || !args[0].isObject()) {
5223 JS_ReportErrorASCII(cx, "Argument must be an object");
5224 return false;
5225 }
5226
5227 args.rval().setObjectOrNull(GetAllocationMetadata(&args[0].toObject()));
5228 return true;
5229 }
5230
5231 static bool testingFunc_bailout(JSContext* cx, unsigned argc, Value* vp) {
5232 CallArgs args = CallArgsFromVp(argc, vp);
5233
5234 // NOP when not in IonMonkey
5235 args.rval().setUndefined();
5236 return true;
5237 }
5238
5239 static bool testingFunc_bailAfter(JSContext* cx, unsigned argc, Value* vp) {
5240 CallArgs args = CallArgsFromVp(argc, vp);
5241 if (args.length() != 1 || !args[0].isInt32() || args[0].toInt32() < 0) {
5242 JS_ReportErrorASCII(
5243 cx, "Argument must be a positive number that fits in an int32");
5244 return false;
5245 }
5246
5247 #ifdef DEBUG
5248 if (auto* jitRuntime = cx->runtime()->jitRuntime()) {
5249 uint32_t bailAfter = args[0].toInt32();
5250 bool enableBailAfter = bailAfter > 0;
5251 if (jitRuntime->ionBailAfterEnabled() != enableBailAfter) {
5252 // Force JIT code to be recompiled with (or without) instrumentation.
5253 ReleaseAllJITCode(cx->gcContext());
5254 jitRuntime->setIonBailAfterEnabled(enableBailAfter);
5255 }
5256 jitRuntime->setIonBailAfterCounter(bailAfter);
5257 }
5258 #endif
5259
5260 args.rval().setUndefined();
5261 return true;
5262 }
5263
5264 static bool testingFunc_invalidate(JSContext* cx, unsigned argc, Value* vp) {
5265 CallArgs args = CallArgsFromVp(argc, vp);
5266
5267 // If the topmost frame is Ion/Warp, find the IonScript and invalidate it.
5268 FrameIter iter(cx);
5269 if (!iter.done() && iter.isIon()) {
5270 while (!iter.isPhysicalJitFrame()) {
5271 ++iter;
5272 }
5273 if (iter.script()->hasIonScript()) {
5274 js::jit::Invalidate(cx, iter.script());
5275 }
5276 }
5277
5278 args.rval().setUndefined();
5279 return true;
5280 }
5281
5282 static constexpr unsigned JitWarmupResetLimit = 20;
5283 static_assert(JitWarmupResetLimit <=
5284 unsigned(JSScript::MutableFlags::WarmupResets_MASK),
5285 "JitWarmupResetLimit exceeds max value");
5286
5287 static bool testingFunc_inJit(JSContext* cx, unsigned argc, Value* vp) {
5288 CallArgs args = CallArgsFromVp(argc, vp);
5289
5290 if (!jit::IsBaselineJitEnabled(cx)) {
5291 return ReturnStringCopy(cx, args, "Baseline is disabled.");
5292 }
5293
5294 // Use frame iterator to inspect caller.
5295 FrameIter iter(cx);
5296
5297 // We may be invoked directly, not in a JS context, e.g. if inJit is added as
5298 // a callback on the event queue.
5299 if (iter.done()) {
5300 args.rval().setBoolean(false);
5301 return true;
5302 }
5303
5304 if (iter.hasScript()) {
5305 // Detect repeated attempts to compile, resetting the counter if inJit
5306 // succeeds. Note: This script may have be inlined into its caller.
5307 if (iter.isJSJit()) {
5308 iter.script()->resetWarmUpResetCounter();
5309 } else if (iter.script()->getWarmUpResetCount() >= JitWarmupResetLimit) {
5310 return ReturnStringCopy(
5311 cx, args, "Compilation is being repeatedly prevented. Giving up.");
5312 }
5313 }
5314
5315 // Returns true for any JIT (including WASM).
5316 MOZ_ASSERT_IF(iter.isJSJit(), cx->currentlyRunningInJit());
5317 args.rval().setBoolean(cx->currentlyRunningInJit());
5318 return true;
5319 }
5320
5321 static bool testingFunc_inIon(JSContext* cx, unsigned argc, Value* vp) {
5322 CallArgs args = CallArgsFromVp(argc, vp);
5323
5324 if (!jit::IsIonEnabled(cx)) {
5325 return ReturnStringCopy(cx, args, "Ion is disabled.");
5326 }
5327
5328 // Use frame iterator to inspect caller.
5329 FrameIter iter(cx);
5330
5331 // We may be invoked directly, not in a JS context, e.g. if inIon is added as
5332 // a callback on the event queue.
5333 if (iter.done()) {
5334 args.rval().setBoolean(false);
5335 return true;
5336 }
5337
5338 if (iter.hasScript()) {
5339 // Detect repeated attempts to compile, resetting the counter if inIon
5340 // succeeds. Note: This script may have be inlined into its caller.
5341 if (iter.isIon()) {
5342 iter.script()->resetWarmUpResetCounter();
5343 } else if (!iter.script()->canIonCompile()) {
5344 return ReturnStringCopy(cx, args, "Unable to Ion-compile this script.");
5345 } else if (iter.script()->getWarmUpResetCount() >= JitWarmupResetLimit) {
5346 return ReturnStringCopy(
5347 cx, args, "Compilation is being repeatedly prevented. Giving up.");
5348 }
5349 }
5350
5351 args.rval().setBoolean(iter.isIon());
5352 return true;
5353 }
5354
5355 bool js::testingFunc_assertFloat32(JSContext* cx, unsigned argc, Value* vp) {
5356 CallArgs args = CallArgsFromVp(argc, vp);
5357 if (args.length() != 2) {
5358 JS_ReportErrorASCII(cx, "Expects only 2 arguments");
5359 return false;
5360 }
5361
5362 // NOP when not in IonMonkey
5363 args.rval().setUndefined();
5364 return true;
5365 }
5366
5367 static bool TestingFunc_assertJitStackInvariants(JSContext* cx, unsigned argc,
5368 Value* vp) {
5369 CallArgs args = CallArgsFromVp(argc, vp);
5370
5371 jit::AssertJitStackInvariants(cx);
5372 args.rval().setUndefined();
5373 return true;
5374 }
5375
5376 bool js::testingFunc_assertRecoveredOnBailout(JSContext* cx, unsigned argc,
5377 Value* vp) {
5378 CallArgs args = CallArgsFromVp(argc, vp);
5379 if (args.length() != 2) {
5380 JS_ReportErrorASCII(cx, "Expects only 2 arguments");
5381 return false;
5382 }
5383
5384 // NOP when not in IonMonkey
5385 args.rval().setUndefined();
5386 return true;
5387 }
5388
5389 static bool GetJitCompilerOptions(JSContext* cx, unsigned argc, Value* vp) {
5390 CallArgs args = CallArgsFromVp(argc, vp);
5391 RootedObject info(cx, JS_NewPlainObject(cx));
5392 if (!info) {
5393 return false;
5394 }
5395
5396 uint32_t intValue = 0;
5397 RootedValue value(cx);
5398
5399 #define JIT_COMPILER_MATCH(key, string) \
5400 opt = JSJITCOMPILER_##key; \
5401 if (JS_GetGlobalJitCompilerOption(cx, opt, &intValue)) { \
5402 value.setInt32(intValue); \
5403 if (!JS_SetProperty(cx, info, string, value)) return false; \
5404 }
5405
5406 JSJitCompilerOption opt = JSJITCOMPILER_NOT_AN_OPTION;
5407 JIT_COMPILER_OPTIONS(JIT_COMPILER_MATCH);
5408 #undef JIT_COMPILER_MATCH
5409
5410 args.rval().setObject(*info);
5411 return true;
5412 }
5413
5414 static bool SetIonCheckGraphCoherency(JSContext* cx, unsigned argc, Value* vp) {
5415 CallArgs args = CallArgsFromVp(argc, vp);
5416 jit::JitOptions.checkGraphConsistency = ToBoolean(args.get(0));
5417 args.rval().setUndefined();
5418 return true;
5419 }
5420
5421 // A JSObject that holds structured clone data, similar to the C++ class
5422 // JSAutoStructuredCloneBuffer.
5423 class CloneBufferObject : public NativeObject {
5424 static const JSPropertySpec props_[3];
5425
5426 static const size_t DATA_SLOT = 0;
5427 static const size_t SYNTHETIC_SLOT = 1;
5428 static const size_t NUM_SLOTS = 2;
5429
5430 public:
5431 static const JSClass class_;
5432
5433 static CloneBufferObject* Create(JSContext* cx) {
5434 RootedObject obj(cx, JS_NewObject(cx, &class_));
5435 if (!obj) {
5436 return nullptr;
5437 }
5438 obj->as<CloneBufferObject>().setReservedSlot(DATA_SLOT,
5439 PrivateValue(nullptr));
5440 obj->as<CloneBufferObject>().setReservedSlot(SYNTHETIC_SLOT,
5441 BooleanValue(false));
5442
5443 if (!JS_DefineProperties(cx, obj, props_)) {
5444 return nullptr;
5445 }
5446
5447 return &obj->as<CloneBufferObject>();
5448 }
5449
5450 static CloneBufferObject* Create(JSContext* cx,
5451 JSAutoStructuredCloneBuffer* buffer) {
5452 Rooted<CloneBufferObject*> obj(cx, Create(cx));
5453 if (!obj) {
5454 return nullptr;
5455 }
5456 auto data = js::MakeUnique<JSStructuredCloneData>(buffer->scope());
5457 if (!data) {
5458 ReportOutOfMemory(cx);
5459 return nullptr;
5460 }
5461 buffer->giveTo(data.get());
5462 obj->setData(data.release(), false);
5463 return obj;
5464 }
5465
5466 JSStructuredCloneData* data() const {
5467 return static_cast<JSStructuredCloneData*>(
5468 getReservedSlot(DATA_SLOT).toPrivate());
5469 }
5470
5471 bool isSynthetic() const {
5472 return getReservedSlot(SYNTHETIC_SLOT).toBoolean();
5473 }
5474
5475 void setData(JSStructuredCloneData* aData, bool synthetic) {
5476 MOZ_ASSERT(!data());
5477 setReservedSlot(DATA_SLOT, PrivateValue(aData));
5478 setReservedSlot(SYNTHETIC_SLOT, BooleanValue(synthetic));
5479 }
5480
5481 // Discard an owned clone buffer.
5482 void discard() {
5483 js_delete(data());
5484 setReservedSlot(DATA_SLOT, PrivateValue(nullptr));
5485 }
5486
5487 static bool setCloneBuffer_impl(JSContext* cx, const CallArgs& args) {
5488 Rooted<CloneBufferObject*> obj(
5489 cx, &args.thisv().toObject().as<CloneBufferObject>());
5490
5491 const char* data = nullptr;
5492 UniqueChars dataOwner;
5493 size_t nbytes;
5494
5495 if (args.get(0).isObject() && args[0].toObject().is<ArrayBufferObject>()) {
5496 ArrayBufferObject* buffer = &args[0].toObject().as<ArrayBufferObject>();
5497 bool isSharedMemory;
5498 uint8_t* dataBytes = nullptr;
5499 JS::GetArrayBufferLengthAndData(buffer, &nbytes, &isSharedMemory,
5500 &dataBytes);
5501 MOZ_ASSERT(!isSharedMemory);
5502 data = reinterpret_cast<char*>(dataBytes);
5503 } else {
5504 JSString* str = JS::ToString(cx, args.get(0));
5505 if (!str) {
5506 return false;
5507 }
5508 dataOwner = JS_EncodeStringToLatin1(cx, str);
5509 if (!dataOwner) {
5510 return false;
5511 }
5512 data = dataOwner.get();
5513 nbytes = JS_GetStringLength(str);
5514 }
5515
5516 if (nbytes == 0 || (nbytes % sizeof(uint64_t) != 0)) {
5517 JS_ReportErrorASCII(cx, "Invalid length for clonebuffer data");
5518 return false;
5519 }
5520
5521 auto buf = js::MakeUnique<JSStructuredCloneData>(
5522 JS::StructuredCloneScope::DifferentProcess);
5523 if (!buf || !buf->Init(nbytes)) {
5524 ReportOutOfMemory(cx);
5525 return false;
5526 }
5527
5528 MOZ_ALWAYS_TRUE(buf->AppendBytes(data, nbytes));
5529 obj->discard();
5530 obj->setData(buf.release(), true);
5531
5532 args.rval().setUndefined();
5533 return true;
5534 }
5535
5536 static bool is(HandleValue v) {
5537 return v.isObject() && v.toObject().is<CloneBufferObject>();
5538 }
5539
5540 static bool setCloneBuffer(JSContext* cx, unsigned int argc, JS::Value* vp) {
5541 CallArgs args = CallArgsFromVp(argc, vp);
5542 return CallNonGenericMethod<is, setCloneBuffer_impl>(cx, args);
5543 }
5544
5545 static bool getData(JSContext* cx, Handle<CloneBufferObject*> obj,
5546 JSStructuredCloneData** data) {
5547 if (!obj->data()) {
5548 *data = nullptr;
5549 return true;
5550 }
5551
5552 bool hasTransferable;
5553 if (!JS_StructuredCloneHasTransferables(*obj->data(), &hasTransferable)) {
5554 return false;
5555 }
5556
5557 if (hasTransferable) {
5558 JS_ReportErrorASCII(
5559 cx, "cannot retrieve structured clone buffer with transferables");
5560 return false;
5561 }
5562
5563 *data = obj->data();
5564 return true;
5565 }
5566
5567 static bool getCloneBuffer_impl(JSContext* cx, const CallArgs& args) {
5568 Rooted<CloneBufferObject*> obj(
5569 cx, &args.thisv().toObject().as<CloneBufferObject>());
5570 if (args.length() != 0) {
5571 RootedObject callee(cx, &args.callee());
5572 ReportUsageErrorASCII(cx, callee, "Too many arguments");
5573 return false;
5574 }
5575
5576 JSStructuredCloneData* data;
5577 if (!getData(cx, obj, &data)) {
5578 return false;
5579 }
5580
5581 if (data == nullptr) {
5582 args.rval().setUndefined();
5583 return true;
5584 }
5585
5586 size_t size = data->Size();
5587 UniqueChars buffer(js_pod_malloc<char>(size));
5588 if (!buffer) {
5589 ReportOutOfMemory(cx);
5590 return false;
5591 }
5592 auto iter = data->Start();
5593 if (!data->ReadBytes(iter, buffer.get(), size)) {
5594 ReportOutOfMemory(cx);
5595 return false;
5596 }
5597 JSString* str = JS_NewStringCopyN(cx, buffer.get(), size);
5598 if (!str) {
5599 return false;
5600 }
5601 args.rval().setString(str);
5602 return true;
5603 }
5604
5605 static bool getCloneBuffer(JSContext* cx, unsigned int argc, JS::Value* vp) {
5606 CallArgs args = CallArgsFromVp(argc, vp);
5607 return CallNonGenericMethod<is, getCloneBuffer_impl>(cx, args);
5608 }
5609
5610 static bool getCloneBufferAsArrayBuffer_impl(JSContext* cx,
5611 const CallArgs& args) {
5612 Rooted<CloneBufferObject*> obj(
5613 cx, &args.thisv().toObject().as<CloneBufferObject>());
5614 if (args.length() != 0) {
5615 RootedObject callee(cx, &args.callee());
5616 ReportUsageErrorASCII(cx, callee, "Too many arguments");
5617 return false;
5618 }
5619
5620 JSStructuredCloneData* data;
5621 if (!getData(cx, obj, &data)) {
5622 return false;
5623 }
5624
5625 if (data == nullptr) {
5626 args.rval().setUndefined();
5627 return true;
5628 }
5629
5630 size_t size = data->Size();
5631 UniqueChars buffer(js_pod_malloc<char>(size));
5632 if (!buffer) {
5633 ReportOutOfMemory(cx);
5634 return false;
5635 }
5636 auto iter = data->Start();
5637 if (!data->ReadBytes(iter, buffer.get(), size)) {
5638 ReportOutOfMemory(cx);
5639 return false;
5640 }
5641
5642 JSObject* arrayBuffer =
5643 JS::NewArrayBufferWithContents(cx, size, std::move(buffer));
5644 if (!arrayBuffer) {
5645 return false;
5646 }
5647
5648 args.rval().setObject(*arrayBuffer);
5649 return true;
5650 }
5651
5652 static bool getCloneBufferAsArrayBuffer(JSContext* cx, unsigned int argc,
5653 JS::Value* vp) {
5654 CallArgs args = CallArgsFromVp(argc, vp);
5655 return CallNonGenericMethod<is, getCloneBufferAsArrayBuffer_impl>(cx, args);
5656 }
5657
5658 static void Finalize(JS::GCContext* gcx, JSObject* obj) {
5659 obj->as<CloneBufferObject>().discard();
5660 }
5661 };
5662
5663 static const JSClassOps CloneBufferObjectClassOps = {
5664 nullptr, // addProperty
5665 nullptr, // delProperty
5666 nullptr, // enumerate
5667 nullptr, // newEnumerate
5668 nullptr, // resolve
5669 nullptr, // mayResolve
5670 CloneBufferObject::Finalize, // finalize
5671 nullptr, // call
5672 nullptr, // construct
5673 nullptr, // trace
5674 };
5675
5676 const JSClass CloneBufferObject::class_ = {
5677 "CloneBuffer",
5678 JSCLASS_HAS_RESERVED_SLOTS(CloneBufferObject::NUM_SLOTS) |
5679 JSCLASS_FOREGROUND_FINALIZE,
5680 &CloneBufferObjectClassOps,
5681 };
5682
5683 const JSPropertySpec CloneBufferObject::props_[] = {
5684 JS_PSGS("clonebuffer", getCloneBuffer, setCloneBuffer, 0),
5685 JS_PSGS("arraybuffer", getCloneBufferAsArrayBuffer, setCloneBuffer, 0),
5686 JS_PS_END,
5687 };
5688
5689 static mozilla::Maybe<JS::StructuredCloneScope> ParseCloneScope(
5690 JSContext* cx, HandleString str) {
5691 mozilla::Maybe<JS::StructuredCloneScope> scope;
5692
5693 JSLinearString* scopeStr = str->ensureLinear(cx);
5694 if (!scopeStr) {
5695 return scope;
5696 }
5697
5698 if (StringEqualsLiteral(scopeStr, "SameProcess")) {
5699 scope.emplace(JS::StructuredCloneScope::SameProcess);
5700 } else if (StringEqualsLiteral(scopeStr, "DifferentProcess")) {
5701 scope.emplace(JS::StructuredCloneScope::DifferentProcess);
5702 } else if (StringEqualsLiteral(scopeStr, "DifferentProcessForIndexedDB")) {
5703 scope.emplace(JS::StructuredCloneScope::DifferentProcessForIndexedDB);
5704 }
5705
5706 return scope;
5707 }
5708
5709 // A custom object that is serializable and transferable using
5710 // the engine's custom hooks. The callbacks log their activity
5711 // to a JSRuntime-wide log (tagging actions with IDs to distinguish them).
5712 class CustomSerializableObject : public NativeObject {
5713 static const size_t ID_SLOT = 0;
5714 static const size_t DETACHED_SLOT = 1;
5715 static const size_t BEHAVIOR_SLOT = 2;
5716 static const size_t NUM_SLOTS = 3;
5717
5718 static constexpr size_t MAX_LOG_LEN = 100;
5719
5720 // The activity log should be specific to a JSRuntime.
5721 struct ActivityLog {
5722 uint32_t buffer[MAX_LOG_LEN];
5723 size_t length = 0;
5724
5725 static MOZ_THREAD_LOCAL(ActivityLog*) self;
5726 static ActivityLog* getThreadLog() {
5727 if (!self.initialized() || !self.get()) {
5728 self.infallibleInit();
5729 AutoEnterOOMUnsafeRegion oomUnsafe;
5730 self.set(js_new<ActivityLog>());
5731 if (!self.get()) {
5732 oomUnsafe.crash("allocating activity log");
5733 }
5734 if (!TlsContext.get()->runtime()->atExit(
5735 [](void* vpData) {
5736 auto* log = static_cast<ActivityLog*>(vpData);
5737 js_delete(log);
5738 },
5739 self.get())) {
5740 oomUnsafe.crash("atExit");
5741 }
5742 }
5743 return self.get();
5744 }
5745
5746 static bool log(int32_t id, char action) {
5747 return getThreadLog()->logImpl(id, action);
5748 }
5749
5750 bool logImpl(int32_t id, char action) {
5751 if (length + 2 > MAX_LOG_LEN) {
5752 return false;
5753 }
5754 buffer[length++] = id;
5755 buffer[length++] = uint32_t(action);
5756 return true;
5757 }
5758 };
5759
5760 public:
5761 enum class Behavior {
5762 Nothing = 0,
5763 FailDuringReadTransfer = 1,
5764 FailDuringRead = 2
5765 };
5766
5767 static constexpr JSClass class_ = {
5768 "CustomSerializable",
5769 JSCLASS_HAS_RESERVED_SLOTS(NUM_SLOTS),
5770 };
5771
5772 static bool is(HandleValue v) {
5773 return v.isObject() && v.toObject().is<CustomSerializableObject>();
5774 }
5775
5776 static CustomSerializableObject* Create(JSContext* cx, int32_t id,
5777 Behavior behavior) {
5778 Rooted<CustomSerializableObject*> obj(
5779 cx, static_cast<CustomSerializableObject*>(JS_NewObject(cx, &class_)));
5780 if (!obj) {
5781 return nullptr;
5782 }
5783 obj->setReservedSlot(ID_SLOT, Int32Value(id));
5784 obj->setReservedSlot(DETACHED_SLOT, BooleanValue(false));
5785 obj->setReservedSlot(BEHAVIOR_SLOT,
5786 Int32Value(static_cast<int32_t>(behavior)));
5787
5788 if (!JS_DefineProperty(cx, obj, "log", getLog, clearLog, 0)) {
5789 return nullptr;
5790 }
5791
5792 return obj;
5793 }
5794
5795 public:
5796 static uint32_t tag() { return JS_SCTAG_USER_MIN; }
5797
5798 static bool log(int32_t id, char action) {
5799 return ActivityLog::log(id, action);
5800 }
5801 bool log(char action) {
5802 return log(getReservedSlot(ID_SLOT).toInt32(), action);
5803 }
5804
5805 void detach() { setReservedSlot(DETACHED_SLOT, BooleanValue(true)); }
5806 bool isDetached() { return getReservedSlot(DETACHED_SLOT).toBoolean(); }
5807
5808 uint32_t id() const { return getReservedSlot(ID_SLOT).toInt32(); }
5809 Behavior behavior() {
5810 return static_cast<Behavior>(getReservedSlot(BEHAVIOR_SLOT).toInt32());
5811 }
5812
5813 static bool getLog(JSContext* cx, unsigned int argc, JS::Value* vp) {
5814 CallArgs args = CallArgsFromVp(argc, vp);
5815 return CallNonGenericMethod<is, getLog_impl>(cx, args);
5816 }
5817
5818 static bool getLog_impl(JSContext* cx, const CallArgs& args) {
5819 Rooted<CustomSerializableObject*> obj(
5820 cx, &args.thisv().toObject().as<CustomSerializableObject>());
5821
5822 size_t len = ActivityLog::getThreadLog()->length;
5823 uint32_t* logBuffer = ActivityLog::getThreadLog()->buffer;
5824
5825 Rooted<ArrayObject*> result(cx, NewDenseFullyAllocatedArray(cx, len));
5826 if (!result) {
5827 return false;
5828 }
5829 result->ensureDenseInitializedLength(0, len);
5830
5831 for (size_t p = 0; p < len; p += 2) {
5832 int32_t id = int32_t(logBuffer[p]);
5833 char action = char(logBuffer[p + 1]);
5834 result->setDenseElement(p, Int32Value(id));
5835 JSString* str = JS_NewStringCopyN(cx, &action, 1);
5836 if (!str) {
5837 return false;
5838 }
5839 result->setDenseElement(p + 1, StringValue(str));
5840 }
5841
5842 args.rval().setObject(*result);
5843 return true;
5844 }
5845
5846 static bool clearLog(JSContext* cx, unsigned int argc, JS::Value* vp) {
5847 CallArgs args = CallArgsFromVp(argc, vp);
5848 if (!args.get(0).isNullOrUndefined()) {
5849 JS_ReportErrorASCII(cx, "log may only be assigned null/undefined");
5850 return false;
5851 }
5852 ActivityLog::getThreadLog()->length = 0;
5853 args.rval().setUndefined();
5854 return true;
5855 }
5856
5857 static bool Write(JSContext* cx, JSStructuredCloneWriter* w,
5858 JS::HandleObject aObj, bool* sameProcessScopeRequired,
5859 void* closure) {
5860 Rooted<CustomSerializableObject*> obj(cx);
5861
5862 if ((obj = aObj->maybeUnwrapIf<CustomSerializableObject>())) {
5863 obj->log('w');
5864 // Write a regular clone as a <tag, id> pair, followed by <0, behavior>.
5865 // Note that transferring will communicate the behavior via a different
5866 // mechanism.
5867 return JS_WriteUint32Pair(w, obj->tag(), obj->id()) &&
5868 JS_WriteUint32Pair(w, 0, static_cast<uint32_t>(obj->behavior()));
5869 }
5870
5871 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5872 JSMSG_SC_UNSUPPORTED_TYPE);
5873 return false;
5874 }
5875
5876 static JSObject* Read(JSContext* cx, JSStructuredCloneReader* r,
5877 const JS::CloneDataPolicy& cloneDataPolicy,
5878 uint32_t tag, uint32_t id, void* closure) {
5879 uint32_t dummy, behaviorData;
5880 if (!JS_ReadUint32Pair(r, &dummy, &behaviorData)) {
5881 return nullptr;
5882 }
5883 if (dummy != 0 || id > INT32_MAX) {
5884 JS_ReportErrorASCII(cx, "out of range");
5885 return nullptr;
5886 }
5887
5888 auto b = static_cast<Behavior>(behaviorData);
5889 Rooted<CustomSerializableObject*> obj(
5890 cx, Create(cx, static_cast<int32_t>(id), b));
5891 if (!obj) {
5892 return nullptr;
5893 }
5894
5895 obj->log('r');
5896 if (obj->behavior() == Behavior::FailDuringRead) {
5897 JS_ReportErrorASCII(cx,
5898 "Failed as requested in read during deserialization");
5899 return nullptr;
5900 }
5901 return obj;
5902 }
5903
5904 static bool CanTransfer(JSContext* cx, JS::Handle<JSObject*> wrapped,
5905 bool* sameProcessScopeRequired, void* closure) {
5906 Rooted<CustomSerializableObject*> obj(cx);
5907
5908 if ((obj = wrapped->maybeUnwrapIf<CustomSerializableObject>())) {
5909 obj->log('?');
5910 // For now, all CustomSerializable objects are considered to be
5911 // transferable.
5912 return true;
5913 }
5914
5915 return false;
5916 }
5917
5918 static bool WriteTransfer(JSContext* cx, JS::Handle<JSObject*> aObj,
5919 void* closure, uint32_t* tag,
5920 JS::TransferableOwnership* ownership,
5921 void** content, uint64_t* extraData) {
5922 Rooted<CustomSerializableObject*> obj(cx);
5923
5924 if ((obj = aObj->maybeUnwrapIf<CustomSerializableObject>())) {
5925 if (obj->isDetached()) {
5926 JS_ReportErrorASCII(cx, "Attempted to transfer detached object");
5927 return false;
5928 }
5929 obj->log('W');
5930 *content = reinterpret_cast<void*>(obj->id());
5931 *extraData = static_cast<uint64_t>(obj->behavior());
5932 *tag = obj->tag();
5933 *ownership = JS::SCTAG_TMO_CUSTOM;
5934 obj->detach();
5935 return true;
5936 }
5937
5938 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5939 JSMSG_SC_NOT_TRANSFERABLE);
5940 return false;
5941 }
5942
5943 static bool ReadTransfer(JSContext* cx, JSStructuredCloneReader* r,
5944 const JS::CloneDataPolicy& cloneDataPolicy,
5945 uint32_t tag, void* content, uint64_t extraData,
5946 void* closure,
5947 JS::MutableHandleObject returnObject) {
5948 if (tag == CustomSerializableObject::tag()) {
5949 int32_t id = int32_t(reinterpret_cast<uintptr_t>(content));
5950 Rooted<CustomSerializableObject*> obj(
5951 cx, CustomSerializableObject::Create(
5952 cx, id, static_cast<Behavior>(extraData)));
5953 if (!obj) {
5954 return false;
5955 }
5956 obj->log('R');
5957 if (obj->behavior() == Behavior::FailDuringReadTransfer) {
5958 return false;
5959 }
5960 returnObject.set(obj);
5961 return true;
5962 }
5963
5964 return false;
5965 }
5966
5967 static void FreeTransfer(uint32_t tag, JS::TransferableOwnership ownership,
5968 void* content, uint64_t extraData, void* closure) {
5969 CustomSerializableObject::log(uint32_t(reinterpret_cast<intptr_t>(content)),
5970 'F');
5971 }
5972 };
5973
5974 MOZ_THREAD_LOCAL(CustomSerializableObject::ActivityLog*)
5975 CustomSerializableObject::ActivityLog::self;
5976
5977 static bool MakeSerializable(JSContext* cx, unsigned argc, Value* vp) {
5978 CallArgs args = CallArgsFromVp(argc, vp);
5979
5980 int32_t id = 0;
5981 if (args.get(0).isInt32()) {
5982 id = args[0].toInt32();
5983 if (id < 0) {
5984 JS_ReportErrorASCII(cx, "id out of range");
5985 return false;
5986 }
5987 }
5988 CustomSerializableObject::Behavior behavior =
5989 CustomSerializableObject::Behavior::Nothing;
5990 if (args.get(1).isInt32()) {
5991 int32_t iv = args[1].toInt32();
5992 constexpr int32_t min =
5993 static_cast<int32_t>(CustomSerializableObject::Behavior::Nothing);
5994 constexpr int32_t max = static_cast<int32_t>(
5995 CustomSerializableObject::Behavior::FailDuringRead);
5996 if (iv < min || iv > max) {
5997 JS_ReportErrorASCII(cx, "behavior out of range");
5998 return false;
5999 }
6000 behavior = static_cast<CustomSerializableObject::Behavior>(iv);
6001 }
6002
6003 JSObject* obj = CustomSerializableObject::Create(cx, id, behavior);
6004 if (!obj) {
6005 return false;
6006 }
6007
6008 args.rval().setObject(*obj);
6009 return true;
6010 }
6011
6012 static JSStructuredCloneCallbacks gCloneCallbacks = {
6013 .read = CustomSerializableObject::Read,
6014 .write = CustomSerializableObject::Write,
6015 .reportError = nullptr,
6016 .readTransfer = CustomSerializableObject::ReadTransfer,
6017 .writeTransfer = CustomSerializableObject::WriteTransfer,
6018 .freeTransfer = CustomSerializableObject::FreeTransfer,
6019 .canTransfer = CustomSerializableObject::CanTransfer,
6020 .sabCloned = nullptr};
6021
6022 bool js::testingFunc_serialize(JSContext* cx, unsigned argc, Value* vp) {
6023 CallArgs args = CallArgsFromVp(argc, vp);
6024
6025 if (js::SupportDifferentialTesting()) {
6026 RootedObject callee(cx, &args.callee());
6027 ReportUsageErrorASCII(cx, callee,
6028 "Function unavailable in differential testing mode.");
6029 return false;
6030 }
6031
6032 mozilla::Maybe<JSAutoStructuredCloneBuffer> clonebuf;
6033 JS::CloneDataPolicy policy;
6034
6035 if (!args.get(2).isUndefined()) {
6036 RootedObject opts(cx, ToObject(cx, args.get(2)));
6037 if (!opts) {
6038 return false;
6039 }
6040
6041 RootedValue v(cx);
6042 if (!JS_GetProperty(cx, opts, "SharedArrayBuffer", &v)) {
6043 return false;
6044 }
6045
6046 if (!v.isUndefined()) {
6047 JSString* str = JS::ToString(cx, v);
6048 if (!str) {
6049 return false;
6050 }
6051 JSLinearString* poli = str->ensureLinear(cx);
6052 if (!poli) {
6053 return false;
6054 }
6055
6056 if (StringEqualsLiteral(poli, "allow")) {
6057 policy.allowSharedMemoryObjects();
6058 policy.allowIntraClusterClonableSharedObjects();
6059 } else if (StringEqualsLiteral(poli, "deny")) {
6060 // default
6061 } else {
6062 JS_ReportErrorASCII(cx, "Invalid policy value for 'SharedArrayBuffer'");
6063 return false;
6064 }
6065 }
6066
6067 if (!JS_GetProperty(cx, opts, "scope", &v)) {
6068 return false;
6069 }
6070
6071 if (!v.isUndefined()) {
6072 RootedString str(cx, JS::ToString(cx, v));
6073 if (!str) {
6074 return false;
6075 }
6076 auto scope = ParseCloneScope(cx, str);
6077 if (!scope) {
6078 JS_ReportErrorASCII(cx, "Invalid structured clone scope");
6079 return false;
6080 }
6081 clonebuf.emplace(*scope, &gCloneCallbacks, nullptr);
6082 }
6083 }
6084
6085 if (!clonebuf) {
6086 clonebuf.emplace(JS::StructuredCloneScope::SameProcess, &gCloneCallbacks,
6087 nullptr);
6088 }
6089
6090 if (!clonebuf->write(cx, args.get(0), args.get(1), policy)) {
6091 return false;
6092 }
6093
6094 RootedObject obj(cx, CloneBufferObject::Create(cx, clonebuf.ptr()));
6095 if (!obj) {
6096 return false;
6097 }
6098
6099 args.rval().setObject(*obj);
6100 return true;
6101 }
6102
6103 static bool Deserialize(JSContext* cx, unsigned argc, Value* vp) {
6104 CallArgs args = CallArgsFromVp(argc, vp);
6105
6106 if (js::SupportDifferentialTesting()) {
6107 RootedObject callee(cx, &args.callee());
6108 ReportUsageErrorASCII(cx, callee,
6109 "Function unavailable in differential testing mode.");
6110 return false;
6111 }
6112
6113 if (!args.get(0).isObject() || !args[0].toObject().is<CloneBufferObject>()) {
6114 JS_ReportErrorASCII(cx, "deserialize requires a clonebuffer argument");
6115 return false;
6116 }
6117 Rooted<CloneBufferObject*> obj(cx,
6118 &args[0].toObject().as<CloneBufferObject>());
6119
6120 JS::CloneDataPolicy policy;
6121
6122 JS::StructuredCloneScope scope =
6123 obj->isSynthetic() ? JS::StructuredCloneScope::DifferentProcess
6124 : JS::StructuredCloneScope::SameProcess;
6125 if (args.get(1).isObject()) {
6126 RootedObject opts(cx, &args[1].toObject());
6127 if (!opts) {
6128 return false;
6129 }
6130
6131 RootedValue v(cx);
6132 if (!JS_GetProperty(cx, opts, "SharedArrayBuffer", &v)) {
6133 return false;
6134 }
6135
6136 if (!v.isUndefined()) {
6137 JSString* str = JS::ToString(cx, v);
6138 if (!str) {
6139 return false;
6140 }
6141 JSLinearString* poli = str->ensureLinear(cx);
6142 if (!poli) {
6143 return false;
6144 }
6145
6146 if (StringEqualsLiteral(poli, "allow")) {
6147 policy.allowSharedMemoryObjects();
6148 policy.allowIntraClusterClonableSharedObjects();
6149 } else if (StringEqualsLiteral(poli, "deny")) {
6150 // default
6151 } else {
6152 JS_ReportErrorASCII(cx, "Invalid policy value for 'SharedArrayBuffer'");
6153 return false;
6154 }
6155 }
6156
6157 if (!JS_GetProperty(cx, opts, "scope", &v)) {
6158 return false;
6159 }
6160
6161 if (!v.isUndefined()) {
6162 RootedString str(cx, JS::ToString(cx, v));
6163 if (!str) {
6164 return false;
6165 }
6166 auto maybeScope = ParseCloneScope(cx, str);
6167 if (!maybeScope) {
6168 JS_ReportErrorASCII(cx, "Invalid structured clone scope");
6169 return false;
6170 }
6171
6172 if (*maybeScope < scope) {
6173 JS_ReportErrorASCII(cx,
6174 "Cannot use less restrictive scope "
6175 "than the deserialized clone buffer's scope");
6176 return false;
6177 }
6178
6179 scope = *maybeScope;
6180 }
6181 }
6182
6183 if (scope > JS::StructuredCloneScope::SameProcess &&
6184 (policy.areIntraClusterClonableSharedObjectsAllowed() ||
6185 policy.areSharedMemoryObjectsAllowed())) {
6186 JS_ReportErrorASCII(
6187 cx, "deserialize in DifferentProcess scope cannot allow shared memory");
6188 return false;
6189 }
6190
6191 // Clone buffer was already consumed?
6192 if (!obj->data()) {
6193 JS_ReportErrorASCII(cx,
6194 "deserialize given invalid clone buffer "
6195 "(transferables already consumed?)");
6196 return false;
6197 }
6198
6199 bool hasTransferable;
6200 if (!JS_StructuredCloneHasTransferables(*obj->data(), &hasTransferable)) {
6201 return false;
6202 }
6203
6204 RootedValue deserialized(cx);
6205 if (!JS_ReadStructuredClone(cx, *obj->data(), JS_STRUCTURED_CLONE_VERSION,
6206 scope, &deserialized, policy, &gCloneCallbacks,
6207 nullptr)) {
6208 return false;
6209 }
6210 args.rval().set(deserialized);
6211
6212 // Consume any clone buffer with transferables; throw an error if it is
6213 // deserialized again.
6214 if (hasTransferable) {
6215 obj->discard();
6216 }
6217
6218 return true;
6219 }
6220
6221 static bool DetachArrayBuffer(JSContext* cx, unsigned argc, Value* vp) {
6222 CallArgs args = CallArgsFromVp(argc, vp);
6223
6224 if (args.length() != 1) {
6225 JS_ReportErrorASCII(cx, "detachArrayBuffer() requires a single argument");
6226 return false;
6227 }
6228
6229 if (!args[0].isObject()) {
6230 JS_ReportErrorASCII(cx, "detachArrayBuffer must be passed an object");
6231 return false;
6232 }
6233
6234 RootedObject obj(cx, &args[0].toObject());
6235 if (!JS::DetachArrayBuffer(cx, obj)) {
6236 return false;
6237 }
6238
6239 args.rval().setUndefined();
6240 return true;
6241 }
6242
6243 static bool EnsureNonInline(JSContext* cx, unsigned argc, Value* vp) {
6244 CallArgs args = CallArgsFromVp(argc, vp);
6245 Rooted<JSObject*> callee(cx, &args.callee());
6246
6247 if (!args.get(0).isObject()) {
6248 js::ReportUsageErrorASCII(cx, callee, "Single object argument required");
6249 return false;
6250 }
6251
6252 RootedObject obj(cx, &args[0].toObject());
6253 if (!JS::EnsureNonInlineArrayBufferOrView(cx, obj)) {
6254 return false;
6255 }
6256
6257 args.rval().setUndefined();
6258 return true;
6259 }
6260
6261 static bool PinArrayBufferOrViewLength(JSContext* cx, unsigned argc,
6262 Value* vp) {
6263 CallArgs args = CallArgsFromVp(argc, vp);
6264 Rooted<JSObject*> callee(cx, &args.callee());
6265
6266 if (!args.get(0).isObject()) {
6267 js::ReportUsageErrorASCII(
6268 cx, callee, "ArrayBuffer or ArrayBufferView argument required");
6269 return false;
6270 }
6271 RootedObject obj(cx, &args[0].toObject());
6272 if (!obj->canUnwrapAs<ArrayBufferViewObject>() &&
6273 !obj->canUnwrapAs<ArrayBufferObjectMaybeShared>()) {
6274 js::ReportUsageErrorASCII(
6275 cx, callee, "ArrayBuffer or ArrayBufferView argument required");
6276 return false;
6277 }
6278
6279 bool pin = args.get(1).isUndefined() ? true : ToBoolean(args.get(1));
6280
6281 args.rval().setBoolean(JS::PinArrayBufferOrViewLength(obj, pin));
6282 return true;
6283 }
6284
6285 static bool JSONStringify(JSContext* cx, unsigned argc, Value* vp) {
6286 CallArgs args = CallArgsFromVp(argc, vp);
6287
6288 RootedValue value(cx, args.get(0));
6289 RootedValue behaviorVal(cx, args.get(1));
6290 StringifyBehavior behavior = StringifyBehavior::Normal;
6291 if (behaviorVal.isString()) {
6292 bool matches;
6293 #define MATCH(name) \
6294 if (!JS_StringEqualsLiteral(cx, behaviorVal.toString(), #name, &matches)) { \
6295 return false; \
6296 } \
6297 if (matches) { \
6298 behavior = StringifyBehavior::name; \
6299 }
6300 MATCH(Normal)
6301 MATCH(FastOnly)
6302 MATCH(SlowOnly)
6303 MATCH(Compare)
6304 #undef MATCH
6305 }
6306
6307 JSStringBuilder sb(cx);
6308 if (!Stringify(cx, &value, nullptr, UndefinedValue(), sb, behavior)) {
6309 return false;
6310 }
6311
6312 if (!sb.empty()) {
6313 JSString* str = sb.finishString();
6314 if (!str) {
6315 return false;
6316 }
6317 args.rval().setString(str);
6318 } else {
6319 args.rval().setUndefined();
6320 }
6321
6322 return true;
6323 }
6324
6325 static bool HelperThreadCount(JSContext* cx, unsigned argc, Value* vp) {
6326 CallArgs args = CallArgsFromVp(argc, vp);
6327
6328 if (js::SupportDifferentialTesting()) {
6329 // Always return 0 to get consistent output with and without --no-threads.
6330 args.rval().setInt32(0);
6331 return true;
6332 }
6333
6334 if (CanUseExtraThreads()) {
6335 args.rval().setInt32(GetHelperThreadCount());
6336 } else {
6337 args.rval().setInt32(0);
6338 }
6339 return true;
6340 }
6341
6342 static bool EnableShapeConsistencyChecks(JSContext* cx, unsigned argc,
6343 Value* vp) {
6344 CallArgs args = CallArgsFromVp(argc, vp);
6345 #ifdef DEBUG
6346 NativeObject::enableShapeConsistencyChecks();
6347 #endif
6348 args.rval().setUndefined();
6349 return true;
6350 }
6351
6352 // ShapeSnapshot holds information about an object's properties. This is used
6353 // for checking object and shape changes between two points in time.
6354 class ShapeSnapshot {
6355 HeapPtr<JSObject*> object_;
6356 HeapPtr<Shape*> shape_;
6357 HeapPtr<BaseShape*> baseShape_;
6358 ObjectFlags objectFlags_;
6359
6360 GCVector<HeapPtr<Value>, 8> slots_;
6361
6362 struct PropertySnapshot {
6363 HeapPtr<PropMap*> propMap;
6364 uint32_t propMapIndex;
6365 HeapPtr<PropertyKey> key;
6366 PropertyInfo prop;
6367
6368 explicit PropertySnapshot(PropMap* map, uint32_t index)
6369 : propMap(map),
6370 propMapIndex(index),
6371 key(map->getKey(index)),
6372 prop(map->getPropertyInfo(index)) {}
6373
6374 void trace(JSTracer* trc) {
6375 TraceEdge(trc, &propMap, "propMap");
6376 TraceEdge(trc, &key, "key");
6377 }
6378
6379 bool operator==(const PropertySnapshot& other) const {
6380 return propMap == other.propMap && propMapIndex == other.propMapIndex &&
6381 key == other.key && prop == other.prop;
6382 }
6383 bool operator!=(const PropertySnapshot& other) const {
6384 return !operator==(other);
6385 }
6386 };
6387 GCVector<PropertySnapshot, 8> properties_;
6388
6389 public:
6390 explicit ShapeSnapshot(JSContext* cx) : slots_(cx), properties_(cx) {}
6391 void checkSelf(JSContext* cx) const;
6392 void check(JSContext* cx, const ShapeSnapshot& other) const;
6393 bool init(JSObject* obj);
6394 void trace(JSTracer* trc);
6395
6396 JSObject* object() const { return object_; }
6397 };
6398
6399 // A JSObject that holds a ShapeSnapshot.
6400 class ShapeSnapshotObject : public NativeObject {
6401 static constexpr size_t SnapshotSlot = 0;
6402 static constexpr size_t ReservedSlots = 1;
6403
6404 public:
6405 static const JSClassOps classOps_;
6406 static const JSClass class_;
6407
6408 bool hasSnapshot() const {
6409 // The snapshot may not be present yet if we GC during initialization.
6410 return !getReservedSlot(SnapshotSlot).isUndefined();
6411 }
6412
6413 ShapeSnapshot& snapshot() const {
6414 void* ptr = getReservedSlot(SnapshotSlot).toPrivate();
6415 MOZ_ASSERT(ptr);
6416 return *static_cast<ShapeSnapshot*>(ptr);
6417 }
6418
6419 static ShapeSnapshotObject* create(JSContext* cx, HandleObject obj);
6420
6421 static void finalize(JS::GCContext* gcx, JSObject* obj) {
6422 if (obj->as<ShapeSnapshotObject>().hasSnapshot()) {
6423 js_delete(&obj->as<ShapeSnapshotObject>().snapshot());
6424 }
6425 }
6426 static void trace(JSTracer* trc, JSObject* obj) {
6427 if (obj->as<ShapeSnapshotObject>().hasSnapshot()) {
6428 obj->as<ShapeSnapshotObject>().snapshot().trace(trc);
6429 }
6430 }
6431 };
6432
6433 /*static */ const JSClassOps ShapeSnapshotObject::classOps_ = {
6434 nullptr, // addProperty
6435 nullptr, // delProperty
6436 nullptr, // enumerate
6437 nullptr, // newEnumerate
6438 nullptr, // resolve
6439 nullptr, // mayResolve
6440 ShapeSnapshotObject::finalize, // finalize
6441 nullptr, // call
6442 nullptr, // construct
6443 ShapeSnapshotObject::trace, // trace
6444 };
6445
6446 /*static */ const JSClass ShapeSnapshotObject::class_ = {
6447 "ShapeSnapshotObject",
6448 JSCLASS_HAS_RESERVED_SLOTS(ShapeSnapshotObject::ReservedSlots) |
6449 JSCLASS_BACKGROUND_FINALIZE,
6450 &ShapeSnapshotObject::classOps_,
6451 };
6452
6453 bool ShapeSnapshot::init(JSObject* obj) {
6454 object_ = obj;
6455 shape_ = obj->shape();
6456 baseShape_ = shape_->base();
6457 objectFlags_ = shape_->objectFlags();
6458
6459 if (obj->is<NativeObject>()) {
6460 NativeObject* nobj = &obj->as<NativeObject>();
6461
6462 // Snapshot the slot values.
6463 size_t slotSpan = nobj->slotSpan();
6464 if (!slots_.growBy(slotSpan)) {
6465 return false;
6466 }
6467 for (size_t i = 0; i < slotSpan; i++) {
6468 slots_[i] = nobj->getSlot(i);
6469 }
6470
6471 // Snapshot property information.
6472 if (uint32_t len = nobj->shape()->propMapLength(); len > 0) {
6473 PropMap* map = nobj->shape()->propMap();
6474 while (true) {
6475 for (uint32_t i = 0; i < len; i++) {
6476 if (!map->hasKey(i)) {
6477 continue;
6478 }
6479 if (!properties_.append(PropertySnapshot(map, i))) {
6480 return false;
6481 }
6482 }
6483 if (!map->hasPrevious()) {
6484 break;
6485 }
6486 map = map->asLinked()->previous();
6487 len = PropMap::Capacity;
6488 }
6489 }
6490 }
6491
6492 return true;
6493 }
6494
6495 void ShapeSnapshot::trace(JSTracer* trc) {
6496 TraceEdge(trc, &object_, "object");
6497 TraceEdge(trc, &shape_, "shape");
6498 TraceEdge(trc, &baseShape_, "baseShape");
6499 slots_.trace(trc);
6500 properties_.trace(trc);
6501 }
6502
6503 void ShapeSnapshot::checkSelf(JSContext* cx) const {
6504 // Assertions based on a single snapshot.
6505
6506 // Non-dictionary shapes must not be mutated.
6507 if (!shape_->isDictionary()) {
6508 MOZ_RELEASE_ASSERT(shape_->base() == baseShape_);
6509 MOZ_RELEASE_ASSERT(shape_->objectFlags() == objectFlags_);
6510 }
6511
6512 for (const PropertySnapshot& propSnapshot : properties_) {
6513 PropMap* propMap = propSnapshot.propMap;
6514 uint32_t propMapIndex = propSnapshot.propMapIndex;
6515 PropertyInfo prop = propSnapshot.prop;
6516
6517 // Skip if the map no longer matches the snapshotted data. This can
6518 // only happen for dictionary maps because they can be mutated or compacted
6519 // after a shape change.
6520 if (!propMap->hasKey(propMapIndex) ||
6521 PropertySnapshot(propMap, propMapIndex) != propSnapshot) {
6522 MOZ_RELEASE_ASSERT(propMap->isDictionary());
6523 MOZ_RELEASE_ASSERT(object_->shape() != shape_);
6524 continue;
6525 }
6526
6527 // Ensure ObjectFlags depending on property information are set if needed.
6528 ObjectFlags expectedFlags = GetObjectFlagsForNewProperty(
6529 shape_->getObjectClass(), shape_->objectFlags(), propSnapshot.key,
6530 prop.flags(), cx);
6531 MOZ_RELEASE_ASSERT(expectedFlags == objectFlags_);
6532
6533 // Accessors must have a PrivateGCThingValue(GetterSetter*) slot value.
6534 if (prop.isAccessorProperty()) {
6535 Value slotVal = slots_[prop.slot()];
6536 MOZ_RELEASE_ASSERT(slotVal.isPrivateGCThing());
6537 MOZ_RELEASE_ASSERT(slotVal.toGCThing()->is<GetterSetter>());
6538 }
6539
6540 // Data properties must not have a PrivateGCThingValue slot value.
6541 if (prop.isDataProperty()) {
6542 Value slotVal = slots_[prop.slot()];
6543 MOZ_RELEASE_ASSERT(!slotVal.isPrivateGCThing());
6544 }
6545 }
6546 }
6547
6548 void ShapeSnapshot::check(JSContext* cx, const ShapeSnapshot& later) const {
6549 checkSelf(cx);
6550 later.checkSelf(cx);
6551
6552 if (object_ != later.object_) {
6553 // Snapshots are for different objects. Assert dictionary shapes aren't
6554 // shared.
6555 if (object_->is<NativeObject>()) {
6556 NativeObject* nobj = &object_->as<NativeObject>();
6557 if (nobj->inDictionaryMode()) {
6558 MOZ_RELEASE_ASSERT(nobj->shape() != later.shape_);
6559 }
6560 }
6561 return;
6562 }
6563
6564 // We have two snapshots for the same object. Check the shape information
6565 // wasn't changed in invalid ways.
6566
6567 // If the Shape is still the same, the object must have the same BaseShape,
6568 // ObjectFlags and property information.
6569 if (shape_ == later.shape_) {
6570 MOZ_RELEASE_ASSERT(objectFlags_ == later.objectFlags_);
6571 MOZ_RELEASE_ASSERT(baseShape_ == later.baseShape_);
6572 MOZ_RELEASE_ASSERT(slots_.length() == later.slots_.length());
6573 MOZ_RELEASE_ASSERT(properties_.length() == later.properties_.length());
6574
6575 for (size_t i = 0; i < properties_.length(); i++) {
6576 MOZ_RELEASE_ASSERT(properties_[i] == later.properties_[i]);
6577 // Non-configurable accessor properties and non-configurable, non-writable
6578 // data properties shouldn't have had their slot mutated.
6579 PropertyInfo prop = properties_[i].prop;
6580 if (!prop.configurable()) {
6581 if (prop.isAccessorProperty() ||
6582 (prop.isDataProperty() && !prop.writable())) {
6583 size_t slot = prop.slot();
6584 MOZ_RELEASE_ASSERT(slots_[slot] == later.slots_[slot]);
6585 }
6586 }
6587 }
6588 }
6589
6590 // Object flags should not be lost. The exception is the Indexed flag, it
6591 // can be cleared when densifying elements, so clear that flag first.
6592 {
6593 ObjectFlags flags = objectFlags_;
6594 ObjectFlags flagsLater = later.objectFlags_;
6595 flags.clearFlag(ObjectFlag::Indexed);
6596 flagsLater.clearFlag(ObjectFlag::Indexed);
6597 MOZ_RELEASE_ASSERT((flags.toRaw() & flagsLater.toRaw()) == flags.toRaw());
6598 }
6599
6600 // If the HadGetterSetterChange flag wasn't set, all GetterSetter slots must
6601 // be unchanged.
6602 if (!later.objectFlags_.hasFlag(ObjectFlag::HadGetterSetterChange)) {
6603 for (size_t i = 0; i < slots_.length(); i++) {
6604 if (slots_[i].isPrivateGCThing() &&
6605 slots_[i].toGCThing()->is<GetterSetter>()) {
6606 MOZ_RELEASE_ASSERT(i < later.slots_.length());
6607 MOZ_RELEASE_ASSERT(later.slots_[i] == slots_[i]);
6608 }
6609 }
6610 }
6611 }
6612
6613 // static
6614 ShapeSnapshotObject* ShapeSnapshotObject::create(JSContext* cx,
6615 HandleObject obj) {
6616 Rooted<UniquePtr<ShapeSnapshot>> snapshot(cx,
6617 cx->make_unique<ShapeSnapshot>(cx));
6618 if (!snapshot || !snapshot->init(obj)) {
6619 return nullptr;
6620 }
6621
6622 auto* snapshotObj = NewObjectWithGivenProto<ShapeSnapshotObject>(cx, nullptr);
6623 if (!snapshotObj) {
6624 return nullptr;
6625 }
6626 snapshotObj->initReservedSlot(SnapshotSlot, PrivateValue(snapshot.release()));
6627 return snapshotObj;
6628 }
6629
6630 static bool CreateShapeSnapshot(JSContext* cx, unsigned argc, Value* vp) {
6631 CallArgs args = CallArgsFromVp(argc, vp);
6632
6633 if (!args.get(0).isObject()) {
6634 JS_ReportErrorASCII(cx, "createShapeSnapshot requires an object argument");
6635 return false;
6636 }
6637
6638 RootedObject obj(cx, &args[0].toObject());
6639 auto* res = ShapeSnapshotObject::create(cx, obj);
6640 if (!res) {
6641 return false;
6642 }
6643
6644 res->snapshot().check(cx, res->snapshot());
6645
6646 args.rval().setObject(*res);
6647 return true;
6648 }
6649
6650 static bool CheckShapeSnapshot(JSContext* cx, unsigned argc, Value* vp) {
6651 CallArgs args = CallArgsFromVp(argc, vp);
6652
6653 if (!args.get(0).isObject() ||
6654 !args[0].toObject().is<ShapeSnapshotObject>()) {
6655 JS_ReportErrorASCII(cx, "checkShapeSnapshot requires a snapshot argument");
6656 return false;
6657 }
6658
6659 // Get the object to use from the snapshot if the second argument is not an
6660 // object.
6661 RootedObject obj(cx);
6662 if (args.get(1).isObject()) {
6663 obj = &args[1].toObject();
6664 } else {
6665 auto& snapshot = args[0].toObject().as<ShapeSnapshotObject>().snapshot();
6666 obj = snapshot.object();
6667 }
6668
6669 RootedObject otherSnapshot(cx, ShapeSnapshotObject::create(cx, obj));
6670 if (!otherSnapshot) {
6671 return false;
6672 }
6673
6674 auto& snapshot1 = args[0].toObject().as<ShapeSnapshotObject>().snapshot();
6675 auto& snapshot2 = otherSnapshot->as<ShapeSnapshotObject>().snapshot();
6676 snapshot1.check(cx, snapshot2);
6677
6678 args.rval().setUndefined();
6679 return true;
6680 }
6681
6682 #if defined(DEBUG) || defined(JS_JITSPEW)
6683 static bool DumpObject(JSContext* cx, unsigned argc, Value* vp) {
6684 CallArgs args = CallArgsFromVp(argc, vp);
6685 RootedObject obj(cx, ToObject(cx, args.get(0)));
6686 if (!obj) {
6687 return false;
6688 }
6689
6690 DumpObject(obj);
6691
6692 args.rval().setUndefined();
6693 return true;
6694 }
6695
6696 static bool DumpValue(JSContext* cx, unsigned argc, Value* vp) {
6697 CallArgs args = CallArgsFromVp(argc, vp);
6698 args.get(0).get().dump();
6699 args.rval().setUndefined();
6700 return true;
6701 }
6702
6703 static bool DumpValueToString(JSContext* cx, unsigned argc, Value* vp) {
6704 CallArgs args = CallArgsFromVp(argc, vp);
6705
6706 JSSprinter out(cx);
6707 if (!out.init()) {
6708 return false;
6709 }
6710 args.get(0).get().dump(out);
6711
6712 JSString* rep = out.release(cx);
6713 if (!rep) {
6714 return false;
6715 }
6716
6717 args.rval().setString(rep);
6718 return true;
6719 }
6720 #endif
6721
6722 static bool SharedMemoryEnabled(JSContext* cx, unsigned argc, Value* vp) {
6723 CallArgs args = CallArgsFromVp(argc, vp);
6724 args.rval().setBoolean(
6725 cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled());
6726 return true;
6727 }
6728
6729 static bool SharedArrayRawBufferRefcount(JSContext* cx, unsigned argc,
6730 Value* vp) {
6731 CallArgs args = CallArgsFromVp(argc, vp);
6732 if (args.length() != 1 || !args[0].isObject()) {
6733 JS_ReportErrorASCII(cx, "Expected SharedArrayBuffer object");
6734 return false;
6735 }
6736 RootedObject obj(cx, &args[0].toObject());
6737 if (!obj->is<SharedArrayBufferObject>()) {
6738 JS_ReportErrorASCII(cx, "Expected SharedArrayBuffer object");
6739 return false;
6740 }
6741 args.rval().setInt32(
6742 obj->as<SharedArrayBufferObject>().rawBufferObject()->refcount());
6743 return true;
6744 }
6745
6746 #ifdef NIGHTLY_BUILD
6747 static bool ObjectAddress(JSContext* cx, unsigned argc, Value* vp) {
6748 CallArgs args = CallArgsFromVp(argc, vp);
6749
6750 if (js::SupportDifferentialTesting()) {
6751 RootedObject callee(cx, &args.callee());
6752 ReportUsageErrorASCII(cx, callee,
6753 "Function unavailable in differential testing mode.");
6754 return false;
6755 }
6756
6757 if (args.length() != 1) {
6758 RootedObject callee(cx, &args.callee());
6759 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
6760 return false;
6761 }
6762 if (!args[0].isObject()) {
6763 RootedObject callee(cx, &args.callee());
6764 ReportUsageErrorASCII(cx, callee, "Expected object");
6765 return false;
6766 }
6767
6768 void* ptr = js::UncheckedUnwrap(&args[0].toObject(), true);
6769 char buffer[64];
6770 SprintfLiteral(buffer, "%p", ptr);
6771
6772 return ReturnStringCopy(cx, args, buffer);
6773 }
6774
6775 static bool SharedAddress(JSContext* cx, unsigned argc, Value* vp) {
6776 CallArgs args = CallArgsFromVp(argc, vp);
6777
6778 if (js::SupportDifferentialTesting()) {
6779 RootedObject callee(cx, &args.callee());
6780 ReportUsageErrorASCII(cx, callee,
6781 "Function unavailable in differential testing mode.");
6782 return false;
6783 }
6784
6785 if (args.length() != 1) {
6786 RootedObject callee(cx, &args.callee());
6787 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
6788 return false;
6789 }
6790 if (!args[0].isObject()) {
6791 RootedObject callee(cx, &args.callee());
6792 ReportUsageErrorASCII(cx, callee, "Expected object");
6793 return false;
6794 }
6795
6796 RootedObject obj(cx, CheckedUnwrapStatic(&args[0].toObject()));
6797 if (!obj) {
6798 ReportAccessDenied(cx);
6799 return false;
6800 }
6801 if (!obj->is<SharedArrayBufferObject>()) {
6802 JS_ReportErrorASCII(cx, "Argument must be a SharedArrayBuffer");
6803 return false;
6804 }
6805 char buffer[64];
6806 uint32_t nchar = SprintfLiteral(
6807 buffer, "%p",
6808 obj->as<SharedArrayBufferObject>().dataPointerShared().unwrap(
6809 /*safeish*/));
6810
6811 JSString* str = JS_NewStringCopyN(cx, buffer, nchar);
6812 if (!str) {
6813 return false;
6814 }
6815
6816 args.rval().setString(str);
6817
6818 return true;
6819 }
6820 #endif
6821
6822 static bool HasInvalidatedTeleporting(JSContext* cx, unsigned argc, Value* vp) {
6823 CallArgs args = CallArgsFromVp(argc, vp);
6824
6825 if (args.length() != 1 || !args[0].isObject()) {
6826 RootedObject callee(cx, &args.callee());
6827 ReportUsageErrorASCII(cx, callee, "Expected single object argument");
6828 return false;
6829 }
6830
6831 args.rval().setBoolean(args[0].toObject().hasInvalidatedTeleporting());
6832 return true;
6833 }
6834
6835 static bool DumpBacktrace(JSContext* cx, unsigned argc, Value* vp) {
6836 CallArgs args = CallArgsFromVp(argc, vp);
6837 DumpBacktrace(cx);
6838 args.rval().setUndefined();
6839 return true;
6840 }
6841
6842 static bool GetBacktrace(JSContext* cx, unsigned argc, Value* vp) {
6843 CallArgs args = CallArgsFromVp(argc, vp);
6844
6845 bool showArgs = false;
6846 bool showLocals = false;
6847 bool showThisProps = false;
6848
6849 if (args.length() > 1) {
6850 RootedObject callee(cx, &args.callee());
6851 ReportUsageErrorASCII(cx, callee, "Too many arguments");
6852 return false;
6853 }
6854
6855 if (args.length() == 1) {
6856 RootedObject cfg(cx, ToObject(cx, args[0]));
6857 if (!cfg) {
6858 return false;
6859 }
6860 RootedValue v(cx);
6861
6862 if (!JS_GetProperty(cx, cfg, "args", &v)) {
6863 return false;
6864 }
6865 showArgs = ToBoolean(v);
6866
6867 if (!JS_GetProperty(cx, cfg, "locals", &v)) {
6868 return false;
6869 }
6870 showLocals = ToBoolean(v);
6871
6872 if (!JS_GetProperty(cx, cfg, "thisprops", &v)) {
6873 return false;
6874 }
6875 showThisProps = ToBoolean(v);
6876 }
6877
6878 JS::UniqueChars buf =
6879 JS::FormatStackDump(cx, showArgs, showLocals, showThisProps);
6880 if (!buf) {
6881 return false;
6882 }
6883
6884 size_t len;
6885 UniqueTwoByteChars ucbuf(JS::LossyUTF8CharsToNewTwoByteCharsZ(
6886 cx, JS::UTF8Chars(buf.get(), strlen(buf.get())),
6887 &len, js::MallocArena)
6888 .get());
6889 if (!ucbuf) {
6890 return false;
6891 }
6892 JSString* str = JS_NewUCStringCopyN(cx, ucbuf.get(), len);
6893 if (!str) {
6894 return false;
6895 }
6896
6897 args.rval().setString(str);
6898 return true;
6899 }
6900
6901 static bool ReportOutOfMemory(JSContext* cx, unsigned argc, Value* vp) {
6902 CallArgs args = CallArgsFromVp(argc, vp);
6903 JS_ReportOutOfMemory(cx);
6904 cx->clearPendingException();
6905 args.rval().setUndefined();
6906 return true;
6907 }
6908
6909 static bool ThrowOutOfMemory(JSContext* cx, unsigned argc, Value* vp) {
6910 JS_ReportOutOfMemory(cx);
6911 return false;
6912 }
6913
6914 static bool ReportLargeAllocationFailure(JSContext* cx, unsigned argc,
6915 Value* vp) {
6916 CallArgs args = CallArgsFromVp(argc, vp);
6917
6918 size_t bytes = JSRuntime::LARGE_ALLOCATION;
6919 if (args.length() >= 1) {
6920 if (!args[0].isInt32()) {
6921 RootedObject callee(cx, &args.callee());
6922 ReportUsageErrorASCII(cx, callee,
6923 "First argument must be an integer if specified.");
6924 return false;
6925 }
6926 bytes = args[0].toInt32();
6927 }
6928
6929 void* buf = cx->runtime()->onOutOfMemoryCanGC(AllocFunction::Malloc,
6930 js::MallocArena, bytes);
6931
6932 js_free(buf);
6933 args.rval().setUndefined();
6934 return true;
6935 }
6936
6937 namespace heaptools {
6938
6939 using EdgeName = UniqueTwoByteChars;
6940
6941 // An edge to a node from its predecessor in a path through the graph.
6942 class BackEdge {
6943 // The node from which this edge starts.
6944 JS::ubi::Node predecessor_;
6945
6946 // The name of this edge.
6947 EdgeName name_;
6948
6949 public:
6950 BackEdge() : name_(nullptr) {}
6951 // Construct an initialized back edge, taking ownership of |name|.
6952 BackEdge(JS::ubi::Node predecessor, EdgeName name)
6953 : predecessor_(predecessor), name_(std::move(name)) {}
6954 BackEdge(BackEdge&& rhs)
6955 : predecessor_(rhs.predecessor_), name_(std::move(rhs.name_)) {}
6956 BackEdge& operator=(BackEdge&& rhs) {
6957 MOZ_ASSERT(&rhs != this);
6958 this->~BackEdge();
6959 new (this) BackEdge(std::move(rhs));
6960 return *this;
6961 }
6962
6963 EdgeName forgetName() { return std::move(name_); }
6964 JS::ubi::Node predecessor() const { return predecessor_; }
6965
6966 private:
6967 // No copy constructor or copying assignment.
6968 BackEdge(const BackEdge&) = delete;
6969 BackEdge& operator=(const BackEdge&) = delete;
6970 };
6971
6972 // A path-finding handler class for use with JS::ubi::BreadthFirst.
6973 struct FindPathHandler {
6974 using NodeData = BackEdge;
6975 using Traversal = JS::ubi::BreadthFirst<FindPathHandler>;
6976
6977 FindPathHandler(JSContext* cx, JS::ubi::Node start, JS::ubi::Node target,
6978 MutableHandle<GCVector<Value>> nodes, Vector<EdgeName>& edges)
6979 : cx(cx),
6980 start(start),
6981 target(target),
6982 foundPath(false),
6983 nodes(nodes),
6984 edges(edges) {}
6985
6986 bool operator()(Traversal& traversal, JS::ubi::Node origin,
6987 const JS::ubi::Edge& edge, BackEdge* backEdge, bool first) {
6988 // We take care of each node the first time we visit it, so there's
6989 // nothing to be done on subsequent visits.
6990 if (!first) {
6991 return true;
6992 }
6993
6994 // Record how we reached this node. This is the last edge on a
6995 // shortest path to this node.
6996 EdgeName edgeName =
6997 DuplicateStringToArena(js::StringBufferArena, cx, edge.name.get());
6998 if (!edgeName) {
6999 return false;
7000 }
7001 *backEdge = BackEdge(origin, std::move(edgeName));
7002
7003 // Have we reached our final target node?
7004 if (edge.referent == target) {
7005 // Record the path that got us here, which must be a shortest path.
7006 if (!recordPath(traversal, backEdge)) {
7007 return false;
7008 }
7009 foundPath = true;
7010 traversal.stop();
7011 }
7012
7013 return true;
7014 }
7015
7016 // We've found a path to our target. Walk the backlinks to produce the
7017 // (reversed) path, saving the path in |nodes| and |edges|. |nodes| is
7018 // rooted, so it can hold the path's nodes as we leave the scope of
7019 // the AutoCheckCannotGC. Note that nodes are added to |visited| after we
7020 // return from operator() so we have to pass the target BackEdge* to this
7021 // function.
7022 bool recordPath(Traversal& traversal, BackEdge* targetBackEdge) {
7023 JS::ubi::Node here = target;
7024
7025 do {
7026 BackEdge* backEdge = targetBackEdge;
7027 if (here != target) {
7028 Traversal::NodeMap::Ptr p = traversal.visited.lookup(here);
7029 MOZ_ASSERT(p);
7030 backEdge = &p->value();
7031 }
7032 JS::ubi::Node predecessor = backEdge->predecessor();
7033 if (!nodes.append(predecessor.exposeToJS()) ||
7034 !edges.append(backEdge->forgetName())) {
7035 return false;
7036 }
7037 here = predecessor;
7038 } while (here != start);
7039
7040 return true;
7041 }
7042
7043 JSContext* cx;
7044
7045 // The node we're starting from.
7046 JS::ubi::Node start;
7047
7048 // The node we're looking for.
7049 JS::ubi::Node target;
7050
7051 // True if we found a path to target, false if we didn't.
7052 bool foundPath;
7053
7054 // The nodes and edges of the path --- should we find one. The path is
7055 // stored in reverse order, because that's how it's easiest for us to
7056 // construct it:
7057 // - edges[i] is the name of the edge from nodes[i] to nodes[i-1].
7058 // - edges[0] is the name of the edge from nodes[0] to the target.
7059 // - The last node, nodes[n-1], is the start node.
7060 MutableHandle<GCVector<Value>> nodes;
7061 Vector<EdgeName>& edges;
7062 };
7063
7064 } // namespace heaptools
7065
7066 static bool FindPath(JSContext* cx, unsigned argc, Value* vp) {
7067 CallArgs args = CallArgsFromVp(argc, vp);
7068 if (!args.requireAtLeast(cx, "findPath", 2)) {
7069 return false;
7070 }
7071
7072 // We don't ToString non-objects given as 'start' or 'target', because this
7073 // test is all about object identity, and ToString doesn't preserve that.
7074 // Non-GCThing endpoints don't make much sense.
7075 if (!args[0].isObject() && !args[0].isString() && !args[0].isSymbol()) {
7076 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[0],
7077 nullptr, "not an object, string, or symbol");
7078 return false;
7079 }
7080
7081 if (!args[1].isObject() && !args[1].isString() && !args[1].isSymbol()) {
7082 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[0],
7083 nullptr, "not an object, string, or symbol");
7084 return false;
7085 }
7086
7087 Rooted<GCVector<Value>> nodes(cx, GCVector<Value>(cx));
7088 Vector<heaptools::EdgeName> edges(cx);
7089
7090 {
7091 // We can't tolerate the GC moving things around while we're searching
7092 // the heap. Check that nothing we do causes a GC.
7093 JS::AutoCheckCannotGC autoCannotGC;
7094
7095 JS::ubi::Node start(args[0]), target(args[1]);
7096
7097 heaptools::FindPathHandler handler(cx, start, target, &nodes, edges);
7098 heaptools::FindPathHandler::Traversal traversal(cx, handler, autoCannotGC);
7099 if (!traversal.addStart(start)) {
7100 ReportOutOfMemory(cx);
7101 return false;
7102 }
7103
7104 if (!traversal.traverse()) {
7105 if (!cx->isExceptionPending()) {
7106 ReportOutOfMemory(cx);
7107 }
7108 return false;
7109 }
7110
7111 if (!handler.foundPath) {
7112 // We didn't find any paths from the start to the target.
7113 args.rval().setUndefined();
7114 return true;
7115 }
7116 }
7117
7118 // |nodes| and |edges| contain the path from |start| to |target|, reversed.
7119 // Construct a JavaScript array describing the path from the start to the
7120 // target. Each element has the form:
7121 //
7122 // {
7123 // node: <object or string or symbol>,
7124 // edge: <string describing outgoing edge from node>
7125 // }
7126 //
7127 // or, if the node is some internal thing that isn't a proper JavaScript
7128 // value:
7129 //
7130 // { node: undefined, edge: <string> }
7131 size_t length = nodes.length();
7132 Rooted<ArrayObject*> result(cx, NewDenseFullyAllocatedArray(cx, length));
7133 if (!result) {
7134 return false;
7135 }
7136 result->ensureDenseInitializedLength(0, length);
7137
7138 // Walk |nodes| and |edges| in the stored order, and construct the result
7139 // array in start-to-target order.
7140 for (size_t i = 0; i < length; i++) {
7141 // Build an object describing the node and edge.
7142 RootedObject obj(cx, NewPlainObject(cx));
7143 if (!obj) {
7144 return false;
7145 }
7146
7147 // Only define the "node" property if we're not fuzzing, to prevent the
7148 // fuzzers from messing with internal objects that we don't want to expose
7149 // to arbitrary JS.
7150 if (!fuzzingSafe) {
7151 RootedValue wrapped(cx, nodes[i]);
7152 if (!cx->compartment()->wrap(cx, &wrapped)) {
7153 return false;
7154 }
7155
7156 if (!JS_DefineProperty(cx, obj, "node", wrapped, JSPROP_ENUMERATE)) {
7157 return false;
7158 }
7159 }
7160
7161 heaptools::EdgeName edgeName = std::move(edges[i]);
7162
7163 size_t edgeNameLength = js_strlen(edgeName.get());
7164 RootedString edgeStr(
7165 cx, NewString<CanGC>(cx, std::move(edgeName), edgeNameLength));
7166 if (!edgeStr) {
7167 return false;
7168 }
7169
7170 if (!JS_DefineProperty(cx, obj, "edge", edgeStr, JSPROP_ENUMERATE)) {
7171 return false;
7172 }
7173
7174 result->setDenseElement(length - i - 1, ObjectValue(*obj));
7175 }
7176
7177 args.rval().setObject(*result);
7178 return true;
7179 }
7180
7181 static bool ShortestPaths(JSContext* cx, unsigned argc, Value* vp) {
7182 CallArgs args = CallArgsFromVp(argc, vp);
7183 if (!args.requireAtLeast(cx, "shortestPaths", 1)) {
7184 return false;
7185 }
7186
7187 if (!args[0].isObject() || !args[0].toObject().is<ArrayObject>()) {
7188 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[0],
7189 nullptr, "not an array object");
7190 return false;
7191 }
7192
7193 Rooted<ArrayObject*> objs(cx, &args[0].toObject().as<ArrayObject>());
7194
7195 RootedValue start(cx, NullValue());
7196 int32_t maxNumPaths = 3;
7197
7198 if (!args.get(1).isUndefined()) {
7199 if (!args[1].isObject()) {
7200 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[1],
7201 nullptr, "not an options object");
7202 return false;
7203 }
7204
7205 RootedObject options(cx, &args[1].toObject());
7206 bool exists;
7207 if (!JS_HasProperty(cx, options, "start", &exists)) {
7208 return false;
7209 }
7210 if (exists) {
7211 if (!JS_GetProperty(cx, options, "start", &start)) {
7212 return false;
7213 }
7214
7215 // Non-GCThing endpoints don't make much sense.
7216 if (!start.isGCThing()) {
7217 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, start,
7218 nullptr, "not a GC thing");
7219 return false;
7220 }
7221 }
7222
7223 RootedValue v(cx, Int32Value(maxNumPaths));
7224 if (!JS_HasProperty(cx, options, "maxNumPaths", &exists)) {
7225 return false;
7226 }
7227 if (exists) {
7228 if (!JS_GetProperty(cx, options, "maxNumPaths", &v)) {
7229 return false;
7230 }
7231 if (!JS::ToInt32(cx, v, &maxNumPaths)) {
7232 return false;
7233 }
7234 }
7235 if (maxNumPaths <= 0) {
7236 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, v,
7237 nullptr, "not greater than 0");
7238 return false;
7239 }
7240 }
7241
7242 // Ensure we have at least one target.
7243 size_t length = objs->getDenseInitializedLength();
7244 if (length == 0) {
7245 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, args[0],
7246 nullptr,
7247 "not a dense array object with one or more elements");
7248 return false;
7249 }
7250
7251 for (size_t i = 0; i < length; i++) {
7252 RootedValue el(cx, objs->getDenseElement(i));
7253 if (!el.isGCThing()) {
7254 JS_ReportErrorASCII(cx, "Each target must be a GC thing");
7255 return false;
7256 }
7257 }
7258
7259 // We accumulate the results into a GC-stable form, due to the fact that the
7260 // JS::ubi::ShortestPaths lifetime (when operating on the live heap graph)
7261 // is bounded within an AutoCheckCannotGC.
7262 Rooted<GCVector<GCVector<GCVector<Value>>>> values(
7263 cx, GCVector<GCVector<GCVector<Value>>>(cx));
7264 Vector<Vector<Vector<JS::ubi::EdgeName>>> names(cx);
7265
7266 {
7267 JS::ubi::Node root;
7268
7269 JS::ubi::RootList rootList(cx, true);
7270 if (start.isNull()) {
7271 auto [ok, nogc] = rootList.init();
7272 (void)nogc; // Old compilers get anxious about nogc being unused.
7273 if (!ok) {
7274 ReportOutOfMemory(cx);
7275 return false;
7276 }
7277 root = JS::ubi::Node(&rootList);
7278 } else {
7279 root = JS::ubi::Node(start);
7280 }
7281 JS::AutoCheckCannotGC noGC(cx);
7282
7283 JS::ubi::NodeSet targets;
7284
7285 for (size_t i = 0; i < length; i++) {
7286 RootedValue val(cx, objs->getDenseElement(i));
7287 JS::ubi::Node node(val);
7288 if (!targets.put(node)) {
7289 ReportOutOfMemory(cx);
7290 return false;
7291 }
7292 }
7293
7294 auto maybeShortestPaths = JS::ubi::ShortestPaths::Create(
7295 cx, noGC, maxNumPaths, root, std::move(targets));
7296 if (maybeShortestPaths.isNothing()) {
7297 ReportOutOfMemory(cx);
7298 return false;
7299 }
7300 auto& shortestPaths = *maybeShortestPaths;
7301
7302 for (size_t i = 0; i < length; i++) {
7303 if (!values.append(GCVector<GCVector<Value>>(cx)) ||
7304 !names.append(Vector<Vector<JS::ubi::EdgeName>>(cx))) {
7305 return false;
7306 }
7307
7308 RootedValue val(cx, objs->getDenseElement(i));
7309 JS::ubi::Node target(val);
7310
7311 bool ok = shortestPaths.forEachPath(target, [&](JS::ubi::Path& path) {
7312 Rooted<GCVector<Value>> pathVals(cx, GCVector<Value>(cx));
7313 Vector<JS::ubi::EdgeName> pathNames(cx);
7314
7315 for (auto& part : path) {
7316 if (!pathVals.append(part->predecessor().exposeToJS()) ||
7317 !pathNames.append(std::move(part->name()))) {
7318 return false;
7319 }
7320 }
7321
7322 return values.back().append(std::move(pathVals.get())) &&
7323 names.back().append(std::move(pathNames));
7324 });
7325
7326 if (!ok) {
7327 return false;
7328 }
7329 }
7330 }
7331
7332 MOZ_ASSERT(values.length() == names.length());
7333 MOZ_ASSERT(values.length() == length);
7334
7335 Rooted<ArrayObject*> results(cx, NewDenseFullyAllocatedArray(cx, length));
7336 if (!results) {
7337 return false;
7338 }
7339 results->ensureDenseInitializedLength(0, length);
7340
7341 for (size_t i = 0; i < length; i++) {
7342 size_t numPaths = values[i].length();
7343 MOZ_ASSERT(names[i].length() == numPaths);
7344
7345 Rooted<ArrayObject*> pathsArray(cx,
7346 NewDenseFullyAllocatedArray(cx, numPaths));
7347 if (!pathsArray) {
7348 return false;
7349 }
7350 pathsArray->ensureDenseInitializedLength(0, numPaths);
7351
7352 for (size_t j = 0; j < numPaths; j++) {
7353 size_t pathLength = values[i][j].length();
7354 MOZ_ASSERT(names[i][j].length() == pathLength);
7355
7356 Rooted<ArrayObject*> path(cx,
7357 NewDenseFullyAllocatedArray(cx, pathLength));
7358 if (!path) {
7359 return false;
7360 }
7361 path->ensureDenseInitializedLength(0, pathLength);
7362
7363 for (size_t k = 0; k < pathLength; k++) {
7364 Rooted<PlainObject*> part(cx, NewPlainObject(cx));
7365 if (!part) {
7366 return false;
7367 }
7368
7369 RootedValue predecessor(cx, values[i][j][k]);
7370 if (!cx->compartment()->wrap(cx, &predecessor) ||
7371 !JS_DefineProperty(cx, part, "predecessor", predecessor,
7372 JSPROP_ENUMERATE)) {
7373 return false;
7374 }
7375
7376 if (names[i][j][k]) {
7377 RootedString edge(cx,
7378 NewStringCopyZ<CanGC>(cx, names[i][j][k].get()));
7379 if (!edge ||
7380 !JS_DefineProperty(cx, part, "edge", edge, JSPROP_ENUMERATE)) {
7381 return false;
7382 }
7383 }
7384
7385 path->setDenseElement(k, ObjectValue(*part));
7386 }
7387
7388 pathsArray->setDenseElement(j, ObjectValue(*path));
7389 }
7390
7391 results->setDenseElement(i, ObjectValue(*pathsArray));
7392 }
7393
7394 args.rval().setObject(*results);
7395 return true;
7396 }
7397
7398 static bool EvalReturningScope(JSContext* cx, unsigned argc, Value* vp) {
7399 CallArgs args = CallArgsFromVp(argc, vp);
7400 if (!args.requireAtLeast(cx, "evalReturningScope", 1)) {
7401 return false;
7402 }
7403
7404 RootedString str(cx, ToString(cx, args[0]));
7405 if (!str) {
7406 return false;
7407 }
7408
7409 JS::AutoFilename filename;
7410 uint32_t lineno;
7411
7412 JS::DescribeScriptedCaller(&filename, cx, &lineno);
7413
7414 // CompileOption should be created in the target global's realm.
7415 RootedObject global(cx);
7416 Maybe<JS::CompileOptions> maybeOptions;
7417 if (args.hasDefined(1)) {
7418 global = ToObject(cx, args[1]);
7419 if (!global) {
7420 return false;
7421 }
7422
7423 global = CheckedUnwrapDynamic(global, cx, /* stopAtWindowProxy = */ false);
7424 if (!global) {
7425 JS_ReportErrorASCII(cx, "Permission denied to access global");
7426 return false;
7427 }
7428 if (!global->is<GlobalObject>()) {
7429 JS_ReportErrorASCII(cx, "Argument must be a global object");
7430 return false;
7431 }
7432
7433 JSAutoRealm ar(cx, global);
7434 maybeOptions.emplace(cx);
7435 } else {
7436 global = JS::CurrentGlobalOrNull(cx);
7437 maybeOptions.emplace(cx);
7438 }
7439
7440 CompileOptions& options = maybeOptions.ref();
7441 options.setFileAndLine(filename.get(), lineno);
7442 options.setNoScriptRval(true);
7443 options.setNonSyntacticScope(true);
7444
7445 AutoStableStringChars linearChars(cx);
7446 if (!linearChars.initTwoByte(cx, str)) {
7447 return false;
7448 }
7449 JS::SourceText<char16_t> srcBuf;
7450 if (!srcBuf.initMaybeBorrowed(cx, linearChars)) {
7451 return false;
7452 }
7453
7454 RootedObject varObj(cx);
7455
7456 {
7457 // ExecuteInFrameScriptEnvironment requires the script be in the same
7458 // realm as the global. The script compilation should be done after
7459 // switching globals.
7460 AutoRealm ar(cx, global);
7461
7462 RootedScript script(cx, JS::Compile(cx, options, srcBuf));
7463 if (!script) {
7464 return false;
7465 }
7466
7467 JS::RootedObject obj(cx, JS_NewPlainObject(cx));
7468 if (!obj) {
7469 return false;
7470 }
7471
7472 RootedObject lexicalScope(cx);
7473 if (!js::ExecuteInFrameScriptEnvironment(cx, obj, script, &lexicalScope)) {
7474 return false;
7475 }
7476
7477 varObj = lexicalScope->enclosingEnvironment()->enclosingEnvironment();
7478 MOZ_ASSERT(varObj->is<NonSyntacticVariablesObject>());
7479 }
7480
7481 RootedValue varObjVal(cx, ObjectValue(*varObj));
7482 if (!cx->compartment()->wrap(cx, &varObjVal)) {
7483 return false;
7484 }
7485
7486 args.rval().set(varObjVal);
7487 return true;
7488 }
7489
7490 static bool ByteSize(JSContext* cx, unsigned argc, Value* vp) {
7491 CallArgs args = CallArgsFromVp(argc, vp);
7492 mozilla::MallocSizeOf mallocSizeOf = cx->runtime()->debuggerMallocSizeOf;
7493
7494 {
7495 // We can't tolerate the GC moving things around while we're using a
7496 // ubi::Node. Check that nothing we do causes a GC.
7497 JS::AutoCheckCannotGC autoCannotGC;
7498
7499 JS::ubi::Node node = args.get(0);
7500 if (node) {
7501 args.rval().setNumber(uint32_t(node.size(mallocSizeOf)));
7502 } else {
7503 args.rval().setUndefined();
7504 }
7505 }
7506 return true;
7507 }
7508
7509 static bool ByteSizeOfScript(JSContext* cx, unsigned argc, Value* vp) {
7510 CallArgs args = CallArgsFromVp(argc, vp);
7511 if (!args.requireAtLeast(cx, "byteSizeOfScript", 1)) {
7512 return false;
7513 }
7514 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
7515 JS_ReportErrorASCII(cx, "Argument must be a Function object");
7516 return false;
7517 }
7518
7519 RootedFunction fun(cx, &args[0].toObject().as<JSFunction>());
7520 if (fun->isNativeFun()) {
7521 JS_ReportErrorASCII(cx, "Argument must be a scripted function");
7522 return false;
7523 }
7524
7525 RootedScript script(cx, JSFunction::getOrCreateScript(cx, fun));
7526 if (!script) {
7527 return false;
7528 }
7529
7530 mozilla::MallocSizeOf mallocSizeOf = cx->runtime()->debuggerMallocSizeOf;
7531
7532 {
7533 // We can't tolerate the GC moving things around while we're using a
7534 // ubi::Node. Check that nothing we do causes a GC.
7535 JS::AutoCheckCannotGC autoCannotGC;
7536
7537 JS::ubi::Node node = script;
7538 if (node) {
7539 args.rval().setNumber(uint32_t(node.size(mallocSizeOf)));
7540 } else {
7541 args.rval().setUndefined();
7542 }
7543 }
7544 return true;
7545 }
7546
7547 static bool SetImmutablePrototype(JSContext* cx, unsigned argc, Value* vp) {
7548 CallArgs args = CallArgsFromVp(argc, vp);
7549 if (!args.get(0).isObject()) {
7550 JS_ReportErrorASCII(cx, "setImmutablePrototype: object expected");
7551 return false;
7552 }
7553
7554 RootedObject obj(cx, &args[0].toObject());
7555
7556 bool succeeded;
7557 if (!js::SetImmutablePrototype(cx, obj, &succeeded)) {
7558 return false;
7559 }
7560
7561 args.rval().setBoolean(succeeded);
7562 return true;
7563 }
7564
7565 #if defined(DEBUG) || defined(JS_JITSPEW)
7566 static bool DumpStringRepresentation(JSContext* cx, unsigned argc, Value* vp) {
7567 CallArgs args = CallArgsFromVp(argc, vp);
7568
7569 RootedString str(cx, ToString(cx, args.get(0)));
7570 if (!str) {
7571 return false;
7572 }
7573
7574 Fprinter out(stderr);
7575 str->dumpRepresentation(out);
7576
7577 args.rval().setUndefined();
7578 return true;
7579 }
7580
7581 static bool GetStringRepresentation(JSContext* cx, unsigned argc, Value* vp) {
7582 CallArgs args = CallArgsFromVp(argc, vp);
7583
7584 RootedString str(cx, ToString(cx, args.get(0)));
7585 if (!str) {
7586 return false;
7587 }
7588
7589 JSSprinter out(cx);
7590 if (!out.init()) {
7591 return false;
7592 }
7593 str->dumpRepresentation(out);
7594
7595 JSString* rep = out.release(cx);
7596 if (!rep) {
7597 return false;
7598 }
7599
7600 args.rval().setString(rep);
7601 return true;
7602 }
7603 #endif
7604
7605 static bool ParseCompileOptionsForModule(JSContext* cx,
7606 JS::CompileOptions& options,
7607 JS::Handle<JSObject*> opts,
7608 bool& isModule) {
7609 JS::Rooted<JS::Value> v(cx);
7610
7611 if (!JS_GetProperty(cx, opts, "module", &v)) {
7612 return false;
7613 }
7614 if (!v.isUndefined() && JS::ToBoolean(v)) {
7615 options.setModule();
7616 isModule = true;
7617
7618 if (!ValidateModuleCompileOptions(cx, options)) {
7619 return false;
7620 }
7621 } else {
7622 isModule = false;
7623 }
7624
7625 return true;
7626 }
7627
7628 static bool ParseCompileOptionsForInstantiate(JSContext* cx,
7629 JS::CompileOptions& options,
7630 JS::Handle<JSObject*> opts,
7631 bool& prepareForInstantiate) {
7632 JS::Rooted<JS::Value> v(cx);
7633
7634 if (!JS_GetProperty(cx, opts, "prepareForInstantiate", &v)) {
7635 return false;
7636 }
7637 if (!v.isUndefined()) {
7638 prepareForInstantiate = JS::ToBoolean(v);
7639 } else {
7640 prepareForInstantiate = false;
7641 }
7642
7643 return true;
7644 }
7645
7646 static bool CompileToStencil(JSContext* cx, uint32_t argc, Value* vp) {
7647 CallArgs args = CallArgsFromVp(argc, vp);
7648
7649 if (!args.requireAtLeast(cx, "compileToStencil", 1)) {
7650 return false;
7651 }
7652 if (!args[0].isString()) {
7653 const char* typeName = InformalValueTypeName(args[0]);
7654 JS_ReportErrorASCII(cx, "expected string to parse, got %s", typeName);
7655 return false;
7656 }
7657
7658 RootedString src(cx, ToString<CanGC>(cx, args[0]));
7659 if (!src) {
7660 return false;
7661 }
7662
7663 /* Linearize the string to obtain a char16_t* range. */
7664 AutoStableStringChars linearChars(cx);
7665 if (!linearChars.initTwoByte(cx, src)) {
7666 return false;
7667 }
7668 JS::SourceText<char16_t> srcBuf;
7669 if (!srcBuf.initMaybeBorrowed(cx, linearChars)) {
7670 return false;
7671 }
7672
7673 CompileOptions options(cx);
7674 options.setFile("<compileToStencil>");
7675
7676 RootedString displayURL(cx);
7677 RootedString sourceMapURL(cx);
7678 UniqueChars fileNameBytes;
7679 bool isModule = false;
7680 bool prepareForInstantiate = false;
7681 if (args.length() == 2) {
7682 if (!args[1].isObject()) {
7683 JS_ReportErrorASCII(
7684 cx, "compileToStencil: The 2nd argument must be an object");
7685 return false;
7686 }
7687
7688 RootedObject opts(cx, &args[1].toObject());
7689
7690 if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) {
7691 return false;
7692 }
7693 if (!ParseCompileOptionsForModule(cx, options, opts, isModule)) {
7694 return false;
7695 }
7696 if (!ParseCompileOptionsForInstantiate(cx, options, opts,
7697 prepareForInstantiate)) {
7698 return false;
7699 }
7700 if (!js::ParseSourceOptions(cx, opts, &displayURL, &sourceMapURL)) {
7701 return false;
7702 }
7703 }
7704
7705 RefPtr<JS::Stencil> stencil;
7706 if (isModule) {
7707 stencil = JS::CompileModuleScriptToStencil(cx, options, srcBuf);
7708 } else {
7709 stencil = JS::CompileGlobalScriptToStencil(cx, options, srcBuf);
7710 }
7711 if (!stencil) {
7712 return false;
7713 }
7714
7715 JS::InstantiationStorage storage;
7716 {
7717 AutoReportFrontendContext fc(cx);
7718 if (!SetSourceOptions(cx, &fc, stencil->getInitial()->source, displayURL,
7719 sourceMapURL)) {
7720 return false;
7721 }
7722
7723 if (prepareForInstantiate) {
7724 if (!JS::PrepareForInstantiate(&fc, *stencil, storage)) {
7725 return false;
7726 }
7727 }
7728 }
7729
7730 Rooted<js::StencilObject*> stencilObj(
7731 cx, js::StencilObject::create(cx, std::move(stencil)));
7732 if (!stencilObj) {
7733 return false;
7734 }
7735
7736 args.rval().setObject(*stencilObj);
7737 return true;
7738 }
7739
7740 static bool EvalStencil(JSContext* cx, uint32_t argc, Value* vp) {
7741 CallArgs args = CallArgsFromVp(argc, vp);
7742
7743 if (!args.requireAtLeast(cx, "evalStencil", 1)) {
7744 return false;
7745 }
7746
7747 /* Prepare the input byte array. */
7748 if (!args[0].isObject()) {
7749 JS_ReportErrorASCII(cx, "evalStencil: Stencil object expected");
7750 return false;
7751 }
7752 Rooted<js::StencilObject*> stencilObj(
7753 cx, args[0].toObject().maybeUnwrapIf<js::StencilObject>());
7754 if (!stencilObj) {
7755 JS_ReportErrorASCII(cx, "evalStencil: Stencil object expected");
7756 return false;
7757 }
7758
7759 if (stencilObj->stencil()->getInitial()->isModule()) {
7760 JS_ReportErrorASCII(cx,
7761 "evalStencil: Module stencil cannot be evaluated. Use "
7762 "instantiateModuleStencil instead");
7763 return false;
7764 }
7765
7766 CompileOptions options(cx);
7767 UniqueChars fileNameBytes;
7768 Rooted<JS::Value> privateValue(cx);
7769 Rooted<JSString*> elementAttributeName(cx);
7770 if (args.length() == 2) {
7771 if (!args[1].isObject()) {
7772 JS_ReportErrorASCII(cx,
7773 "evalStencil: The 2nd argument must be an object");
7774 return false;
7775 }
7776
7777 RootedObject opts(cx, &args[1].toObject());
7778
7779 if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) {
7780 return false;
7781 }
7782 if (!js::ParseDebugMetadata(cx, opts, &privateValue,
7783 &elementAttributeName)) {
7784 return false;
7785 }
7786 }
7787
7788 bool useDebugMetadata = !privateValue.isUndefined() || elementAttributeName;
7789
7790 JS::InstantiateOptions instantiateOptions(options);
7791 if (useDebugMetadata) {
7792 instantiateOptions.hideScriptFromDebugger = true;
7793 }
7794
7795 if (!js::ValidateLazinessOfStencilAndGlobal(cx, stencilObj->stencil())) {
7796 return false;
7797 }
7798
7799 RootedScript script(cx, JS::InstantiateGlobalStencil(cx, instantiateOptions,
7800 stencilObj->stencil()));
7801 if (!script) {
7802 return false;
7803 }
7804
7805 if (useDebugMetadata) {
7806 instantiateOptions.hideScriptFromDebugger = false;
7807 if (!JS::UpdateDebugMetadata(cx, script, instantiateOptions, privateValue,
7808 elementAttributeName, nullptr, nullptr)) {
7809 return false;
7810 }
7811 }
7812
7813 RootedValue retVal(cx);
7814 if (!JS_ExecuteScript(cx, script, &retVal)) {
7815 return false;
7816 }
7817
7818 args.rval().set(retVal);
7819 return true;
7820 }
7821
7822 static bool CompileToStencilXDR(JSContext* cx, uint32_t argc, Value* vp) {
7823 CallArgs args = CallArgsFromVp(argc, vp);
7824
7825 if (!args.requireAtLeast(cx, "compileToStencilXDR", 1)) {
7826 return false;
7827 }
7828
7829 RootedString src(cx, ToString<CanGC>(cx, args[0]));
7830 if (!src) {
7831 return false;
7832 }
7833
7834 /* Linearize the string to obtain a char16_t* range. */
7835 AutoStableStringChars linearChars(cx);
7836 if (!linearChars.initTwoByte(cx, src)) {
7837 return false;
7838 }
7839 JS::SourceText<char16_t> srcBuf;
7840 if (!srcBuf.initMaybeBorrowed(cx, linearChars)) {
7841 return false;
7842 }
7843
7844 CompileOptions options(cx);
7845 options.setFile("<compileToStencilXDR>");
7846
7847 RootedString displayURL(cx);
7848 RootedString sourceMapURL(cx);
7849 UniqueChars fileNameBytes;
7850 bool isModule = false;
7851 if (args.length() == 2) {
7852 if (!args[1].isObject()) {
7853 JS_ReportErrorASCII(
7854 cx, "compileToStencilXDR: The 2nd argument must be an object");
7855 return false;
7856 }
7857
7858 RootedObject opts(cx, &args[1].toObject());
7859
7860 if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) {
7861 return false;
7862 }
7863 if (!ParseCompileOptionsForModule(cx, options, opts, isModule)) {
7864 return false;
7865 }
7866 if (!js::ParseSourceOptions(cx, opts, &displayURL, &sourceMapURL)) {
7867 return false;
7868 }
7869 }
7870
7871 RefPtr<JS::Stencil> stencil;
7872 if (isModule) {
7873 stencil = JS::CompileModuleScriptToStencil(cx, options, srcBuf);
7874 } else {
7875 stencil = JS::CompileGlobalScriptToStencil(cx, options, srcBuf);
7876 }
7877 if (!stencil) {
7878 return false;
7879 }
7880
7881 {
7882 AutoReportFrontendContext fc(cx);
7883 if (!SetSourceOptions(cx, &fc, stencil->getInitial()->source, displayURL,
7884 sourceMapURL)) {
7885 return false;
7886 }
7887 }
7888
7889 /* Serialize the stencil to XDR. */
7890 JS::TranscodeBuffer xdrBytes;
7891 auto result = JS::EncodeStencil(cx, stencil, xdrBytes);
7892 if (result == JS::TranscodeResult::Throw) {
7893 return false;
7894 }
7895 if (JS::IsTranscodeFailureResult(result)) {
7896 JS_ReportErrorASCII(cx, "Encoding failure");
7897 return false;
7898 }
7899
7900 Rooted<StencilXDRBufferObject*> xdrObj(
7901 cx,
7902 StencilXDRBufferObject::create(cx, xdrBytes.begin(), xdrBytes.length()));
7903 if (!xdrObj) {
7904 return false;
7905 }
7906
7907 args.rval().setObject(*xdrObj);
7908 return true;
7909 }
7910
7911 static bool EvalStencilXDR(JSContext* cx, uint32_t argc, Value* vp) {
7912 CallArgs args = CallArgsFromVp(argc, vp);
7913
7914 if (!args.requireAtLeast(cx, "evalStencilXDR", 1)) {
7915 return false;
7916 }
7917
7918 /* Prepare the input byte array. */
7919 if (!args[0].isObject()) {
7920 JS_ReportErrorASCII(cx, "evalStencilXDR: Stencil XDR object expected");
7921 return false;
7922 }
7923 Rooted<StencilXDRBufferObject*> xdrObj(
7924 cx, args[0].toObject().maybeUnwrapIf<StencilXDRBufferObject>());
7925 if (!xdrObj) {
7926 JS_ReportErrorASCII(cx, "evalStencilXDR: Stencil XDR object expected");
7927 return false;
7928 }
7929 MOZ_ASSERT(xdrObj->hasBuffer());
7930
7931 CompileOptions options(cx);
7932 UniqueChars fileNameBytes;
7933 Rooted<JS::Value> privateValue(cx);
7934 Rooted<JSString*> elementAttributeName(cx);
7935 if (args.length() == 2) {
7936 if (!args[1].isObject()) {
7937 JS_ReportErrorASCII(cx,
7938 "evalStencilXDR: The 2nd argument must be an object");
7939 return false;
7940 }
7941
7942 RootedObject opts(cx, &args[1].toObject());
7943
7944 if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) {
7945 return false;
7946 }
7947 if (!js::ParseDebugMetadata(cx, opts, &privateValue,
7948 &elementAttributeName)) {
7949 return false;
7950 }
7951 }
7952
7953 JS::TranscodeRange xdrRange(xdrObj->buffer(), xdrObj->bufferLength());
7954 JS::DecodeOptions decodeOptions(options);
7955 RefPtr<JS::Stencil> stencil;
7956 auto result =
7957 JS::DecodeStencil(cx, decodeOptions, xdrRange, getter_AddRefs(stencil));
7958 if (result == JS::TranscodeResult::Throw) {
7959 return false;
7960 }
7961 if (JS::IsTranscodeFailureResult(result)) {
7962 JS_ReportErrorASCII(cx, "Decoding failure");
7963 return false;
7964 }
7965
7966 if (stencil->getInitial()->isModule()) {
7967 JS_ReportErrorASCII(cx,
7968 "evalStencilXDR: Module stencil cannot be evaluated. "
7969 "Use instantiateModuleStencilXDR instead");
7970 return false;
7971 }
7972
7973 if (!js::ValidateLazinessOfStencilAndGlobal(cx, stencil.get())) {
7974 return false;
7975 }
7976
7977 bool useDebugMetadata = !privateValue.isUndefined() || elementAttributeName;
7978
7979 JS::InstantiateOptions instantiateOptions(options);
7980 if (useDebugMetadata) {
7981 instantiateOptions.hideScriptFromDebugger = true;
7982 }
7983 RootedScript script(
7984 cx, JS::InstantiateGlobalStencil(cx, instantiateOptions, stencil.get()));
7985 if (!script) {
7986 return false;
7987 }
7988
7989 if (useDebugMetadata) {
7990 instantiateOptions.hideScriptFromDebugger = false;
7991 if (!JS::UpdateDebugMetadata(cx, script, instantiateOptions, privateValue,
7992 elementAttributeName, nullptr, nullptr)) {
7993 return false;
7994 }
7995 }
7996
7997 RootedValue retVal(cx);
7998 if (!JS_ExecuteScript(cx, script, &retVal)) {
7999 return false;
8000 }
8001
8002 args.rval().set(retVal);
8003 return true;
8004 }
8005
8006 static bool GetExceptionInfo(JSContext* cx, uint32_t argc, Value* vp) {
8007 CallArgs args = CallArgsFromVp(argc, vp);
8008
8009 if (!args.requireAtLeast(cx, "getExceptionInfo", 1)) {
8010 return false;
8011 }
8012
8013 if (!args[0].isObject() || !args[0].toObject().is<JSFunction>()) {
8014 JS_ReportErrorASCII(cx, "getExceptionInfo: expected function argument");
8015 return false;
8016 }
8017
8018 RootedValue rval(cx);
8019 if (JS_CallFunctionValue(cx, nullptr, args[0], JS::HandleValueArray::empty(),
8020 &rval)) {
8021 // Function didn't throw.
8022 args.rval().setNull();
8023 return true;
8024 }
8025
8026 // We currently don't support interrupts or forced returns.
8027 if (!cx->isExceptionPending()) {
8028 JS_ReportErrorASCII(cx, "getExceptionInfo: unsupported exception status");
8029 return false;
8030 }
8031
8032 RootedValue excVal(cx);
8033 Rooted<SavedFrame*> stack(cx);
8034 if (!GetAndClearExceptionAndStack(cx, &excVal, &stack)) {
8035 return false;
8036 }
8037
8038 RootedValue stackVal(cx);
8039 if (stack) {
8040 RootedString stackString(cx);
8041 if (!BuildStackString(cx, cx->realm()->principals(), stack, &stackString)) {
8042 return false;
8043 }
8044 stackVal.setString(stackString);
8045 } else {
8046 stackVal.setNull();
8047 }
8048
8049 RootedObject obj(cx, NewPlainObject(cx));
8050 if (!obj) {
8051 return false;
8052 }
8053
8054 if (!JS_DefineProperty(cx, obj, "exception", excVal, JSPROP_ENUMERATE)) {
8055 return false;
8056 }
8057
8058 if (!JS_DefineProperty(cx, obj, "stack", stackVal, JSPROP_ENUMERATE)) {
8059 return false;
8060 }
8061
8062 args.rval().setObject(*obj);
8063 return true;
8064 }
8065
8066 class AllocationMarkerObject : public NativeObject {
8067 public:
8068 static const JSClass class_;
8069 };
8070
8071 const JSClass AllocationMarkerObject::class_ = {
8072 "AllocationMarker",
8073 };
8074
8075 static bool AllocationMarker(JSContext* cx, unsigned argc, Value* vp) {
8076 CallArgs args = CallArgsFromVp(argc, vp);
8077
8078 bool allocateInsideNursery = true;
8079 if (args.length() > 0 && args[0].isObject()) {
8080 RootedObject options(cx, &args[0].toObject());
8081
8082 RootedValue nurseryVal(cx);
8083 if (!JS_GetProperty(cx, options, "nursery", &nurseryVal)) {
8084 return false;
8085 }
8086 allocateInsideNursery = ToBoolean(nurseryVal);
8087 }
8088
8089 JSObject* obj =
8090 allocateInsideNursery
8091 ? NewObjectWithGivenProto<AllocationMarkerObject>(cx, nullptr)
8092 : NewTenuredObjectWithGivenProto<AllocationMarkerObject>(cx, nullptr);
8093 if (!obj) {
8094 return false;
8095 }
8096
8097 args.rval().setObject(*obj);
8098 return true;
8099 }
8100
8101 namespace gcCallback {
8102
8103 struct MajorGC {
8104 int32_t depth;
8105 int32_t phases;
8106 };
8107
8108 static void majorGC(JSContext* cx, JSGCStatus status, JS::GCReason reason,
8109 void* data) {
8110 auto info = static_cast<MajorGC*>(data);
8111 if (!(info->phases & (1 << status))) {
8112 return;
8113 }
8114
8115 if (info->depth > 0) {
8116 info->depth--;
8117 JS::PrepareForFullGC(cx);
8118 JS::NonIncrementalGC(cx, JS::GCOptions::Normal, JS::GCReason::API);
8119 info->depth++;
8120 }
8121 }
8122
8123 struct MinorGC {
8124 int32_t phases;
8125 bool active;
8126 };
8127
8128 static void minorGC(JSContext* cx, JSGCStatus status, JS::GCReason reason,
8129 void* data) {
8130 auto info = static_cast<MinorGC*>(data);
8131 if (!(info->phases & (1 << status))) {
8132 return;
8133 }
8134
8135 if (info->active) {
8136 info->active = false;
8137 if (cx->zone() && !cx->zone()->isAtomsZone()) {
8138 cx->runtime()->gc.evictNursery(JS::GCReason::DEBUG_GC);
8139 }
8140 info->active = true;
8141 }
8142 }
8143
8144 // Process global, should really be runtime-local.
8145 static MajorGC majorGCInfo;
8146 static MinorGC minorGCInfo;
8147
8148 static void enterNullRealm(JSContext* cx, JSGCStatus status,
8149 JS::GCReason reason, void* data) {
8150 JSAutoNullableRealm enterRealm(cx, nullptr);
8151 }
8152
8153 } /* namespace gcCallback */
8154
8155 static bool SetGCCallback(JSContext* cx, unsigned argc, Value* vp) {
8156 CallArgs args = CallArgsFromVp(argc, vp);
8157
8158 if (args.length() != 1) {
8159 JS_ReportErrorASCII(cx, "Wrong number of arguments");
8160 return false;
8161 }
8162
8163 RootedObject opts(cx, ToObject(cx, args[0]));
8164 if (!opts) {
8165 return false;
8166 }
8167
8168 RootedValue v(cx);
8169 if (!JS_GetProperty(cx, opts, "action", &v)) {
8170 return false;
8171 }
8172
8173 JSString* str = JS::ToString(cx, v);
8174 if (!str) {
8175 return false;
8176 }
8177 Rooted<JSLinearString*> action(cx, str->ensureLinear(cx));
8178 if (!action) {
8179 return false;
8180 }
8181
8182 int32_t phases = 0;
8183 if (StringEqualsLiteral(action, "minorGC") ||
8184 StringEqualsLiteral(action, "majorGC")) {
8185 if (!JS_GetProperty(cx, opts, "phases", &v)) {
8186 return false;
8187 }
8188 if (v.isUndefined()) {
8189 phases = (1 << JSGC_END);
8190 } else {
8191 JSString* str = JS::ToString(cx, v);
8192 if (!str) {
8193 return false;
8194 }
8195 JSLinearString* phasesStr = str->ensureLinear(cx);
8196 if (!phasesStr) {
8197 return false;
8198 }
8199
8200 if (StringEqualsLiteral(phasesStr, "begin")) {
8201 phases = (1 << JSGC_BEGIN);
8202 } else if (StringEqualsLiteral(phasesStr, "end")) {
8203 phases = (1 << JSGC_END);
8204 } else if (StringEqualsLiteral(phasesStr, "both")) {
8205 phases = (1 << JSGC_BEGIN) | (1 << JSGC_END);
8206 } else {
8207 JS_ReportErrorASCII(cx, "Invalid callback phase");
8208 return false;
8209 }
8210 }
8211 }
8212
8213 if (StringEqualsLiteral(action, "minorGC")) {
8214 gcCallback::minorGCInfo.phases = phases;
8215 gcCallback::minorGCInfo.active = true;
8216 JS_SetGCCallback(cx, gcCallback::minorGC, &gcCallback::minorGCInfo);
8217 } else if (StringEqualsLiteral(action, "majorGC")) {
8218 if (!JS_GetProperty(cx, opts, "depth", &v)) {
8219 return false;
8220 }
8221 int32_t depth = 1;
8222 if (!v.isUndefined()) {
8223 if (!ToInt32(cx, v, &depth)) {
8224 return false;
8225 }
8226 }
8227 if (depth < 0) {
8228 JS_ReportErrorASCII(cx, "Nesting depth cannot be negative");
8229 return false;
8230 }
8231 if (depth + gcstats::MAX_PHASE_NESTING >
8232 gcstats::Statistics::MAX_SUSPENDED_PHASES) {
8233 JS_ReportErrorASCII(cx, "Nesting depth too large, would overflow");
8234 return false;
8235 }
8236
8237 gcCallback::majorGCInfo.phases = phases;
8238 gcCallback::majorGCInfo.depth = depth;
8239 JS_SetGCCallback(cx, gcCallback::majorGC, &gcCallback::majorGCInfo);
8240 } else if (StringEqualsLiteral(action, "enterNullRealm")) {
8241 JS_SetGCCallback(cx, gcCallback::enterNullRealm, nullptr);
8242 } else {
8243 JS_ReportErrorASCII(cx, "Unknown GC callback action");
8244 return false;
8245 }
8246
8247 args.rval().setUndefined();
8248 return true;
8249 }
8250
8251 #ifdef DEBUG
8252 static bool EnqueueMark(JSContext* cx, unsigned argc, Value* vp) {
8253 CallArgs args = CallArgsFromVp(argc, vp);
8254 gc::GCRuntime* gc = &cx->runtime()->gc;
8255
8256 if (gc->isIncrementalGCInProgress() &&
8257 gc->hasZealMode(gc::ZealMode::IncrementalMarkingValidator)) {
8258 JS_ReportErrorASCII(
8259 cx,
8260 "Can't add to test mark queue during incremental GC if marking "
8261 "validation is enabled as this can cause failures");
8262 return false;
8263 }
8264
8265 if (args.get(0).isString()) {
8266 RootedString val(cx, args[0].toString());
8267 if (!val->ensureLinear(cx)) {
8268 return false;
8269 }
8270 if (!gc->appendTestMarkQueue(StringValue(val))) {
8271 JS_ReportOutOfMemory(cx);
8272 return false;
8273 }
8274 } else if (args.get(0).isObject()) {
8275 if (!gc->appendTestMarkQueue(args[0])) {
8276 JS_ReportOutOfMemory(cx);
8277 return false;
8278 }
8279 } else {
8280 JS_ReportErrorASCII(cx, "Argument must be a string or object");
8281 return false;
8282 }
8283
8284 args.rval().setUndefined();
8285 return true;
8286 }
8287
8288 static bool GetMarkQueue(JSContext* cx, unsigned argc, Value* vp) {
8289 CallArgs args = CallArgsFromVp(argc, vp);
8290
8291 const auto& queue = cx->runtime()->gc.getTestMarkQueue();
8292
8293 RootedObject result(cx, JS::NewArrayObject(cx, queue.length()));
8294 if (!result) {
8295 return false;
8296 }
8297 for (size_t i = 0; i < queue.length(); i++) {
8298 RootedValue val(cx, queue[i]);
8299 if (!JS_WrapValue(cx, &val)) {
8300 return false;
8301 }
8302 if (!JS_SetElement(cx, result, i, val)) {
8303 return false;
8304 }
8305 }
8306
8307 args.rval().setObject(*result);
8308 return true;
8309 }
8310
8311 static bool ClearMarkQueue(JSContext* cx, unsigned argc, Value* vp) {
8312 CallArgs args = CallArgsFromVp(argc, vp);
8313
8314 cx->runtime()->gc.clearTestMarkQueue();
8315 args.rval().setUndefined();
8316 return true;
8317 }
8318 #endif // DEBUG
8319
8320 static bool NurseryStringsEnabled(JSContext* cx, unsigned argc, Value* vp) {
8321 CallArgs args = CallArgsFromVp(argc, vp);
8322 args.rval().setBoolean(cx->zone()->allocNurseryStrings());
8323 return true;
8324 }
8325
8326 static bool IsNurseryAllocated(JSContext* cx, unsigned argc, Value* vp) {
8327 CallArgs args = CallArgsFromVp(argc, vp);
8328 if (!args.get(0).isGCThing()) {
8329 JS_ReportErrorASCII(
8330 cx, "The function takes one argument, which must be a GC thing");
8331 return false;
8332 }
8333
8334 args.rval().setBoolean(IsInsideNursery(args[0].toGCThing()));
8335 return true;
8336 }
8337
8338 static bool NumAllocSitesPretenured(JSContext* cx, unsigned argc, Value* vp) {
8339 CallArgs args = CallArgsFromVp(argc, vp);
8340 args.rval().setInt32(cx->realm()->numAllocSitesPretenured);
8341 return true;
8342 }
8343
8344 static bool GetLcovInfo(JSContext* cx, unsigned argc, Value* vp) {
8345 CallArgs args = CallArgsFromVp(argc, vp);
8346
8347 if (args.length() > 1) {
8348 JS_ReportErrorASCII(cx, "Wrong number of arguments");
8349 return false;
8350 }
8351
8352 if (!coverage::IsLCovEnabled()) {
8353 JS_ReportErrorASCII(cx, "Coverage not enabled for process.");
8354 return false;
8355 }
8356
8357 RootedObject global(cx);
8358 if (args.hasDefined(0)) {
8359 global = ToObject(cx, args[0]);
8360 if (!global) {
8361 JS_ReportErrorASCII(cx, "Permission denied to access global");
8362 return false;
8363 }
8364 global = CheckedUnwrapDynamic(global, cx, /* stopAtWindowProxy = */ false);
8365 if (!global) {
8366 ReportAccessDenied(cx);
8367 return false;
8368 }
8369 if (!global->is<GlobalObject>()) {
8370 JS_ReportErrorASCII(cx, "Argument must be a global object");
8371 return false;
8372 }
8373 } else {
8374 global = JS::CurrentGlobalOrNull(cx);
8375 }
8376
8377 size_t length = 0;
8378 UniqueChars content;
8379 {
8380 AutoRealm ar(cx, global);
8381 content = js::GetCodeCoverageSummary(cx, &length);
8382 }
8383
8384 if (!content) {
8385 return false;
8386 }
8387
8388 JSString* str =
8389 JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(content.get(), length));
8390 if (!str) {
8391 return false;
8392 }
8393
8394 args.rval().setString(str);
8395 return true;
8396 }
8397
8398 #ifdef DEBUG
8399 static bool SetRNGState(JSContext* cx, unsigned argc, Value* vp) {
8400 CallArgs args = CallArgsFromVp(argc, vp);
8401 if (!args.requireAtLeast(cx, "SetRNGState", 2)) {
8402 return false;
8403 }
8404
8405 double d0;
8406 if (!ToNumber(cx, args[0], &d0)) {
8407 return false;
8408 }
8409
8410 double d1;
8411 if (!ToNumber(cx, args[1], &d1)) {
8412 return false;
8413 }
8414
8415 uint64_t seed0 = static_cast<uint64_t>(d0);
8416 uint64_t seed1 = static_cast<uint64_t>(d1);
8417
8418 if (seed0 == 0 && seed1 == 0) {
8419 JS_ReportErrorASCII(cx, "RNG requires non-zero seed");
8420 return false;
8421 }
8422
8423 cx->realm()->getOrCreateRandomNumberGenerator().setState(seed0, seed1);
8424
8425 args.rval().setUndefined();
8426 return true;
8427 }
8428 #endif
8429
8430 static bool GetTimeZone(JSContext* cx, unsigned argc, Value* vp) {
8431 CallArgs args = CallArgsFromVp(argc, vp);
8432 RootedObject callee(cx, &args.callee());
8433
8434 if (args.length() != 0) {
8435 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
8436 return false;
8437 }
8438
8439 #ifndef __wasi__
8440 auto getTimeZone = [](std::time_t* now) -> const char* {
8441 std::tm local{};
8442 # if defined(_WIN32)
8443 _tzset();
8444 if (localtime_s(&local, now) == 0) {
8445 return _tzname[local.tm_isdst > 0];
8446 }
8447 # else
8448 tzset();
8449 # if defined(HAVE_LOCALTIME_R)
8450 if (localtime_r(now, &local)) {
8451 # else
8452 std::tm* localtm = std::localtime(now);
8453 if (localtm) {
8454 *local = *localtm;
8455 # endif /* HAVE_LOCALTIME_R */
8456
8457 # if defined(HAVE_TM_ZONE_TM_GMTOFF)
8458 return local.tm_zone;
8459 # else
8460 return tzname[local.tm_isdst > 0];
8461 # endif /* HAVE_TM_ZONE_TM_GMTOFF */
8462 }
8463 # endif /* _WIN32 */
8464 return nullptr;
8465 };
8466
8467 std::time_t now = std::time(nullptr);
8468 if (now != static_cast<std::time_t>(-1)) {
8469 if (const char* tz = getTimeZone(&now)) {
8470 return ReturnStringCopy(cx, args, tz);
8471 }
8472 }
8473 #endif /* __wasi__ */
8474 args.rval().setUndefined();
8475 return true;
8476 }
8477
8478 /*
8479 * Validate time zone input. Accepts the following formats:
8480 * - "America/Chicago" (raw time zone)
8481 * - ":America/Chicago"
8482 * - "/this-part-is-ignored/zoneinfo/America/Chicago"
8483 * - ":/this-part-is-ignored/zoneinfo/America/Chicago"
8484 * - "/etc/localtime"
8485 * - ":/etc/localtime"
8486 * Once the raw time zone is parsed out of the string, it is checked
8487 * against the time zones from GetAvailableTimeZones(). Throws an
8488 * Error if the time zone is invalid.
8489 */
8490 #if defined(JS_HAS_INTL_API) && !defined(__wasi__)
8491 static bool ValidateTimeZone(JSContext* cx, const char* timeZone) {
8492 static constexpr char zoneInfo[] = "/zoneinfo/";
8493 static constexpr size_t zoneInfoLength = sizeof(zoneInfo) - 1;
8494
8495 size_t i = 0;
8496 if (timeZone[i] == ':') {
8497 ++i;
8498 }
8499 const char* zoneInfoPtr = strstr(timeZone, zoneInfo);
8500 const char* timeZonePart = timeZone[i] == '/' && zoneInfoPtr
8501 ? zoneInfoPtr + zoneInfoLength
8502 : timeZone + i;
8503
8504 if (!*timeZonePart) {
8505 JS_ReportErrorASCII(cx, "Invalid time zone format");
8506 return false;
8507 }
8508
8509 if (!strcmp(timeZonePart, "/etc/localtime")) {
8510 return true;
8511 }
8512
8513 auto timeZones = mozilla::intl::TimeZone::GetAvailableTimeZones();
8514 if (timeZones.isErr()) {
8515 intl::ReportInternalError(cx, timeZones.unwrapErr());
8516 return false;
8517 }
8518 for (auto timeZoneName : timeZones.unwrap()) {
8519 if (timeZoneName.isErr()) {
8520 intl::ReportInternalError(cx);
8521 return false;
8522 }
8523
8524 if (!strcmp(timeZonePart, timeZoneName.unwrap().data())) {
8525 return true;
8526 }
8527 }
8528
8529 JS_ReportErrorASCII(cx, "Unsupported time zone name: %s", timeZonePart);
8530 return false;
8531 }
8532 #endif
8533
8534 static bool SetTimeZone(JSContext* cx, unsigned argc, Value* vp) {
8535 CallArgs args = CallArgsFromVp(argc, vp);
8536 RootedObject callee(cx, &args.callee());
8537
8538 if (args.length() != 1) {
8539 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
8540 return false;
8541 }
8542
8543 if (!args[0].isString() && !args[0].isUndefined()) {
8544 ReportUsageErrorASCII(cx, callee,
8545 "First argument should be a string or undefined");
8546 return false;
8547 }
8548
8549 #ifndef __wasi__
8550 auto setTimeZone = [](const char* value) {
8551 # if defined(_WIN32)
8552 return _putenv_s("TZ", value) == 0;
8553 # else
8554 return setenv("TZ", value, true) == 0;
8555 # endif /* _WIN32 */
8556 };
8557
8558 auto unsetTimeZone = []() {
8559 # if defined(_WIN32)
8560 return _putenv_s("TZ", "") == 0;
8561 # else
8562 return unsetenv("TZ") == 0;
8563 # endif /* _WIN32 */
8564 };
8565
8566 if (args[0].isString() && !args[0].toString()->empty()) {
8567 Rooted<JSLinearString*> str(cx, args[0].toString()->ensureLinear(cx));
8568 if (!str) {
8569 return false;
8570 }
8571
8572 if (!StringIsAscii(str)) {
8573 ReportUsageErrorASCII(cx, callee,
8574 "First argument contains non-ASCII characters");
8575 return false;
8576 }
8577
8578 UniqueChars timeZone = JS_EncodeStringToASCII(cx, str);
8579 if (!timeZone) {
8580 return false;
8581 }
8582
8583 const char* timeZoneStr = timeZone.get();
8584 # ifdef JS_HAS_INTL_API
8585 if (!ValidateTimeZone(cx, timeZoneStr)) {
8586 return false;
8587 }
8588 # endif
8589
8590 if (!setTimeZone(timeZoneStr)) {
8591 JS_ReportErrorASCII(cx, "Failed to set 'TZ' environment variable");
8592 return false;
8593 }
8594 } else {
8595 if (!unsetTimeZone()) {
8596 JS_ReportErrorASCII(cx, "Failed to unset 'TZ' environment variable");
8597 return false;
8598 }
8599 }
8600
8601 # if defined(_WIN32)
8602 _tzset();
8603 # else
8604 tzset();
8605 # endif /* _WIN32 */
8606
8607 JS::ResetTimeZone();
8608
8609 #endif /* __wasi__ */
8610 args.rval().setUndefined();
8611 return true;
8612 }
8613
8614 static bool GetCoreCount(JSContext* cx, unsigned argc, Value* vp) {
8615 CallArgs args = CallArgsFromVp(argc, vp);
8616 RootedObject callee(cx, &args.callee());
8617
8618 if (args.length() != 0) {
8619 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
8620 return false;
8621 }
8622
8623 args.rval().setInt32(GetCPUCount());
8624 return true;
8625 }
8626
8627 static bool GetDefaultLocale(JSContext* cx, unsigned argc, Value* vp) {
8628 CallArgs args = CallArgsFromVp(argc, vp);
8629 RootedObject callee(cx, &args.callee());
8630
8631 if (args.length() != 0) {
8632 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
8633 return false;
8634 }
8635
8636 UniqueChars locale = JS_GetDefaultLocale(cx);
8637 if (!locale) {
8638 return false;
8639 }
8640
8641 return ReturnStringCopy(cx, args, locale.get());
8642 }
8643
8644 static bool SetDefaultLocale(JSContext* cx, unsigned argc, Value* vp) {
8645 CallArgs args = CallArgsFromVp(argc, vp);
8646 RootedObject callee(cx, &args.callee());
8647
8648 if (args.length() != 1) {
8649 ReportUsageErrorASCII(cx, callee, "Wrong number of arguments");
8650 return false;
8651 }
8652
8653 if (!args[0].isString() && !args[0].isUndefined()) {
8654 ReportUsageErrorASCII(cx, callee,
8655 "First argument should be a string or undefined");
8656 return false;
8657 }
8658
8659 if (args[0].isString() && !args[0].toString()->empty()) {
8660 RootedString str(cx, args[0].toString());
8661 UniqueChars locale = StringToLocale(cx, callee, str);
8662 if (!locale) {
8663 return false;
8664 }
8665
8666 if (!JS_SetDefaultLocale(cx->runtime(), locale.get())) {
8667 ReportOutOfMemory(cx);
8668 return false;
8669 }
8670 } else {
8671 JS_ResetDefaultLocale(cx->runtime());
8672 }
8673
8674 args.rval().setUndefined();
8675 return true;
8676 }
8677
8678 #ifdef AFLFUZZ
8679 static bool AflLoop(JSContext* cx, unsigned argc, Value* vp) {
8680 CallArgs args = CallArgsFromVp(argc, vp);
8681
8682 uint32_t max_cnt;
8683 if (!ToUint32(cx, args.get(0), &max_cnt)) {
8684 return false;
8685 }
8686
8687 args.rval().setBoolean(!!__AFL_LOOP(max_cnt));
8688 return true;
8689 }
8690 #endif
8691
8692 static bool MonotonicNow(JSContext* cx, unsigned argc, Value* vp) {
8693 CallArgs args = CallArgsFromVp(argc, vp);
8694 double now;
8695
8696 // The std::chrono symbols are too new to be present in STL on all platforms we
8697 // care about, so use raw POSIX clock APIs when it might be necessary.
8698 #if defined(XP_UNIX) && !defined(XP_DARWIN)
8699 auto ComputeNow = [](const timespec& ts) {
8700 return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
8701 };
8702
8703 timespec ts;
8704 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
8705 // Use a monotonic clock if available.
8706 now = ComputeNow(ts);
8707 } else {
8708 // Use a realtime clock as fallback.
8709 if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
8710 // Fail if no clock is available.
8711 JS_ReportErrorASCII(cx, "can't retrieve system clock");
8712 return false;
8713 }
8714
8715 now = ComputeNow(ts);
8716
8717 // Manually enforce atomicity on a non-monotonic clock.
8718 {
8719 static mozilla::Atomic<bool, mozilla::ReleaseAcquire> spinLock;
8720 while (!spinLock.compareExchange(false, true)) {
8721 continue;
8722 }
8723
8724 static double lastNow = -FLT_MAX;
8725 now = lastNow = std::max(now, lastNow);
8726
8727 spinLock = false;
8728 }
8729 }
8730 #else
8731 using std::chrono::duration_cast;
8732 using std::chrono::milliseconds;
8733 using std::chrono::steady_clock;
8734 now = duration_cast<milliseconds>(steady_clock::now().time_since_epoch())
8735 .count();
8736 #endif // XP_UNIX && !XP_DARWIN
8737
8738 args.rval().setNumber(now);
8739 return true;
8740 }
8741
8742 static bool TimeSinceCreation(JSContext* cx, unsigned argc, Value* vp) {
8743 CallArgs args = CallArgsFromVp(argc, vp);
8744 double when =
8745 (mozilla::TimeStamp::Now() - mozilla::TimeStamp::ProcessCreation())
8746 .ToMilliseconds();
8747 args.rval().setNumber(when);
8748 return true;
8749 }
8750
8751 static bool GetInnerMostEnvironmentObject(JSContext* cx, unsigned argc,
8752 Value* vp) {
8753 CallArgs args = CallArgsFromVp(argc, vp);
8754
8755 FrameIter iter(cx);
8756 if (iter.done()) {
8757 args.rval().setNull();
8758 return true;
8759 }
8760
8761 args.rval().setObjectOrNull(iter.environmentChain(cx));
8762 return true;
8763 }
8764
8765 static bool GetEnclosingEnvironmentObject(JSContext* cx, unsigned argc,
8766 Value* vp) {
8767 CallArgs args = CallArgsFromVp(argc, vp);
8768 if (!args.requireAtLeast(cx, "getEnclosingEnvironmentObject", 1)) {
8769 return false;
8770 }
8771
8772 if (!args[0].isObject()) {
8773 args.rval().setUndefined();
8774 return true;
8775 }
8776
8777 JSObject* envObj = &args[0].toObject();
8778
8779 if (envObj->is<EnvironmentObject>()) {
8780 EnvironmentObject* env = &envObj->as<EnvironmentObject>();
8781 args.rval().setObject(env->enclosingEnvironment());
8782 return true;
8783 }
8784
8785 if (envObj->is<DebugEnvironmentProxy>()) {
8786 DebugEnvironmentProxy* envProxy = &envObj->as<DebugEnvironmentProxy>();
8787 args.rval().setObject(envProxy->enclosingEnvironment());
8788 return true;
8789 }
8790
8791 args.rval().setNull();
8792 return true;
8793 }
8794
8795 static bool GetEnvironmentObjectType(JSContext* cx, unsigned argc, Value* vp) {
8796 CallArgs args = CallArgsFromVp(argc, vp);
8797 if (!args.requireAtLeast(cx, "getEnvironmentObjectType", 1)) {
8798 return false;
8799 }
8800
8801 if (!args[0].isObject()) {
8802 args.rval().setUndefined();
8803 return true;
8804 }
8805
8806 JSObject* envObj = &args[0].toObject();
8807
8808 if (envObj->is<EnvironmentObject>()) {
8809 EnvironmentObject* env = &envObj->as<EnvironmentObject>();
8810 JSString* str = JS_NewStringCopyZ(cx, env->typeString());
8811 args.rval().setString(str);
8812 return true;
8813 }
8814 if (envObj->is<DebugEnvironmentProxy>()) {
8815 DebugEnvironmentProxy* envProxy = &envObj->as<DebugEnvironmentProxy>();
8816 EnvironmentObject* env = &envProxy->environment();
8817 char buf[256] = {'\0'};
8818 SprintfLiteral(buf, "[DebugProxy] %s", env->typeString());
8819 JSString* str = JS_NewStringCopyZ(cx, buf);
8820 args.rval().setString(str);
8821 return true;
8822 }
8823
8824 args.rval().setUndefined();
8825 return true;
8826 }
8827
8828 static bool AssertRealmFuseInvariants(JSContext* cx, unsigned argc, Value* vp) {
8829 CallArgs args = CallArgsFromVp(argc, vp);
8830 // Note: This will crash if any invariant isn't held, so it's sufficient to
8831 // simply return true always.
8832 cx->realm()->realmFuses.assertInvariants(cx);
8833 args.rval().setUndefined();
8834 return true;
8835 }
8836
8837 static bool GetFuseState(JSContext* cx, unsigned argc, Value* vp) {
8838 CallArgs args = CallArgsFromVp(argc, vp);
8839
8840 cx->realm()->realmFuses.assertInvariants(cx);
8841
8842 RootedObject returnObj(cx, JS_NewPlainObject(cx));
8843 if (!returnObj) {
8844 return false;
8845 }
8846
8847 RootedObject fuseObj(cx);
8848 RootedString intactStr(cx, NewStringCopyZ<CanGC>(cx, "intact"));
8849 if (!intactStr) {
8850 return false;
8851 }
8852
8853 RootedValue intactValue(cx);
8854
8855 #define FUSE(Name, LowerName) \
8856 fuseObj = JS_NewPlainObject(cx); \
8857 if (!fuseObj) { \
8858 return false; \
8859 } \
8860 intactValue.setBoolean(cx->realm()->realmFuses.LowerName.intact()); \
8861 if (!JS_DefineProperty(cx, fuseObj, "intact", intactValue, \
8862 JSPROP_ENUMERATE)) { \
8863 return false; \
8864 } \
8865 if (!JS_DefineProperty(cx, returnObj, #Name, fuseObj, JSPROP_ENUMERATE)) { \
8866 return false; \
8867 }
8868
8869 FOR_EACH_REALM_FUSE(FUSE)
8870 #undef FUSE
8871
8872 // Register hasSeenUndefinedFuse
8873 fuseObj = JS_NewPlainObject(cx);
8874 if (!fuseObj) {
8875 return false;
8876 }
8877 intactValue.setBoolean(
8878 cx->runtime()->hasSeenObjectEmulateUndefinedFuse.ref().intact());
8879 if (!JS_DefineProperty(cx, fuseObj, "intact", intactValue,
8880 JSPROP_ENUMERATE)) {
8881 return false;
8882 }
8883
8884 if (!JS_DefineProperty(cx, returnObj, "hasSeenObjectEmulateUndefinedFuse",
8885 fuseObj, JSPROP_ENUMERATE)) {
8886 return false;
8887 }
8888
8889 fuseObj = JS_NewPlainObject(cx);
8890 if (!fuseObj) {
8891 return false;
8892 }
8893 intactValue.setBoolean(
8894 cx->runtime()->hasSeenArrayExceedsInt32LengthFuse.ref().intact());
8895 if (!JS_DefineProperty(cx, fuseObj, "intact", intactValue,
8896 JSPROP_ENUMERATE)) {
8897 return false;
8898 }
8899 if (!JS_DefineProperty(cx, returnObj, "hasSeenArrayExceedsInt32LengthFuse",
8900 fuseObj, JSPROP_ENUMERATE)) {
8901 return false;
8902 }
8903
8904 args.rval().setObject(*returnObj);
8905 return true;
8906 }
8907
8908 static bool PopAllFusesInRealm(JSContext* cx, unsigned argc, Value* vp) {
8909 CallArgs args = CallArgsFromVp(argc, vp);
8910
8911 MOZ_ASSERT(cx->realm());
8912
8913 RealmFuses& realmFuses = cx->realm()->realmFuses;
8914
8915 #define FUSE(Name, LowerName) realmFuses.LowerName.popFuse(cx, realmFuses);
8916 FOR_EACH_REALM_FUSE(FUSE)
8917 #undef FUSE
8918
8919 args.rval().setUndefined();
8920 return true;
8921 }
8922
8923 static bool GetAllPrefNames(JSContext* cx, unsigned argc, Value* vp) {
8924 CallArgs args = CallArgsFromVp(argc, vp);
8925
8926 RootedValueVector values(cx);
8927
8928 auto addPref = [cx, &values](const char* name) {
8929 JSString* s = JS_NewStringCopyZ(cx, name);
8930 if (!s) {
8931 return false;
8932 }
8933 return values.append(StringValue(s));
8934 };
8935
8936 #define ADD_NAME(NAME, CPP_NAME, TYPE, SETTER, IS_STARTUP_PREF) \
8937 if (!addPref(NAME)) { \
8938 return false; \
8939 }
8940 FOR_EACH_JS_PREF(ADD_NAME)
8941 #undef ADD_NAME
8942
8943 ArrayObject* arr = NewDenseCopiedArray(cx, values.length(), values.begin());
8944 if (!arr) {
8945 return false;
8946 }
8947
8948 args.rval().setObject(*arr);
8949 return true;
8950 }
8951
8952 static bool GetPrefValue(JSContext* cx, unsigned argc, Value* vp) {
8953 CallArgs args = CallArgsFromVp(argc, vp);
8954 if (!args.requireAtLeast(cx, "getPrefValue", 1)) {
8955 return false;
8956 }
8957
8958 if (!args[0].isString()) {
8959 JS_ReportErrorASCII(cx, "expected string argument");
8960 return false;
8961 }
8962
8963 Rooted<JSLinearString*> name(cx, args[0].toString()->ensureLinear(cx));
8964 if (!name) {
8965 return false;
8966 }
8967
8968 auto setReturnValue = [&args](auto value) {
8969 using T = decltype(value);
8970 if constexpr (std::is_same_v<T, bool>) {
8971 args.rval().setBoolean(value);
8972 } else {
8973 static_assert(std::is_same_v<T, int32_t> || std::is_same_v<T, uint32_t>);
8974 args.rval().setNumber(value);
8975 }
8976 };
8977
8978 // Search for a matching pref and return its value.
8979 #define CHECK_PREF(NAME, CPP_NAME, TYPE, SETTER, IS_STARTUP_PREF) \
8980 if (StringEqualsAscii(name, NAME)) { \
8981 setReturnValue(JS::Prefs::CPP_NAME()); \
8982 return true; \
8983 }
8984 FOR_EACH_JS_PREF(CHECK_PREF)
8985 #undef CHECK_PREF
8986
8987 JS_ReportErrorASCII(cx, "invalid pref name");
8988 return false;
8989 }
8990
8991 static bool GetErrorNotes(JSContext* cx, unsigned argc, Value* vp) {
8992 CallArgs args = CallArgsFromVp(argc, vp);
8993 if (!args.requireAtLeast(cx, "getErrorNotes", 1)) {
8994 return false;
8995 }
8996
8997 if (!args[0].isObject() || !args[0].toObject().is<ErrorObject>()) {
8998 args.rval().setNull();
8999 return true;
9000 }
9001
9002 JSErrorReport* report = args[0].toObject().as<ErrorObject>().getErrorReport();
9003 if (!report) {
9004 args.rval().setNull();
9005 return true;
9006 }
9007
9008 RootedObject notesArray(cx, CreateErrorNotesArray(cx, report));
9009 if (!notesArray) {
9010 return false;
9011 }
9012
9013 args.rval().setObject(*notesArray);
9014 return true;
9015 }
9016
9017 static bool IsConstructor(JSContext* cx, unsigned argc, Value* vp) {
9018 CallArgs args = CallArgsFromVp(argc, vp);
9019 if (args.length() < 1) {
9020 args.rval().setBoolean(false);
9021 } else {
9022 args.rval().setBoolean(IsConstructor(args[0]));
9023 }
9024 return true;
9025 }
9026
9027 static bool SetTimeResolution(JSContext* cx, unsigned argc, Value* vp) {
9028 CallArgs args = CallArgsFromVp(argc, vp);
9029 RootedObject callee(cx, &args.callee());
9030
9031 if (!args.requireAtLeast(cx, "setTimeResolution", 2)) {
9032 return false;
9033 }
9034
9035 if (!args[0].isInt32()) {
9036 ReportUsageErrorASCII(cx, callee, "First argument must be an Int32.");
9037 return false;
9038 }
9039 int32_t resolution = args[0].toInt32();
9040
9041 if (!args[1].isBoolean()) {
9042 ReportUsageErrorASCII(cx, callee, "Second argument must be a Boolean");
9043 return false;
9044 }
9045 bool jitter = args[1].toBoolean();
9046
9047 JS::SetTimeResolutionUsec(resolution, jitter);
9048
9049 args.rval().setUndefined();
9050 return true;
9051 }
9052
9053 static bool ScriptedCallerGlobal(JSContext* cx, unsigned argc, Value* vp) {
9054 CallArgs args = CallArgsFromVp(argc, vp);
9055
9056 RootedObject obj(cx, JS::GetScriptedCallerGlobal(cx));
9057 if (!obj) {
9058 args.rval().setNull();
9059 return true;
9060 }
9061
9062 obj = ToWindowProxyIfWindow(obj);
9063
9064 if (!cx->compartment()->wrap(cx, &obj)) {
9065 return false;
9066 }
9067
9068 args.rval().setObject(*obj);
9069 return true;
9070 }
9071
9072 static bool ObjectGlobal(JSContext* cx, unsigned argc, Value* vp) {
9073 CallArgs args = CallArgsFromVp(argc, vp);
9074 RootedObject callee(cx, &args.callee());
9075
9076 if (!args.get(0).isObject()) {
9077 ReportUsageErrorASCII(cx, callee, "Argument must be an object");
9078 return false;
9079 }
9080
9081 RootedObject obj(cx, &args[0].toObject());
9082 if (IsCrossCompartmentWrapper(obj)) {
9083 args.rval().setNull();
9084 return true;
9085 }
9086
9087 obj = ToWindowProxyIfWindow(&obj->nonCCWGlobal());
9088
9089 args.rval().setObject(*obj);
9090 return true;
9091 }
9092
9093 static bool IsSameCompartment(JSContext* cx, unsigned argc, Value* vp) {
9094 CallArgs args = CallArgsFromVp(argc, vp);
9095 RootedObject callee(cx, &args.callee());
9096
9097 if (!args.get(0).isObject() || !args.get(1).isObject()) {
9098 ReportUsageErrorASCII(cx, callee, "Both arguments must be objects");
9099 return false;
9100 }
9101
9102 RootedObject obj1(cx, UncheckedUnwrap(&args[0].toObject()));
9103 RootedObject obj2(cx, UncheckedUnwrap(&args[1].toObject()));
9104
9105 args.rval().setBoolean(obj1->compartment() == obj2->compartment());
9106 return true;
9107 }
9108
9109 static bool FirstGlobalInCompartment(JSContext* cx, unsigned argc, Value* vp) {
9110 CallArgs args = CallArgsFromVp(argc, vp);
9111 RootedObject callee(cx, &args.callee());
9112
9113 if (!args.get(0).isObject()) {
9114 ReportUsageErrorASCII(cx, callee, "Argument must be an object");
9115 return false;
9116 }
9117
9118 RootedObject obj(cx, UncheckedUnwrap(&args[0].toObject()));
9119 obj = ToWindowProxyIfWindow(GetFirstGlobalInCompartment(obj->compartment()));
9120
9121 if (!cx->compartment()->wrap(cx, &obj)) {
9122 return false;
9123 }
9124
9125 args.rval().setObject(*obj);
9126 return true;
9127 }
9128
9129 static bool AssertCorrectRealm(JSContext* cx, unsigned argc, Value* vp) {
9130 CallArgs args = CallArgsFromVp(argc, vp);
9131 MOZ_RELEASE_ASSERT(cx->realm() == args.callee().as<JSFunction>().realm());
9132 args.rval().setUndefined();
9133 return true;
9134 }
9135
9136 static bool GlobalLexicals(JSContext* cx, unsigned argc, Value* vp) {
9137 CallArgs args = CallArgsFromVp(argc, vp);
9138
9139 Rooted<GlobalLexicalEnvironmentObject*> globalLexical(
9140 cx, &cx->global()->lexicalEnvironment());
9141
9142 RootedIdVector props(cx);
9143 if (!GetPropertyKeys(cx, globalLexical, JSITER_HIDDEN, &props)) {
9144 return false;
9145 }
9146
9147 RootedObject res(cx, JS_NewPlainObject(cx));
9148 if (!res) {
9149 return false;
9150 }
9151
9152 RootedValue val(cx);
9153 for (size_t i = 0; i < props.length(); i++) {
9154 HandleId id = props[i];
9155 if (!JS_GetPropertyById(cx, globalLexical, id, &val)) {
9156 return false;
9157 }
9158 if (val.isMagic(JS_UNINITIALIZED_LEXICAL)) {
9159 continue;
9160 }
9161 if (!JS_DefinePropertyById(cx, res, id, val, JSPROP_ENUMERATE)) {
9162 return false;
9163 }
9164 }
9165
9166 args.rval().setObject(*res);
9167 return true;
9168 }
9169
9170 static bool EncodeAsUtf8InBuffer(JSContext* cx, unsigned argc, Value* vp) {
9171 CallArgs args = CallArgsFromVp(argc, vp);
9172 if (!args.requireAtLeast(cx, "encodeAsUtf8InBuffer", 2)) {
9173 return false;
9174 }
9175
9176 RootedObject callee(cx, &args.callee());
9177
9178 if (!args[0].isString()) {
9179 ReportUsageErrorASCII(cx, callee, "First argument must be a String");
9180 return false;
9181 }
9182
9183 // Create the amounts array early so that the raw pointer into Uint8Array
9184 // data has as short a lifetime as possible
9185 Rooted<ArrayObject*> array(cx, NewDenseFullyAllocatedArray(cx, 2));
9186 if (!array) {
9187 return false;
9188 }
9189 array->ensureDenseInitializedLength(0, 2);
9190
9191 JSObject* obj = args[1].isObject() ? &args[1].toObject() : nullptr;
9192 Rooted<JS::Uint8Array> view(cx, JS::Uint8Array::unwrap(obj));
9193 if (!view) {
9194 ReportUsageErrorASCII(cx, callee, "Second argument must be a Uint8Array");
9195 return false;
9196 }
9197
9198 mozilla::Span<uint8_t> span;
9199 bool isSharedMemory = false;
9200 {
9201 // The hazard analysis does not track the data pointer, so it can neither
9202 // tell that `data` is dead if ReportUsageErrorASCII is called, nor that
9203 // its live range ends at the call to AsWritableChars(). Construct a
9204 // temporary scope to hide from the analysis. This should really be replaced
9205 // with a safer mechanism.
9206 JS::AutoCheckCannotGC nogc(cx);
9207 if (!view.isDetached()) {
9208 span = view.get().getData(&isSharedMemory, nogc);
9209 }
9210 }
9211
9212 if (isSharedMemory || // exclude views of SharedArrayBuffers
9213 !span.data()) { // exclude views of detached ArrayBuffers
9214 ReportUsageErrorASCII(
9215 cx, callee,
9216 "Second argument must be an unshared, non-detached Uint8Array");
9217 return false;
9218 }
9219
9220 Maybe<std::tuple<size_t, size_t>> amounts =
9221 JS_EncodeStringToUTF8BufferPartial(cx, args[0].toString(),
9222 AsWritableChars(span));
9223 if (!amounts) {
9224 ReportOutOfMemory(cx);
9225 return false;
9226 }
9227
9228 auto [unitsRead, bytesWritten] = *amounts;
9229
9230 array->initDenseElement(0, Int32Value(AssertedCast<int32_t>(unitsRead)));
9231 array->initDenseElement(1, Int32Value(AssertedCast<int32_t>(bytesWritten)));
9232
9233 args.rval().setObject(*array);
9234 return true;
9235 }
9236
9237 JSScript* js::TestingFunctionArgumentToScript(
9238 JSContext* cx, HandleValue v, JSFunction** funp /* = nullptr */) {
9239 if (v.isString()) {
9240 // To convert a string to a script, compile it. Parse it as an ES6 Program.
9241 Rooted<JSString*> str(cx, v.toString());
9242 AutoStableStringChars linearChars(cx);
9243 if (!linearChars.initTwoByte(cx, str)) {
9244 return nullptr;
9245 }
9246 SourceText<char16_t> source;
9247 if (!source.initMaybeBorrowed(cx, linearChars)) {
9248 return nullptr;
9249 }
9250
9251 CompileOptions options(cx);
9252 return JS::Compile(cx, options, source);
9253 }
9254
9255 RootedFunction fun(cx, JS_ValueToFunction(cx, v));
9256 if (!fun) {
9257 return nullptr;
9258 }
9259
9260 if (!fun->isInterpreted()) {
9261 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
9262 JSMSG_TESTING_SCRIPTS_ONLY);
9263 return nullptr;
9264 }
9265
9266 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
9267 if (!script) {
9268 return nullptr;
9269 }
9270
9271 if (funp) {
9272 *funp = fun;
9273 }
9274
9275 return script;
9276 }
9277
9278 static bool BaselineCompile(JSContext* cx, unsigned argc, Value* vp) {
9279 CallArgs args = CallArgsFromVp(argc, vp);
9280 RootedObject callee(cx, &args.callee());
9281
9282 RootedScript script(cx);
9283 if (args.length() == 0) {
9284 NonBuiltinScriptFrameIter iter(cx);
9285 if (iter.done()) {
9286 ReportUsageErrorASCII(cx, callee,
9287 "no script argument and no script caller");
9288 return false;
9289 }
9290 script = iter.script();
9291 } else {
9292 script = TestingFunctionArgumentToScript(cx, args[0]);
9293 if (!script) {
9294 return false;
9295 }
9296 }
9297
9298 bool forceDebug = false;
9299 if (args.length() > 1) {
9300 if (args.length() > 2) {
9301 ReportUsageErrorASCII(cx, callee, "too many arguments");
9302 return false;
9303 }
9304 if (!args[1].isBoolean() && !args[1].isUndefined()) {
9305 ReportUsageErrorASCII(
9306 cx, callee, "forceDebugInstrumentation argument should be boolean");
9307 return false;
9308 }
9309 forceDebug = ToBoolean(args[1]);
9310 }
9311
9312 const char* returnedStr = nullptr;
9313 do {
9314 // In order to check for differential behaviour, baselineCompile should have
9315 // the same output whether --no-baseline is used or not.
9316 if (js::SupportDifferentialTesting()) {
9317 returnedStr = "skipped (differential testing)";
9318 break;
9319 }
9320
9321 AutoRealm ar(cx, script);
9322 if (script->isBaselineCompilingOffThread()) {
9323 CancelOffThreadBaselineCompile(script);
9324 }
9325
9326 if (script->hasBaselineScript()) {
9327 if (forceDebug && !script->baselineScript()->hasDebugInstrumentation()) {
9328 // There isn't an easy way to do this for a script that might be on
9329 // stack right now. See
9330 // js::jit::RecompileOnStackBaselineScriptsForDebugMode.
9331 ReportUsageErrorASCII(
9332 cx, callee, "unsupported case: recompiling script for debug mode");
9333 return false;
9334 }
9335
9336 args.rval().setUndefined();
9337 return true;
9338 }
9339
9340 if (!jit::IsBaselineJitEnabled(cx)) {
9341 returnedStr = "baseline disabled";
9342 break;
9343 }
9344 if (!script->canBaselineCompile()) {
9345 returnedStr = "can't compile";
9346 break;
9347 }
9348 if (!cx->zone()->ensureJitZoneExists(cx)) {
9349 return false;
9350 }
9351
9352 jit::BaselineOptions options = {
9353 jit::BaselineOption::ForceMainThreadCompilation};
9354 if (forceDebug) {
9355 options.setFlag(jit::BaselineOption::ForceDebugInstrumentation);
9356 }
9357 jit::MethodStatus status = jit::BaselineCompile(cx, script, options);
9358 switch (status) {
9359 case jit::Method_Error:
9360 return false;
9361 case jit::Method_CantCompile:
9362 returnedStr = "can't compile";
9363 break;
9364 case jit::Method_Skipped:
9365 returnedStr = "skipped";
9366 break;
9367 case jit::Method_Compiled:
9368 args.rval().setUndefined();
9369 }
9370 } while (false);
9371
9372 if (returnedStr) {
9373 return ReturnStringCopy(cx, args, returnedStr);
9374 }
9375
9376 return true;
9377 }
9378
9379 static bool ClearKeptObjects(JSContext* cx, unsigned argc, Value* vp) {
9380 CallArgs args = CallArgsFromVp(argc, vp);
9381 JS::ClearKeptObjects(cx);
9382 args.rval().setUndefined();
9383 return true;
9384 }
9385
9386 static bool NumberToDouble(JSContext* cx, unsigned argc, Value* vp) {
9387 CallArgs args = CallArgsFromVp(argc, vp);
9388 if (!args.requireAtLeast(cx, "numberToDouble", 1)) {
9389 return false;
9390 }
9391
9392 if (!args[0].isNumber()) {
9393 RootedObject callee(cx, &args.callee());
9394 ReportUsageErrorASCII(cx, callee, "argument must be a number");
9395 return false;
9396 }
9397
9398 args.rval().setDouble(args[0].toNumber());
9399 return true;
9400 }
9401
9402 static bool GetICUOptions(JSContext* cx, unsigned argc, Value* vp) {
9403 CallArgs args = CallArgsFromVp(argc, vp);
9404
9405 RootedObject info(cx, JS_NewPlainObject(cx));
9406 if (!info) {
9407 return false;
9408 }
9409
9410 #ifdef JS_HAS_INTL_API
9411 RootedString str(cx);
9412
9413 str = NewStringCopy<CanGC>(cx, mozilla::intl::ICU4CLibrary::GetVersion());
9414 if (!str || !JS_DefineProperty(cx, info, "version", str, JSPROP_ENUMERATE)) {
9415 return false;
9416 }
9417
9418 str = NewStringCopy<CanGC>(cx, mozilla::intl::String::GetUnicodeVersion());
9419 if (!str || !JS_DefineProperty(cx, info, "unicode", str, JSPROP_ENUMERATE)) {
9420 return false;
9421 }
9422
9423 str = NewStringCopyZ<CanGC>(cx, mozilla::intl::Locale::GetDefaultLocale());
9424 if (!str || !JS_DefineProperty(cx, info, "locale", str, JSPROP_ENUMERATE)) {
9425 return false;
9426 }
9427
9428 auto tzdataVersion = mozilla::intl::TimeZone::GetTZDataVersion();
9429 if (tzdataVersion.isErr()) {
9430 intl::ReportInternalError(cx, tzdataVersion.unwrapErr());
9431 return false;
9432 }
9433
9434 str = NewStringCopy<CanGC>(cx, tzdataVersion.unwrap());
9435 if (!str || !JS_DefineProperty(cx, info, "tzdata", str, JSPROP_ENUMERATE)) {
9436 return false;
9437 }
9438
9439 intl::FormatBuffer<char16_t, intl::INITIAL_CHAR_BUFFER_SIZE> buf(cx);
9440
9441 if (auto ok = DateTimeInfo::timeZoneId(DateTimeInfo::ForceUTC::No, buf);
9442 ok.isErr()) {
9443 intl::ReportInternalError(cx, ok.unwrapErr());
9444 return false;
9445 }
9446
9447 str = buf.toString(cx);
9448 if (!str || !JS_DefineProperty(cx, info, "timezone", str, JSPROP_ENUMERATE)) {
9449 return false;
9450 }
9451
9452 if (auto ok = mozilla::intl::TimeZone::GetHostTimeZone(buf); ok.isErr()) {
9453 intl::ReportInternalError(cx, ok.unwrapErr());
9454 return false;
9455 }
9456
9457 str = buf.toString(cx);
9458 if (!str ||
9459 !JS_DefineProperty(cx, info, "host-timezone", str, JSPROP_ENUMERATE)) {
9460 return false;
9461 }
9462 #endif
9463
9464 args.rval().setObject(*info);
9465 return true;
9466 }
9467
9468 static bool GetAvailableLocalesOf(JSContext* cx, unsigned argc, Value* vp) {
9469 CallArgs args = CallArgsFromVp(argc, vp);
9470 RootedObject callee(cx, &args.callee());
9471
9472 if (!args.requireAtLeast(cx, "getAvailableLocalesOf", 1)) {
9473 return false;
9474 }
9475
9476 HandleValue arg = args[0];
9477 if (!arg.isString()) {
9478 ReportUsageErrorASCII(cx, callee, "First argument must be a string");
9479 return false;
9480 }
9481
9482 ArrayObject* result;
9483 #ifdef JS_HAS_INTL_API
9484 using SupportedLocaleKind = js::intl::SharedIntlData::SupportedLocaleKind;
9485
9486 SupportedLocaleKind kind;
9487 {
9488 JSLinearString* typeStr = arg.toString()->ensureLinear(cx);
9489 if (!typeStr) {
9490 return false;
9491 }
9492
9493 if (StringEqualsLiteral(typeStr, "Collator")) {
9494 kind = SupportedLocaleKind::Collator;
9495 } else if (StringEqualsLiteral(typeStr, "DateTimeFormat")) {
9496 kind = SupportedLocaleKind::DateTimeFormat;
9497 } else if (StringEqualsLiteral(typeStr, "DisplayNames")) {
9498 kind = SupportedLocaleKind::DisplayNames;
9499 } else if (StringEqualsLiteral(typeStr, "DurationFormat")) {
9500 kind = SupportedLocaleKind::DurationFormat;
9501 } else if (StringEqualsLiteral(typeStr, "ListFormat")) {
9502 kind = SupportedLocaleKind::ListFormat;
9503 } else if (StringEqualsLiteral(typeStr, "NumberFormat")) {
9504 kind = SupportedLocaleKind::NumberFormat;
9505 } else if (StringEqualsLiteral(typeStr, "PluralRules")) {
9506 kind = SupportedLocaleKind::PluralRules;
9507 } else if (StringEqualsLiteral(typeStr, "RelativeTimeFormat")) {
9508 kind = SupportedLocaleKind::RelativeTimeFormat;
9509 } else if (StringEqualsLiteral(typeStr, "Segmenter")) {
9510 kind = SupportedLocaleKind::Segmenter;
9511 } else {
9512 ReportUsageErrorASCII(cx, callee, "Unsupported Intl constructor name");
9513 return false;
9514 }
9515 }
9516
9517 intl::SharedIntlData& sharedIntlData = cx->runtime()->sharedIntlData.ref();
9518 result = sharedIntlData.availableLocalesOf(cx, kind);
9519 #else
9520 result = NewDenseEmptyArray(cx);
9521 #endif
9522 if (!result) {
9523 return false;
9524 }
9525
9526 args.rval().setObject(*result);
9527 return true;
9528 }
9529
9530 static bool IsSmallFunction(JSContext* cx, unsigned argc, Value* vp) {
9531 CallArgs args = CallArgsFromVp(argc, vp);
9532 RootedObject callee(cx, &args.callee());
9533
9534 if (!args.requireAtLeast(cx, "IsSmallFunction", 1)) {
9535 return false;
9536 }
9537
9538 HandleValue arg = args[0];
9539 if (!arg.isObject() || !arg.toObject().is<JSFunction>()) {
9540 ReportUsageErrorASCII(cx, callee, "First argument must be a function");
9541 return false;
9542 }
9543
9544 RootedFunction fun(cx, &args[0].toObject().as<JSFunction>());
9545 if (!fun->isInterpreted()) {
9546 ReportUsageErrorASCII(cx, callee,
9547 "First argument must be an interpreted function");
9548 return false;
9549 }
9550
9551 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
9552 if (!script) {
9553 return false;
9554 }
9555
9556 args.rval().setBoolean(jit::JitOptions.isSmallFunction(script));
9557 return true;
9558 }
9559
9560 static bool PCCountProfiling_Start(JSContext* cx, unsigned argc, Value* vp) {
9561 CallArgs args = CallArgsFromVp(argc, vp);
9562
9563 JS::StartPCCountProfiling(cx);
9564
9565 args.rval().setUndefined();
9566 return true;
9567 }
9568
9569 static bool PCCountProfiling_Stop(JSContext* cx, unsigned argc, Value* vp) {
9570 CallArgs args = CallArgsFromVp(argc, vp);
9571
9572 JS::StopPCCountProfiling(cx);
9573
9574 args.rval().setUndefined();
9575 return true;
9576 }
9577
9578 static bool PCCountProfiling_Purge(JSContext* cx, unsigned argc, Value* vp) {
9579 CallArgs args = CallArgsFromVp(argc, vp);
9580
9581 JS::PurgePCCounts(cx);
9582
9583 args.rval().setUndefined();
9584 return true;
9585 }
9586
9587 static bool PCCountProfiling_ScriptCount(JSContext* cx, unsigned argc,
9588 Value* vp) {
9589 CallArgs args = CallArgsFromVp(argc, vp);
9590
9591 size_t length = JS::GetPCCountScriptCount(cx);
9592
9593 args.rval().setNumber(double(length));
9594 return true;
9595 }
9596
9597 static bool PCCountProfiling_ScriptSummary(JSContext* cx, unsigned argc,
9598 Value* vp) {
9599 CallArgs args = CallArgsFromVp(argc, vp);
9600 if (!args.requireAtLeast(cx, "summary", 1)) {
9601 return false;
9602 }
9603
9604 uint32_t index;
9605 if (!JS::ToUint32(cx, args[0], &index)) {
9606 return false;
9607 }
9608
9609 JSString* str = JS::GetPCCountScriptSummary(cx, index);
9610 if (!str) {
9611 return false;
9612 }
9613
9614 args.rval().setString(str);
9615 return true;
9616 }
9617
9618 static bool PCCountProfiling_ScriptContents(JSContext* cx, unsigned argc,
9619 Value* vp) {
9620 CallArgs args = CallArgsFromVp(argc, vp);
9621 if (!args.requireAtLeast(cx, "contents", 1)) {
9622 return false;
9623 }
9624
9625 uint32_t index;
9626 if (!JS::ToUint32(cx, args[0], &index)) {
9627 return false;
9628 }
9629
9630 JSString* str = JS::GetPCCountScriptContents(cx, index);
9631 if (!str) {
9632 return false;
9633 }
9634
9635 args.rval().setString(str);
9636 return true;
9637 }
9638
9639 static bool NukeCCW(JSContext* cx, unsigned argc, Value* vp) {
9640 CallArgs args = CallArgsFromVp(argc, vp);
9641
9642 if (args.length() != 1 || !args[0].isObject() ||
9643 !IsCrossCompartmentWrapper(&args[0].toObject())) {
9644 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARGS,
9645 "nukeCCW");
9646 return false;
9647 }
9648
9649 NukeCrossCompartmentWrapper(cx, &args[0].toObject());
9650 args.rval().setUndefined();
9651 return true;
9652 }
9653
9654 static bool IsCCW(JSContext* cx, unsigned argc, Value* vp) {
9655 CallArgs args = CallArgsFromVp(argc, vp);
9656
9657 if (args.length() != 1 || !args[0].isObject()) {
9658 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARGS,
9659 "IsCCW");
9660 return false;
9661 }
9662
9663 args.rval().setBoolean(IsCrossCompartmentWrapper(&args[0].toObject()));
9664 return true;
9665 }
9666
9667 static bool FdLibM_Pow(JSContext* cx, unsigned argc, Value* vp) {
9668 CallArgs args = CallArgsFromVp(argc, vp);
9669
9670 double x;
9671 if (!JS::ToNumber(cx, args.get(0), &x)) {
9672 return false;
9673 }
9674
9675 double y;
9676 if (!JS::ToNumber(cx, args.get(1), &y)) {
9677 return false;
9678 }
9679
9680 // Because C99 and ECMA specify different behavior for pow(), we need to wrap
9681 // the fdlibm call to make it ECMA compliant.
9682 if (!std::isfinite(y) && (x == 1.0 || x == -1.0)) {
9683 args.rval().setNaN();
9684 } else {
9685 args.rval().setDouble(fdlibm_pow(x, y));
9686 }
9687 return true;
9688 }
9689
9690 static bool HadOutOfMemory(JSContext* cx, unsigned argc, Value* vp) {
9691 CallArgs args = CallArgsFromVp(argc, vp);
9692 args.rval().setBoolean(cx->runtime()->hadOutOfMemory);
9693 return true;
9694 }
9695
9696 static bool WaitForDone(JSContext* cx, unsigned argc, Value* vp) {
9697 CallArgs args = CallArgsFromVp(argc, vp);
9698 if (args.length() != 1) {
9699 JS_ReportErrorASCII(cx, "The function takes exactly one argument.");
9700 return false;
9701 }
9702
9703 if (!args[0].isObject()) {
9704 JS_ReportErrorASCII(cx, "The first argument should be an object.");
9705 return false;
9706 }
9707
9708 RootedObject obj(cx, &args[0].toObject());
9709 RootedValue val(cx);
9710 if (!JS_GetProperty(cx, obj, "done", &val)) {
9711 return false;
9712 }
9713
9714 args.rval().setUndefined();
9715
9716 while (!val.isBoolean() || !val.toBoolean()) {
9717 js::RunJobs(cx);
9718 if (!JS_GetProperty(cx, obj, "done", &val)) {
9719 return false;
9720 }
9721 }
9722 return true;
9723 }
9724
9725 // clang-format off
9726 static const JSFunctionSpecWithHelp TestingFunctions[] = {
9727 JS_FN_HELP("gc", ::GC, 0, 0,
9728 "gc([obj] | 'zone' [, ('shrinking' | 'last-ditch') ])",
9729 " Run the garbage collector.\n"
9730 " The first parameter describes which zones to collect: if an object is\n"
9731 " given, GC only its zone. If 'zone' is given, GC any zones that were\n"
9732 " scheduled via schedulegc.\n"
9733 " The second parameter is optional and may be 'shrinking' to perform a\n"
9734 " shrinking GC or 'last-ditch' for a shrinking, last-ditch GC."),
9735
9736 JS_FN_HELP("minorgc", ::MinorGC, 0, 0,
9737 "minorgc([aboutToOverflow])",
9738 " Run a minor collector on the Nursery. When aboutToOverflow is true, marks\n"
9739 " the store buffer as about-to-overflow before collecting."),
9740
9741 JS_FN_HELP("maybegc", ::MaybeGC, 0, 0,
9742 "maybegc()",
9743 " Hint to the engine that now is an ok time to run the garbage collector.\n"),
9744
9745 JS_FN_HELP("gcparam", GCParameter, 2, 0,
9746 "gcparam(name [, value])",
9747 " Wrapper for JS_[GS]etGCParameter. The name is one of:" GC_PARAMETER_ARGS_LIST),
9748
9749 JS_FN_HELP("finishBackgroundFree", FinishBackgroundFree, 0, 0,
9750 "finishBackgroundFree()",
9751 " Wait for the GC's background free task to finish.\n"),
9752
9753 JS_FN_HELP("hasDisassembler", HasDisassembler, 0, 0,
9754 "hasDisassembler()",
9755 " Return true if a disassembler is present (for disnative and wasmDis)."),
9756
9757 JS_FN_HELP("disnative", DisassembleNative, 2, 0,
9758 "disnative(fun,[path])",
9759 " Disassemble a function into its native code. Optionally write the native code bytes to a file on disk.\n"),
9760
9761 JS_FN_HELP("disblic", DisassembleBaselineICs, 1, 0,
9762 "disblic(fun)",
9763 " Disassemble the baseline ICs for a function into native code.\n"),
9764
9765 JS_FN_HELP("relazifyFunctions", RelazifyFunctions, 0, 0,
9766 "relazifyFunctions(...)",
9767 " Perform a GC and allow relazification of functions. Accepts the same\n"
9768 " arguments as gc()."),
9769
9770 JS_FN_HELP("getBuildConfiguration", GetBuildConfiguration, 1, 0,
9771 "getBuildConfiguration([option])",
9772 " Query the options SpiderMonkey was built with, or return an object\n"
9773 " with the options if no argument is given."),
9774
9775 JS_FN_HELP("getRealmConfiguration", GetRealmConfiguration, 1, 0,
9776 "getRealmConfiguration([option])",
9777 " Query the runtime options SpiderMonkey is running with, or return an\n."
9778 " object with the options if no argument is given."),
9779
9780 JS_FN_HELP("isLcovEnabled", ::IsLCovEnabled, 0, 0,
9781 "isLcovEnabled()",
9782 " Return true if JS LCov support is enabled."),
9783
9784 JS_FN_HELP("trialInline", TrialInline, 0, 0,
9785 "trialInline()",
9786 " Perform trial-inlining for the caller's frame if it's a BaselineFrame."),
9787
9788 JS_FN_HELP("hasChild", HasChild, 0, 0,
9789 "hasChild(parent, child)",
9790 " Return true if |child| is a child of |parent|, as determined by a call to\n"
9791 " TraceChildren"),
9792
9793 JS_FN_HELP("setSavedStacksRNGState", SetSavedStacksRNGState, 1, 0,
9794 "setSavedStacksRNGState(seed)",
9795 " Set this compartment's SavedStacks' RNG state.\n"),
9796
9797 JS_FN_HELP("getSavedFrameCount", GetSavedFrameCount, 0, 0,
9798 "getSavedFrameCount()",
9799 " Return the number of SavedFrame instances stored in this compartment's\n"
9800 " SavedStacks cache."),
9801
9802 JS_FN_HELP("clearSavedFrames", ClearSavedFrames, 0, 0,
9803 "clearSavedFrames()",
9804 " Empty the current compartment's cache of SavedFrame objects, so that\n"
9805 " subsequent stack captures allocate fresh objects to represent frames.\n"
9806 " Clear the current stack's LiveSavedFrameCaches."),
9807
9808 JS_FN_HELP("saveStack", SaveStack, 0, 0,
9809 "saveStack([maxDepth [, compartment]])",
9810 " Capture a stack. If 'maxDepth' is given, capture at most 'maxDepth' number\n"
9811 " of frames. If 'compartment' is given, allocate the js::SavedFrame instances\n"
9812 " with the given object's compartment."),
9813
9814 JS_FN_HELP("captureFirstSubsumedFrame", CaptureFirstSubsumedFrame, 1, 0,
9815 "saveStack(object [, shouldIgnoreSelfHosted = true]])",
9816 " Capture a stack back to the first frame whose principals are subsumed by the\n"
9817 " object's compartment's principals. If 'shouldIgnoreSelfHosted' is given,\n"
9818 " control whether self-hosted frames are considered when checking principals."),
9819
9820 JS_FN_HELP("callFunctionFromNativeFrame", CallFunctionFromNativeFrame, 1, 0,
9821 "callFunctionFromNativeFrame(function)",
9822 " Call 'function' with a (C++-)native frame on stack.\n"
9823 " Required for testing that SaveStack properly handles native frames."),
9824
9825 JS_FN_HELP("callFunctionWithAsyncStack", CallFunctionWithAsyncStack, 0, 0,
9826 "callFunctionWithAsyncStack(function, stack, asyncCause)",
9827 " Call 'function', using the provided stack as the async stack responsible\n"
9828 " for the call, and propagate its return value or the exception it throws.\n"
9829 " The function is called with no arguments, and 'this' is 'undefined'. The\n"
9830 " specified |asyncCause| is attached to the provided stack frame."),
9831
9832 JS_FN_HELP("enableTrackAllocations", EnableTrackAllocations, 0, 0,
9833 "enableTrackAllocations()",
9834 " Start capturing the JS stack at every allocation. Note that this sets an\n"
9835 " object metadata callback that will override any other object metadata\n"
9836 " callback that may be set."),
9837
9838 JS_FN_HELP("disableTrackAllocations", DisableTrackAllocations, 0, 0,
9839 "disableTrackAllocations()",
9840 " Stop capturing the JS stack at every allocation."),
9841
9842 JS_FN_HELP("setTestFilenameValidationCallback", SetTestFilenameValidationCallback, 0, 0,
9843 "setTestFilenameValidationCallback()",
9844 " Set the filename validation callback to a callback that accepts only\n"
9845 " filenames starting with 'safe' or (only in system realms) 'system'."),
9846
9847 JS_FN_HELP("newObjectWithAddPropertyHook", NewObjectWithAddPropertyHook, 0, 0,
9848 "newObjectWithAddPropertyHook()",
9849 " Returns a new object with an addProperty JSClass hook. This hook\n"
9850 " increments the value of the _propertiesAdded data property on the object\n"
9851 " when a new property is added."),
9852
9853 JS_FN_HELP("newObjectWithCallHook", NewObjectWithCallHook, 0, 0,
9854 "newObjectWithCallHook()",
9855 " Returns a new object with call/construct JSClass hooks. These hooks return\n"
9856 " a new object that contains the Values supplied by the caller."),
9857
9858 JS_FN_HELP("newObjectWithManyReservedSlots", NewObjectWithManyReservedSlots, 0, 0,
9859 "newObjectWithManyReservedSlots()",
9860 " Returns a new object with many reserved slots. The slots are initialized to int32\n"
9861 " values. checkObjectWithManyReservedSlots can be used to check the slots still\n"
9862 " hold these values."),
9863
9864 JS_FN_HELP("checkObjectWithManyReservedSlots", CheckObjectWithManyReservedSlots, 1, 0,
9865 "checkObjectWithManyReservedSlots(obj)",
9866 " Checks the reserved slots set by newObjectWithManyReservedSlots still hold the expected\n"
9867 " values."),
9868
9869 JS_FN_HELP("getWatchtowerLog", GetWatchtowerLog, 0, 0,
9870 "getWatchtowerLog()",
9871 " Returns the Watchtower log recording object changes for objects for which\n"
9872 " addWatchtowerTarget was called. The internal log is cleared. The return\n"
9873 " value is an array of plain objects with the following properties:\n"
9874 " - kind: a string describing the kind of mutation, for example \"add-prop\"\n"
9875 " - object: the object being mutated\n"
9876 " - extra: an extra value, for example the name of the property being added"),
9877
9878 JS_FN_HELP("addWatchtowerTarget", AddWatchtowerTarget, 1, 0,
9879 "addWatchtowerTarget(object)",
9880 " Invoke the watchtower callback for changes to this object."),
9881
9882 JS_FN_HELP("newString", NewString, 2, 0,
9883 "newString(str[, options])",
9884 " Copies str's chars and returns a new string. Valid options:\n"
9885 " \n"
9886 " - tenured: allocate directly into the tenured heap.\n"
9887 " \n"
9888 " - twoByte: create a \"two byte\" string, not a latin1 string, regardless of the\n"
9889 " input string's characters. Latin1 will be used by default if possible\n"
9890 " (again regardless of the input string.)\n"
9891 " \n"
9892 " - newStringBuffer: create a new string that uses a refcounted StringBuffer for\n"
9893 " the characters.\n"
9894 " \n"
9895 " - shareStringBuffer: create a new string that shares str's StringBuffer.\n"
9896 " \n"
9897 " - external: create an external string. External strings are always twoByte and\n"
9898 " tenured.\n"
9899 " \n"
9900 " - maybeExternal: create an external string, unless the data fits within an\n"
9901 " inline string. Inline strings may be nursery-allocated.\n"
9902 " \n"
9903 " - capacity: create an extensible string with the given capacity"),
9904
9905 JS_FN_HELP("newDependentString", NewDependentString, 2, 0,
9906 "newDependentString(str, indexStart[, indexEnd] [, options])",
9907 " Essentially the same as str.substring() but insist on\n"
9908 " creating a dependent string and failing if not. Also has options to\n"
9909 " control the heap the string object is allocated into:\n"
9910 " \n"
9911 " - tenured: if true, allocate in the tenured heap or throw. If false,\n"
9912 " allocate in the nursery or throw.\n"
9913 " - suppress-contraction: prevent the optimization of using a base's base rather\n"
9914 " than creating a chain of dependent string bases."),
9915
9916 JS_FN_HELP("ensureLinearString", EnsureLinearString, 1, 0,
9917 "ensureLinearString(str)",
9918 " Ensures str is a linear (non-rope) string and returns it."),
9919
9920 JS_FN_HELP("representativeStringArray", RepresentativeStringArray, 0, 0,
9921 "representativeStringArray()",
9922 " Returns an array of strings that represent the various internal string\n"
9923 " types and character encodings."),
9924
9925 #if defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
9926
9927 JS_FN_HELP("oomThreadTypes", OOMThreadTypes, 0, 0,
9928 "oomThreadTypes()",
9929 " Get the number of thread types that can be used as an argument for\n"
9930 " oomAfterAllocations() and oomAtAllocation()."),
9931
9932 JS_FN_HELP("oomAfterAllocations", OOMAfterAllocations, 2, 0,
9933 "oomAfterAllocations(count [,threadType])",
9934 " After 'count' js_malloc memory allocations, fail every following allocation\n"
9935 " (return nullptr). The optional thread type limits the effect to the\n"
9936 " specified type of helper thread."),
9937
9938 JS_FN_HELP("oomAtAllocation", OOMAtAllocation, 2, 0,
9939 "oomAtAllocation(count [,threadType])",
9940 " After 'count' js_malloc memory allocations, fail the next allocation\n"
9941 " (return nullptr). The optional thread type limits the effect to the\n"
9942 " specified type of helper thread."),
9943
9944 JS_FN_HELP("resetOOMFailure", ResetOOMFailure, 0, 0,
9945 "resetOOMFailure()",
9946 " Remove the allocation failure scheduled by either oomAfterAllocations() or\n"
9947 " oomAtAllocation() and return whether any allocation had been caused to fail."),
9948
9949 JS_FN_HELP("oomTest", OOMTest, 0, 0,
9950 "oomTest(function, [expectExceptionOnFailure = true | options])",
9951 " Test that the passed function behaves correctly under OOM conditions by\n"
9952 " repeatedly executing it and simulating allocation failure at successive\n"
9953 " allocations until the function completes without seeing a failure.\n"
9954 " By default this tests that an exception is raised if execution fails, but\n"
9955 " this can be disabled by passing false as the optional second parameter.\n"
9956 " This is also disabled when --fuzzing-safe is specified.\n"
9957 " Alternatively an object can be passed to set the following options:\n"
9958 " expectExceptionOnFailure: bool - as described above.\n"
9959 " keepFailing: bool - continue to fail after first simulated failure.\n"
9960 "\n"
9961 " WARNING: By design, oomTest assumes the test-function follows the same\n"
9962 " code path each time it is called, right up to the point where OOM occurs.\n"
9963 " If on iteration 70 it finishes and caches a unit of work that saves 65\n"
9964 " allocations the next time we run, then the subsequent 65 allocation\n"
9965 " points will go untested.\n"
9966 "\n"
9967 " Things in this category include lazy parsing and baseline compilation,\n"
9968 " so it is very easy to accidentally write an oomTest that only tests one\n"
9969 " or the other of those, and not the functionality you meant to test!\n"
9970 " To avoid lazy parsing, call the test function once first before passing\n"
9971 " it to oomTest. The jits can be disabled via the test harness.\n"),
9972
9973 JS_FN_HELP("stackTest", StackTest, 0, 0,
9974 "stackTest(function, [expectExceptionOnFailure = true])",
9975 " This function behaves exactly like oomTest with the difference that\n"
9976 " instead of simulating regular OOM conditions, it simulates the engine\n"
9977 " running out of stack space (failing recursion check).\n"
9978 "\n"
9979 " See the WARNING in help('oomTest').\n"),
9980
9981 JS_FN_HELP("interruptTest", InterruptTest, 0, 0,
9982 "interruptTest(function)",
9983 " This function simulates interrupts similar to how oomTest simulates OOM conditions."
9984 "\n"
9985 " See the WARNING in help('oomTest').\n"),
9986
9987 #endif // defined(DEBUG) || defined(JS_OOM_BREAKPOINT)
9988
9989 JS_FN_HELP("newRope", NewRope, 3, 0,
9990 "newRope(left, right[, options])",
9991 " Creates a rope with the given left/right strings.\n"
9992 " Available options:\n"
9993 " nursery: bool - force the string to be created in/out of the nursery, if possible.\n"),
9994
9995 JS_FN_HELP("isRope", IsRope, 1, 0,
9996 "isRope(str)",
9997 " Returns true if the parameter is a rope"),
9998
9999 JS_FN_HELP("settlePromiseNow", SettlePromiseNow, 1, 0,
10000 "settlePromiseNow(promise)",
10001 " 'Settle' a 'promise' immediately. This just marks the promise as resolved\n"
10002 " with a value of `undefined` and causes the firing of any onPromiseSettled\n"
10003 " hooks set on Debugger instances that are observing the given promise's\n"
10004 " global as a debuggee."),
10005 JS_FN_HELP("getWaitForAllPromise", GetWaitForAllPromise, 1, 0,
10006 "getWaitForAllPromise(densePromisesArray)",
10007 " Calls the 'GetWaitForAllPromise' JSAPI function and returns the result\n"
10008 " Promise."),
10009 JS_FN_HELP("resolvePromise", ResolvePromise, 2, 0,
10010 "resolvePromise(promise, resolution)",
10011 " Resolve a Promise by calling the JSAPI function JS::ResolvePromise."),
10012 JS_FN_HELP("rejectPromise", RejectPromise, 2, 0,
10013 "rejectPromise(promise, reason)",
10014 " Reject a Promise by calling the JSAPI function JS::RejectPromise."),
10015
10016 JS_FN_HELP("makeFinalizeObserver", MakeFinalizeObserver, 0, 0,
10017 "makeFinalizeObserver()",
10018 " Get a special object whose finalization increases the counter returned\n"
10019 " by the finalizeCount function."),
10020
10021 JS_FN_HELP("finalizeCount", FinalizeCount, 0, 0,
10022 "finalizeCount()",
10023 " Return the current value of the finalization counter that is incremented\n"
10024 " each time an object returned by the makeFinalizeObserver is finalized."),
10025
10026 JS_FN_HELP("resetFinalizeCount", ResetFinalizeCount, 0, 0,
10027 "resetFinalizeCount()",
10028 " Reset the value returned by finalizeCount()."),
10029
10030 JS_FN_HELP("gcPreserveCode", GCPreserveCode, 0, 0,
10031 "gcPreserveCode()",
10032 " Preserve JIT code during garbage collections."),
10033
10034 #ifdef JS_GC_ZEAL
10035 JS_FN_HELP("gczeal", GCZeal, 2, 0,
10036 "gczeal([mode, [frequency]])",
10037 gc::ZealModeHelpText),
10038
10039 JS_FN_HELP("unsetgczeal", UnsetGCZeal, 2, 0,
10040 "unsetgczeal(mode)",
10041 " Turn off the mode or modes given that were set with gczeal() or JS_GC_ZEAL\n"
10042 " and don't finish any ongoing collection that may be happening."),
10043
10044 JS_FN_HELP("schedulegc", ScheduleGC, 1, 0,
10045 "schedulegc([num])",
10046 " If num is given, schedule a GC after num allocations.\n"
10047 " Returns the number of allocations before the next trigger."),
10048
10049 JS_FN_HELP("selectforgc", SelectForGC, 0, 0,
10050 "selectforgc(obj1, obj2, ...)",
10051 " Schedule the given objects to be marked in the next GC slice."),
10052
10053 JS_FN_HELP("verifyprebarriers", VerifyPreBarriers, 0, 0,
10054 "verifyprebarriers()",
10055 " Start or end a run of the pre-write barrier verifier."),
10056
10057 JS_FN_HELP("verifypostbarriers", VerifyPostBarriers, 0, 0,
10058 "verifypostbarriers()",
10059 " Enable or disable the post-write barrier verifier."),
10060
10061 JS_FN_HELP("currentgc", CurrentGC, 0, 0,
10062 "currentgc()",
10063 " Report various information about the currently running incremental GC,\n"
10064 " if one is running."),
10065
10066 JS_FN_HELP("deterministicgc", DeterministicGC, 1, 0,
10067 "deterministicgc(true|false)",
10068 " If true, only allow determinstic GCs to run."),
10069
10070 JS_FN_HELP("dumpGCArenaInfo", DumpGCArenaInfo, 0, 0,
10071 "dumpGCArenaInfo()",
10072 " Prints information about the different GC things and how they are arranged\n"
10073 " in arenas.\n"),
10074
10075 JS_FN_HELP("setMarkStackLimit", SetMarkStackLimit, 1, 0,
10076 "markStackLimit(limit)",
10077 " Sets a limit on the number of words used for the mark stack. Used to test OOM"
10078 " handling during marking.\n"),
10079
10080 #endif
10081
10082 JS_FN_HELP("gcstate", GCState, 0, 0,
10083 "gcstate([obj])",
10084 " Report the global GC state, or the GC state for the zone containing |obj|."),
10085
10086 JS_FN_HELP("schedulezone", ScheduleZoneForGC, 1, 0,
10087 "schedulezone([obj | string])",
10088 " If obj is given, schedule a GC of obj's zone.\n"
10089 " If string is given, schedule a GC of the string's zone if possible."),
10090
10091 JS_FN_HELP("startgc", StartGC, 1, 0,
10092 "startgc([n [, 'shrinking']])",
10093 " Start an incremental GC and run a slice that processes about n objects.\n"
10094 " If 'shrinking' is passesd as the optional second argument, perform a\n"
10095 " shrinking GC rather than a normal GC. If no zones have been selected with\n"
10096 " schedulezone(), a full GC will be performed."),
10097
10098 JS_FN_HELP("finishgc", FinishGC, 0, 0,
10099 "finishgc()",
10100 " Finish an in-progress incremental GC, if none is running then do nothing."),
10101
10102 JS_FN_HELP("gcslice", GCSlice, 1, 0,
10103 "gcslice([n [, options]])",
10104 " Start or continue an an incremental GC, running a slice that processes\n"
10105 " about n objects. Takes an optional options object, which may contain the\n"
10106 " following properties:\n"
10107 " dontStart: do not start a new incremental GC if one is not already\n"
10108 " running"),
10109
10110 JS_FN_HELP("abortgc", AbortGC, 1, 0,
10111 "abortgc()",
10112 " Abort the current incremental GC."),
10113
10114 JS_FN_HELP("setMallocMaxDirtyPageModifier", SetMallocMaxDirtyPageModifier, 1, 0,
10115 "setMallocMaxDirtyPageModifier(value)",
10116 " Change the maximum size of jemalloc's page cache. The value should be between\n"
10117 " -5 and 16 (inclusive). See moz_set_max_dirty_page_modifier.\n"),
10118
10119 JS_FN_HELP("fullcompartmentchecks", FullCompartmentChecks, 1, 0,
10120 "fullcompartmentchecks(true|false)",
10121 " If true, check for compartment mismatches before every GC."),
10122
10123 JS_FN_HELP("nondeterministicGetWeakMapKeys", NondeterministicGetWeakMapKeys, 1, 0,
10124 "nondeterministicGetWeakMapKeys(weakmap)",
10125 " Return an array of the keys in the given WeakMap."),
10126
10127 JS_FN_HELP("internalConst", InternalConst, 1, 0,
10128 "internalConst(name)",
10129 " Query an internal constant for the engine. See InternalConst source for\n"
10130 " the list of constant names."),
10131
10132 JS_FN_HELP("isProxy", IsProxy, 1, 0,
10133 "isProxy(obj)",
10134 " If true, obj is a proxy of some sort"),
10135
10136 JS_FN_HELP("dumpHeap", DumpHeap, 1, 0,
10137 "dumpHeap([filename])",
10138 " Dump reachable and unreachable objects to the named file, or to stdout. Objects\n"
10139 " in the nursery are ignored, so if you wish to include them, consider calling\n"
10140 " minorgc() first."),
10141
10142 JS_FN_HELP("terminate", Terminate, 0, 0,
10143 "terminate()",
10144 " Terminate JavaScript execution, as if we had run out of\n"
10145 " memory or been terminated by the slow script dialog."),
10146
10147 JS_FN_HELP("readGeckoProfilingStack", ReadGeckoProfilingStack, 0, 0,
10148 "readGeckoProfilingStack()",
10149 " Reads the JIT/Wasm stack using ProfilingFrameIterator. Skips non-JIT/Wasm frames."),
10150
10151 JS_FN_HELP("readGeckoInterpProfilingStack", ReadGeckoInterpProfilingStack, 0, 0,
10152 "readGeckoInterpProfilingStack()",
10153 " Reads the C++ interpreter profiling stack. Skips JIT/Wasm frames."),
10154
10155 JS_FN_HELP("enableOsiPointRegisterChecks", EnableOsiPointRegisterChecks, 0, 0,
10156 "enableOsiPointRegisterChecks()",
10157 " Emit extra code to verify live regs at the start of a VM call are not\n"
10158 " modified before its OsiPoint."),
10159
10160 JS_FN_HELP("displayName", DisplayName, 1, 0,
10161 "displayName(fn)",
10162 " Gets the display name for a function, which can possibly be a guessed or\n"
10163 " inferred name based on where the function was defined. This can be\n"
10164 " different from the 'name' property on the function."),
10165
10166 JS_FN_HELP("isAsmJSCompilationAvailable", IsAsmJSCompilationAvailable, 0, 0,
10167 "isAsmJSCompilationAvailable",
10168 " Returns whether asm.js compilation is currently available or whether it is disabled\n"
10169 " (e.g., by the debugger)."),
10170
10171 JS_FN_HELP("getJitCompilerOptions", GetJitCompilerOptions, 0, 0,
10172 "getJitCompilerOptions()",
10173 " Return an object describing some of the JIT compiler options.\n"),
10174
10175 JS_FN_HELP("isAsmJSModule", IsAsmJSModule, 1, 0,
10176 "isAsmJSModule(fn)",
10177 " Returns whether the given value is a function containing \"use asm\" that has been\n"
10178 " validated according to the asm.js spec."),
10179
10180 JS_FN_HELP("isAsmJSFunction", IsAsmJSFunction, 1, 0,
10181 "isAsmJSFunction(fn)",
10182 " Returns whether the given value is a nested function in an asm.js module that has been\n"
10183 " both compile- and link-time validated."),
10184
10185 JS_FN_HELP("isAvxPresent", IsAvxPresent, 0, 0,
10186 "isAvxPresent([minVersion])",
10187 " Returns whether AVX is present and enabled. If minVersion specified,\n"
10188 " use 1 - to check if AVX is enabled (default), 2 - if AVX2 is enabled."),
10189
10190 JS_FN_HELP("wasmIsSupported", WasmIsSupported, 0, 0,
10191 "wasmIsSupported()",
10192 " Returns a boolean indicating whether WebAssembly is supported on the current device."),
10193
10194 JS_FN_HELP("wasmIsSupportedByHardware", WasmIsSupportedByHardware, 0, 0,
10195 "wasmIsSupportedByHardware()",
10196 " Returns a boolean indicating whether WebAssembly is supported on the current hardware (regardless of whether we've enabled support)."),
10197
10198 JS_FN_HELP("wasmDebuggingEnabled", WasmDebuggingEnabled, 0, 0,
10199 "wasmDebuggingEnabled()",
10200 " Returns a boolean indicating whether WebAssembly debugging is supported on the current device;\n"
10201 " returns false also if WebAssembly is not supported"),
10202
10203 JS_FN_HELP("wasmStreamingEnabled", WasmStreamingEnabled, 0, 0,
10204 "wasmStreamingEnabled()",
10205 " Returns a boolean indicating whether WebAssembly caching is supported by the runtime."),
10206
10207 JS_FN_HELP("wasmCachingEnabled", WasmCachingEnabled, 0, 0,
10208 "wasmCachingEnabled()",
10209 " Returns a boolean indicating whether WebAssembly caching is supported by the runtime."),
10210
10211 JS_FN_HELP("wasmHugeMemorySupported", WasmHugeMemorySupported, 0, 0,
10212 "wasmHugeMemorySupported()",
10213 " Returns a boolean indicating whether WebAssembly supports using a large"
10214 " virtual memory reservation in order to elide bounds checks on this platform."),
10215
10216 JS_FN_HELP("wasmMaxMemoryPages", WasmMaxMemoryPages, 1, 0,
10217 "wasmMaxMemoryPages(addressType)",
10218 " Returns an int with the maximum number of pages that can be allocated to a memory."
10219 " This is an implementation artifact that does depend on the address type, the hardware,"
10220 " the operating system, the build configuration, and flags. The result is constant for"
10221 " a given combination of those; there is no guarantee that that size allocation will"
10222 " always succeed, only that it can succeed in principle. The addressType is a string,"
10223 " 'i32' or 'i64'."),
10224
10225 #define WASM_FEATURE(NAME, ...) \
10226 JS_FN_HELP("wasm" #NAME "Enabled", Wasm##NAME##Enabled, 0, 0, \
10227 "wasm" #NAME "Enabled()", \
10228 " Returns a boolean indicating whether the WebAssembly " #NAME " proposal is enabled."),
10229 JS_FOR_WASM_FEATURES(WASM_FEATURE)
10230 #undef WASM_FEATURE
10231
10232 JS_FN_HELP("wasmThreadsEnabled", WasmThreadsEnabled, 0, 0,
10233 "wasmThreadsEnabled()",
10234 " Returns a boolean indicating whether the WebAssembly threads proposal is\n"
10235 " supported on the current device."),
10236
10237 JS_FN_HELP("wasmSimdEnabled", WasmSimdEnabled, 0, 0,
10238 "wasmSimdEnabled()",
10239 " Returns a boolean indicating whether WebAssembly SIMD proposal is\n"
10240 " supported by the current device."),
10241
10242 #if defined(ENABLE_WASM_SIMD) && defined(DEBUG)
10243 JS_FN_HELP("wasmSimdAnalysis", WasmSimdAnalysis, 1, 0,
10244 "wasmSimdAnalysis(...)",
10245 " Unstable API for white-box testing.\n"),
10246 #endif
10247
10248 JS_FN_HELP("wasmGlobalFromArrayBuffer", WasmGlobalFromArrayBuffer, 2, 0,
10249 "wasmGlobalFromArrayBuffer(type, arrayBuffer)",
10250 " Create a WebAssembly.Global object from a provided ArrayBuffer. The type\n"
10251 " must be POD (i32, i64, f32, f64, v128). The buffer must be the same\n"
10252 " size as the type in bytes.\n"),
10253 JS_FN_HELP("wasmGlobalExtractLane", WasmGlobalExtractLane, 3, 0,
10254 "wasmGlobalExtractLane(global, laneInterp, laneIndex)",
10255 " Extract a lane from a WebAssembly.Global object that contains a v128 value\n"
10256 " and return it as a new WebAssembly.Global object of the appropriate type.\n"
10257 " The supported laneInterp values are i32x4, i64x2, f32x4, and\n"
10258 " f64x2.\n"),
10259 JS_FN_HELP("wasmGlobalsEqual", WasmGlobalsEqual, 2, 0,
10260 "wasmGlobalsEqual(globalA, globalB)",
10261 " Compares two WebAssembly.Global objects for if their types and values are\n"
10262 " equal. Mutability is not compared. Floating point values are compared for\n"
10263 " bitwise equality, not IEEE 754 equality.\n"),
10264 JS_FN_HELP("wasmGlobalIsNaN", WasmGlobalIsNaN, 2, 0,
10265 "wasmGlobalIsNaN(global, flavor)",
10266 " Compares a floating point WebAssembly.Global object for if its value is a\n"
10267 " specific NaN flavor. Valid flavors are `arithmetic_nan` and `canonical_nan`.\n"),
10268 JS_FN_HELP("wasmGlobalToString", WasmGlobalToString, 1, 0,
10269 "wasmGlobalToString(global)",
10270 " Returns a debug representation of the contents of a WebAssembly.Global\n"
10271 " object.\n"),
10272 JS_FN_HELP("wasmLosslessInvoke", WasmLosslessInvoke, 1, 0,
10273 "wasmLosslessInvoke(wasmFunc, args...)",
10274 " Invokes the provided WebAssembly function using a modified conversion\n"
10275 " function that allows providing a param as a WebAssembly.Global and\n"
10276 " returning a result as a WebAssembly.Global.\n"),
10277
10278 JS_FN_HELP("wasmCompilersPresent", WasmCompilersPresent, 0, 0,
10279 "wasmCompilersPresent()",
10280 " Returns a string indicating the present wasm compilers: a comma-separated list\n"
10281 " of 'baseline', 'ion'. A compiler is present in the executable if it is compiled\n"
10282 " in and can generate code for the current architecture."),
10283
10284 JS_FN_HELP("wasmCompileMode", WasmCompileMode, 0, 0,
10285 "wasmCompileMode()",
10286 " Returns a string indicating the available wasm compilers: 'baseline', 'ion',\n"
10287 " 'baseline+ion', or 'none'. A compiler is available if it is present in the\n"
10288 " executable and not disabled by switches or runtime conditions. At most one\n"
10289 " baseline and one optimizing compiler can be available."),
10290
10291 JS_FN_HELP("wasmLazyTieringEnabled", WasmLazyTieringEnabled, 0, 0,
10292 "wasmLazyTieringEnabled()",
10293 " Returns a boolean indicating whether compilation will be performed\n"
10294 " using lazy tiering."),
10295
10296 JS_FN_HELP("wasmBaselineDisabledByFeatures", WasmBaselineDisabledByFeatures, 0, 0,
10297 "wasmBaselineDisabledByFeatures()",
10298 " If some feature is enabled at compile-time or run-time that prevents baseline\n"
10299 " from being used then this returns a truthy string describing the features that\n."
10300 " are disabling it. Otherwise it returns false."),
10301
10302 JS_FN_HELP("wasmIonDisabledByFeatures", WasmIonDisabledByFeatures, 0, 0,
10303 "wasmIonDisabledByFeatures()",
10304 " If some feature is enabled at compile-time or run-time that prevents Ion\n"
10305 " from being used then this returns a truthy string describing the features that\n."
10306 " are disabling it. Otherwise it returns false."),
10307
10308 JS_FN_HELP("wasmHasTier2CompilationCompleted", WasmHasTier2CompilationCompleted, 1, 0,
10309 "wasmHasTier2CompilationCompleted(module)",
10310 " Returns a boolean indicating whether a given module has finished compiled code for tier2. \n"
10311 "This will return true early if compilation isn't two-tiered. "),
10312
10313 JS_FN_HELP("wasmLoadedFromCache", WasmLoadedFromCache, 1, 0,
10314 "wasmLoadedFromCache(module)",
10315 " Returns a boolean indicating whether a given module was deserialized directly from a\n"
10316 " cache (as opposed to compiled from bytecode)."),
10317
10318 JS_FN_HELP("wasmBuiltinI8VecMul", WasmBuiltinI8VecMul, 0, 0,
10319 "wasmBuiltinI8VecMul()",
10320 " Returns a module that implements an i8 vector pairwise multiplication intrinsic."),
10321
10322 JS_FN_HELP("wasmGcReadField", WasmGcReadField, 2, 0,
10323 "wasmGcReadField(obj, index)",
10324 " Gets a field of a WebAssembly GC struct or array."),
10325
10326 JS_FN_HELP("wasmGcArrayLength", WasmGcArrayLength, 1, 0,
10327 "wasmGcArrayLength(arr)",
10328 " Gets the length of a WebAssembly GC array."),
10329
10330 #ifdef ENABLE_WASM_BRANCH_HINTING
10331 JS_FN_HELP("wasmParsedBranchHints", WasmParsedBranchHints, 1, 0,
10332 "wasmParsedBranchHints(module)",
10333 " Returns a boolean indicating whether a given module has successfully parsed a\n"
10334 " custom branch hinting section."),
10335
10336 #endif // ENABLE_WASM_BRANCH_HINTING
10337
10338 JS_FN_HELP("largeArrayBufferSupported", LargeArrayBufferSupported, 0, 0,
10339 "largeArrayBufferSupported()",
10340 " Returns true if array buffers larger than 2GB can be allocated."),
10341
10342 JS_FN_HELP("isLazyFunction", IsLazyFunction, 1, 0,
10343 "isLazyFunction(fun)",
10344 " True if fun is a lazy JSFunction."),
10345
10346 JS_FN_HELP("isRelazifiableFunction", IsRelazifiableFunction, 1, 0,
10347 "isRelazifiableFunction(fun)",
10348 " True if fun is a JSFunction with a relazifiable JSScript."),
10349
10350 JS_FN_HELP("hasSameBytecodeData", HasSameBytecodeData, 2, 0,
10351 "hasSameBytecodeData(fun1, fun2)",
10352 " True if fun1 and fun2 share the same copy of bytecode data. This will\n"
10353 " delazify the function if necessary."),
10354
10355 JS_FN_HELP("enableShellAllocationMetadataBuilder", EnableShellAllocationMetadataBuilder, 0, 0,
10356 "enableShellAllocationMetadataBuilder()",
10357 " Use ShellAllocationMetadataBuilder to supply metadata for all newly created objects."),
10358
10359 JS_FN_HELP("getAllocationMetadata", GetAllocationMetadata, 1, 0,
10360 "getAllocationMetadata(obj)",
10361 " Get the metadata for an object."),
10362
10363 JS_INLINABLE_FN_HELP("bailout", testingFunc_bailout, 0, 0, TestBailout,
10364 "bailout()",
10365 " Force a bailout out of ionmonkey (if running in ionmonkey)."),
10366
10367 JS_FN_HELP("bailAfter", testingFunc_bailAfter, 1, 0,
10368 "bailAfter(number)",
10369 " Start a counter to bail once after passing the given amount of possible bailout positions in\n"
10370 " ionmonkey.\n"),
10371
10372 JS_FN_HELP("invalidate", testingFunc_invalidate, 0, 0,
10373 "invalidate()",
10374 " Force an immediate invalidation (if running in Warp)."),
10375
10376 JS_FN_HELP("inJit", testingFunc_inJit, 0, 0,
10377 "inJit()",
10378 " Returns true when called within (jit-)compiled code. When jit compilation is disabled this\n"
10379 " function returns an error string. This function returns false in all other cases.\n"
10380 " Depending on truthiness, you should continue to wait for compilation to happen or stop execution.\n"),
10381
10382 JS_FN_HELP("inIon", testingFunc_inIon, 0, 0,
10383 "inIon()",
10384 " Returns true when called within ion. When ion is disabled or when compilation is abnormally\n"
10385 " slow to start, this function returns an error string. Otherwise, this function returns false.\n"
10386 " This behaviour ensures that a falsy value means that we are not in ion, but expect a\n"
10387 " compilation to occur in the future. Conversely, a truthy value means that we are either in\n"
10388 " ion or that there is litle or no chance of ion ever compiling the current script."),
10389
10390 JS_FN_HELP("assertJitStackInvariants", TestingFunc_assertJitStackInvariants, 0, 0,
10391 "assertJitStackInvariants()",
10392 " Iterates the Jit stack and check that stack invariants hold."),
10393
10394 JS_FN_HELP("setIonCheckGraphCoherency", SetIonCheckGraphCoherency, 1, 0,
10395 "setIonCheckGraphCoherency(bool)",
10396 " Set whether Ion should perform graph consistency (DEBUG-only) assertions. These assertions\n"
10397 " are valuable and should be generally enabled, however they can be very expensive for large\n"
10398 " (wasm) programs."),
10399
10400 JS_FN_HELP("serialize", testingFunc_serialize, 1, 0,
10401 "serialize(data, [transferables, [policy]])",
10402 " Serialize 'data' using JS_WriteStructuredClone. Returns a structured\n"
10403 " clone buffer object. 'policy' may be an options hash. Valid keys:\n"
10404 " 'SharedArrayBuffer' - either 'allow' or 'deny' (the default)\n"
10405 " to specify whether SharedArrayBuffers may be serialized.\n"
10406 " 'scope' - SameProcess, DifferentProcess, or\n"
10407 " DifferentProcessForIndexedDB. Determines how some values will be\n"
10408 " serialized. Clone buffers may only be deserialized with a compatible\n"
10409 " scope. NOTE - For DifferentProcess/DifferentProcessForIndexedDB,\n"
10410 " must also set SharedArrayBuffer:'deny' if data contains any shared memory\n"
10411 " object."),
10412
10413 JS_FN_HELP("deserialize", Deserialize, 1, 0,
10414 "deserialize(clonebuffer[, opts])",
10415 " Deserialize data generated by serialize. 'opts' may be an options hash.\n"
10416 " Valid keys:\n"
10417 " 'SharedArrayBuffer' - either 'allow' or 'deny' (the default)\n"
10418 " to specify whether SharedArrayBuffers may be serialized.\n"
10419 " 'scope', which limits the clone buffers that are considered\n"
10420 " valid. Allowed values: ''SameProcess', 'DifferentProcess',\n"
10421 " and 'DifferentProcessForIndexedDB'. So for example, a\n"
10422 " DifferentProcessForIndexedDB clone buffer may be deserialized in any scope, but\n"
10423 " a SameProcess clone buffer cannot be deserialized in a\n"
10424 " DifferentProcess scope."),
10425
10426 JS_FN_HELP("detachArrayBuffer", DetachArrayBuffer, 1, 0,
10427 "detachArrayBuffer(buffer)",
10428 " Detach the given ArrayBuffer object from its memory, i.e. as if it\n"
10429 " had been transferred to a WebWorker."),
10430
10431 JS_FN_HELP("makeSerializable", MakeSerializable, 1, 0,
10432 "makeSerializable(numeric id, [behavior])",
10433 " Make a custom serializable, transferable object. It will have a single accessor\n"
10434 " obj.log that will give a history of all operations on all such objects in the\n"
10435 " current thread as an array [id, action, id, action, ...] where the id\n"
10436 " is the number passed into this function, and the action is one of:\n"
10437 " ? - the canTransfer() hook was called.\n"
10438 " w - the write() hook was called.\n"
10439 " W - the writeTransfer() hook was called.\n"
10440 " R - the readTransfer() hook was called.\n"
10441 " r - the read() hook was called.\n"
10442 " F - the freeTransfer() hook was called.\n"
10443 " The `behavior` parameter can be used to force a failure during processing:\n"
10444 " 1 - fail during readTransfer() hook\n"
10445 " 2 - fail during read() hook\n"
10446 " Set the log to null to clear it."),
10447
10448 JS_FN_HELP("ensureNonInline", EnsureNonInline, 1, 0,
10449 "ensureNonInline(view or buffer)",
10450 " Ensure that the memory for the given ArrayBuffer or ArrayBufferView\n"
10451 " is not inline."),
10452
10453 JS_FN_HELP("pinArrayBufferOrViewLength", PinArrayBufferOrViewLength, 1, 0,
10454 "pinArrayBufferOrViewLength(view or buffer[, pin])",
10455 " Prevent or allow (if `pin` is false) changes to the length of the given\n"
10456 " ArrayBuffer or ArrayBufferView. `pin` defaults to true."),
10457
10458 JS_FN_HELP("JSONStringify", JSONStringify, 4, 0,
10459 "JSONStringify(value, behavior)",
10460 " Same as JSON.stringify(value), but allows setting behavior:\n"
10461 " Normal: the default\n"
10462 " FastOnly: throw if the fast path bails\n"
10463 " SlowOnly: skip the fast path entirely\n"
10464 " Compare: run both the fast and slow paths and compare the result. Crash if\n"
10465 " they do not match. If the fast path bails, no comparison is done."),
10466
10467 JS_FN_HELP("helperThreadCount", HelperThreadCount, 0, 0,
10468 "helperThreadCount()",
10469 " Returns the number of helper threads available for off-thread tasks."),
10470
10471 JS_FN_HELP("createShapeSnapshot", CreateShapeSnapshot, 1, 0,
10472 "createShapeSnapshot(obj)",
10473 " Returns an object containing a shape snapshot for use with\n"
10474 " checkShapeSnapshot.\n"),
10475
10476 JS_FN_HELP("checkShapeSnapshot", CheckShapeSnapshot, 2, 0,
10477 "checkShapeSnapshot(snapshot, [obj])",
10478 " Check shape invariants based on the given snapshot and optional object.\n"
10479 " If there's no object argument, the snapshot's object is used.\n"),
10480
10481 JS_FN_HELP("enableShapeConsistencyChecks", EnableShapeConsistencyChecks, 0, 0,
10482 "enableShapeConsistencyChecks()",
10483 " Enable some slow Shape assertions.\n"),
10484
10485 JS_FN_HELP("reportOutOfMemory", ReportOutOfMemory, 0, 0,
10486 "reportOutOfMemory()",
10487 " Report OOM, then clear the exception and return undefined. For crash testing."),
10488
10489 JS_FN_HELP("throwOutOfMemory", ThrowOutOfMemory, 0, 0,
10490 "throwOutOfMemory()",
10491 " Throw out of memory exception, for OOM handling testing."),
10492
10493 JS_FN_HELP("reportLargeAllocationFailure", ReportLargeAllocationFailure, 0, 0,
10494 "reportLargeAllocationFailure([bytes])",
10495 " Call the large allocation failure callback, as though a large malloc call failed,\n"
10496 " then return undefined. In Gecko, this sends a memory pressure notification, which\n"
10497 " can free up some memory."),
10498
10499 JS_FN_HELP("findPath", FindPath, 2, 0,
10500 "findPath(start, target)",
10501 " Return an array describing one of the shortest paths of GC heap edges from\n"
10502 " |start| to |target|, or |undefined| if |target| is unreachable from |start|.\n"
10503 " Each element of the array is either of the form:\n"
10504 " { node: <object or string>, edge: <string describing edge from node> }\n"
10505 " if the node is a JavaScript object or value; or of the form:\n"
10506 " { type: <string describing node>, edge: <string describing edge> }\n"
10507 " if the node is some internal thing that is not a proper JavaScript value\n"
10508 " (like a shape or a scope chain element). The destination of the i'th array\n"
10509 " element's edge is the node of the i+1'th array element; the destination of\n"
10510 " the last array element is implicitly |target|.\n"),
10511
10512 JS_FN_HELP("sharedMemoryEnabled", SharedMemoryEnabled, 0, 0,
10513 "sharedMemoryEnabled()",
10514 " Return true if SharedArrayBuffer and Atomics are enabled"),
10515
10516 JS_FN_HELP("sharedArrayRawBufferRefcount", SharedArrayRawBufferRefcount, 0, 0,
10517 "sharedArrayRawBufferRefcount(sab)",
10518 " Return the reference count of the SharedArrayRawBuffer object held by sab"),
10519
10520 #ifdef NIGHTLY_BUILD
10521 JS_FN_HELP("objectAddress", ObjectAddress, 1, 0,
10522 "objectAddress(obj)",
10523 " Return the current address of the object. For debugging only--this\n"
10524 " address may change during a moving GC."),
10525
10526 JS_FN_HELP("sharedAddress", SharedAddress, 1, 0,
10527 "sharedAddress(obj)",
10528 " Return the address of the shared storage of a SharedArrayBuffer."),
10529 #endif
10530
10531 JS_FN_HELP("hasInvalidatedTeleporting", HasInvalidatedTeleporting, 1, 0,
10532 "hasInvalidatedTeleporting(obj)",
10533 " Return true if the shape teleporting optimization has been disabled for |obj|."),
10534
10535 JS_FN_HELP("evalReturningScope", EvalReturningScope, 1, 0,
10536 "evalReturningScope(scriptStr, [global])",
10537 " Evaluate the script in a new scope and return the scope.\n"
10538 " If |global| is present, clone the script to |global| before executing."),
10539
10540 JS_FN_HELP("backtrace", DumpBacktrace, 1, 0,
10541 "backtrace()",
10542 " Dump out a brief backtrace."),
10543
10544 JS_FN_HELP("getBacktrace", GetBacktrace, 1, 0,
10545 "getBacktrace([options])",
10546 " Return the current stack as a string. Takes an optional options object,\n"
10547 " which may contain any or all of the boolean properties:\n"
10548 " options.args - show arguments to each function\n"
10549 " options.locals - show local variables in each frame\n"
10550 " options.thisprops - show the properties of the 'this' object of each frame\n"),
10551
10552 JS_FN_HELP("byteSize", ByteSize, 1, 0,
10553 "byteSize(value)",
10554 " Return the size in bytes occupied by |value|, or |undefined| if value\n"
10555 " is not allocated in memory.\n"),
10556
10557 JS_FN_HELP("byteSizeOfScript", ByteSizeOfScript, 1, 0,
10558 "byteSizeOfScript(f)",
10559 " Return the size in bytes occupied by the function |f|'s JSScript.\n"),
10560
10561 JS_FN_HELP("setImmutablePrototype", SetImmutablePrototype, 1, 0,
10562 "setImmutablePrototype(obj)",
10563 " Try to make obj's [[Prototype]] immutable, such that subsequent attempts to\n"
10564 " change it will fail. Return true if obj's [[Prototype]] was successfully made\n"
10565 " immutable (or if it already was immutable), false otherwise. Throws in case\n"
10566 " of internal error, or if the operation doesn't even make sense (for example,\n"
10567 " because the object is a revoked proxy)."),
10568
10569 JS_FN_HELP("allocationMarker", AllocationMarker, 0, 0,
10570 "allocationMarker([options])",
10571 " Return a freshly allocated object whose [[Class]] name is\n"
10572 " \"AllocationMarker\". Such objects are allocated only by calls\n"
10573 " to this function, never implicitly by the system, making them\n"
10574 " suitable for use in allocation tooling tests. Takes an optional\n"
10575 " options object which may contain the following properties:\n"
10576 " * nursery: bool, whether to allocate the object in the nursery\n"),
10577
10578 JS_FN_HELP("setGCCallback", SetGCCallback, 1, 0,
10579 "setGCCallback({action:\"...\", options...})",
10580 " Set the GC callback. action may be:\n"
10581 " 'minorGC' - run a nursery collection\n"
10582 " 'majorGC' - run a major collection, nesting up to a given 'depth'\n"),
10583
10584 #ifdef DEBUG
10585 JS_FN_HELP("enqueueMark", EnqueueMark, 1, 0,
10586 "enqueueMark(obj|string)",
10587 " Add an object to the queue of objects to mark at the beginning every GC. (Note\n"
10588 " that the objects will actually be marked at the beginning of every slice, but\n"
10589 " after the first slice they will already be marked so nothing will happen.)\n"
10590 " \n"
10591 " Instead of an object, a few magic strings may be used:\n"
10592 " 'yield' - cause the current marking slice to end, as if the mark budget were\n"
10593 " exceeded.\n"
10594 " 'enter-weak-marking-mode' - divide the list into two segments. The items after\n"
10595 " this string will not be marked until we enter weak marking mode. Note that weak\n"
10596 " marking mode may be entered zero or multiple times for one GC.\n"
10597 " 'abort-weak-marking-mode' - same as above, but then abort weak marking to fall back\n"
10598 " on the old iterative marking code path.\n"
10599 " 'drain' - fully drain the mark stack before continuing.\n"
10600 " 'set-color-black' - force everything following in the mark queue to be marked black.\n"
10601 " 'set-color-gray' - continue with the regular GC until gray marking is possible, then force\n"
10602 " everything following in the mark queue to be marked gray.\n"
10603 " 'unset-color' - stop forcing the mark color."),
10604
10605 JS_FN_HELP("clearMarkQueue", ClearMarkQueue, 0, 0,
10606 "clearMarkQueue()",
10607 " Cancel the special marking of all objects enqueue with enqueueMark()."),
10608
10609 JS_FN_HELP("getMarkQueue", GetMarkQueue, 0, 0,
10610 "getMarkQueue()",
10611 " Return the current mark queue set up via enqueueMark calls. Note that all\n"
10612 " returned values will be wrapped into the current compartment, so this loses\n"
10613 " some fidelity."),
10614 #endif // DEBUG
10615
10616 JS_FN_HELP("nurseryStringsEnabled", NurseryStringsEnabled, 0, 0,
10617 "nurseryStringsEnabled()",
10618 " Return whether strings are currently allocated in the nursery for the current\n"
10619 " global\n"),
10620
10621 JS_FN_HELP("isNurseryAllocated", IsNurseryAllocated, 1, 0,
10622 "isNurseryAllocated(thing)",
10623 " Return whether a GC thing is nursery allocated.\n"),
10624
10625 JS_FN_HELP("numAllocSitesPretenured", NumAllocSitesPretenured, 0, 0,
10626 "numAllocSitesPretenured()",
10627 " Return the number of allocation sites that were pretenured for the current\n"
10628 " global\n"),
10629
10630 JS_FN_HELP("getLcovInfo", GetLcovInfo, 1, 0,
10631 "getLcovInfo(global)",
10632 " Generate LCOV tracefile for the given compartment. If no global are provided then\n"
10633 " the current global is used as the default one.\n"),
10634
10635 #ifdef DEBUG
10636 JS_FN_HELP("setRNGState", SetRNGState, 2, 0,
10637 "setRNGState(seed0, seed1)",
10638 " Set this compartment's RNG state.\n"),
10639 #endif
10640
10641 #ifdef AFLFUZZ
10642 JS_FN_HELP("aflloop", AflLoop, 1, 0,
10643 "aflloop(max_cnt)",
10644 " Call the __AFL_LOOP() runtime function (see AFL docs)\n"),
10645 #endif
10646
10647 JS_FN_HELP("monotonicNow", MonotonicNow, 0, 0,
10648 "monotonicNow()",
10649 " Return a timestamp reflecting the current elapsed system time.\n"
10650 " This is monotonically increasing.\n"),
10651
10652 JS_FN_HELP("timeSinceCreation", TimeSinceCreation, 0, 0,
10653 "TimeSinceCreation()",
10654 " Returns the time in milliseconds since process creation.\n"
10655 " This uses a clock compatible with the profiler.\n"),
10656
10657 JS_FN_HELP("isConstructor", IsConstructor, 1, 0,
10658 "isConstructor(value)",
10659 " Returns whether the value is considered IsConstructor.\n"),
10660
10661 JS_FN_HELP("getTimeZone", GetTimeZone, 0, 0,
10662 "getTimeZone()",
10663 " Get the current time zone.\n"),
10664
10665 JS_FN_HELP("getDefaultLocale", GetDefaultLocale, 0, 0,
10666 "getDefaultLocale()",
10667 " Get the current default locale.\n"),
10668
10669 JS_FN_HELP("getCoreCount", GetCoreCount, 0, 0,
10670 "getCoreCount()",
10671 " Get the number of CPU cores from the platform layer. Typically this\n"
10672 " means the number of hyperthreads on systems where that makes sense.\n"),
10673
10674 JS_FN_HELP("setTimeResolution", SetTimeResolution, 2, 0,
10675 "setTimeResolution(resolution, jitter)",
10676 " Enables time clamping and jittering. Specify a time resolution in\n"
10677 " microseconds and whether or not to jitter\n"),
10678
10679 JS_FN_HELP("scriptedCallerGlobal", ScriptedCallerGlobal, 0, 0,
10680 "scriptedCallerGlobal()",
10681 " Get the caller's global (or null). See JS::GetScriptedCallerGlobal.\n"),
10682
10683 JS_FN_HELP("objectGlobal", ObjectGlobal, 1, 0,
10684 "objectGlobal(obj)",
10685 " Returns the object's global object or null if the object is a wrapper.\n"),
10686
10687 JS_FN_HELP("isSameCompartment", IsSameCompartment, 2, 0,
10688 "isSameCompartment(obj1, obj2)",
10689 " Unwraps obj1 and obj2 and returns whether the unwrapped objects are\n"
10690 " same-compartment.\n"),
10691
10692 JS_FN_HELP("firstGlobalInCompartment", FirstGlobalInCompartment, 1, 0,
10693 "firstGlobalInCompartment(obj)",
10694 " Returns the first global in obj's compartment.\n"),
10695
10696 JS_FN_HELP("assertCorrectRealm", AssertCorrectRealm, 0, 0,
10697 "assertCorrectRealm()",
10698 " Asserts cx->realm matches callee->realm.\n"),
10699
10700 JS_FN_HELP("globalLexicals", GlobalLexicals, 0, 0,
10701 "globalLexicals()",
10702 " Returns an object containing a copy of all global lexical bindings.\n"
10703 " Example use: let x = 1; assertEq(globalLexicals().x, 1);\n"),
10704
10705 JS_FN_HELP("baselineCompile", BaselineCompile, 2, 0,
10706 "baselineCompile([fun/code], forceDebugInstrumentation=false)",
10707 " Baseline-compiles the given JS function or script.\n"
10708 " Without arguments, baseline-compiles the caller's script; but note\n"
10709 " that extra boilerplate is needed afterwards to cause the VM to start\n"
10710 " running the jitcode rather than staying in the interpreter:\n"
10711 " baselineCompile(); for (var i=0; i<1; i++) {} ...\n"
10712 " The interpreter will enter the new jitcode at the loop header unless\n"
10713 " baselineCompile returned a string or threw an error.\n"),
10714
10715 JS_FN_HELP("encodeAsUtf8InBuffer", EncodeAsUtf8InBuffer, 2, 0,
10716 "encodeAsUtf8InBuffer(str, uint8Array)",
10717 " Encode as many whole code points from the string str into the provided\n"
10718 " Uint8Array as will completely fit in it, converting lone surrogates to\n"
10719 " REPLACEMENT CHARACTER. Return an array [r, w] where |r| is the\n"
10720 " number of 16-bit units read and |w| is the number of bytes of UTF-8\n"
10721 " written."),
10722
10723 JS_FN_HELP("clearKeptObjects", ClearKeptObjects, 0, 0,
10724 "clearKeptObjects()",
10725 "Perform the ECMAScript ClearKeptObjects operation, clearing the list of\n"
10726 "observed WeakRef targets that are kept alive until the next synchronous\n"
10727 "sequence of ECMAScript execution completes. This is used for testing\n"
10728 "WeakRefs.\n"),
10729
10730 JS_FN_HELP("numberToDouble", NumberToDouble, 1, 0,
10731 "numberToDouble(number)",
10732 " Return the input number as double-typed number."),
10733
10734 JS_FN_HELP("getICUOptions", GetICUOptions, 0, 0,
10735 "getICUOptions()",
10736 " Return an object describing the following ICU options.\n\n"
10737 " version: a string containing the ICU version number, e.g. '67.1'\n"
10738 " unicode: a string containing the Unicode version number, e.g. '13.0'\n"
10739 " locale: the ICU default locale, e.g. 'en_US'\n"
10740 " tzdata: a string containing the tzdata version number, e.g. '2020a'\n"
10741 " timezone: the ICU default time zone, e.g. 'America/Los_Angeles'\n"
10742 " host-timezone: the host time zone, e.g. 'America/Los_Angeles'"),
10743
10744 JS_FN_HELP("getAvailableLocalesOf", GetAvailableLocalesOf, 0, 0,
10745 "getAvailableLocalesOf(name)",
10746 " Return an array of all available locales for the given Intl constuctor."),
10747
10748 JS_FN_HELP("isSmallFunction", IsSmallFunction, 1, 0,
10749 "isSmallFunction(fun)",
10750 " Returns true if a scripted function is small enough to be inlinable."),
10751
10752 JS_FN_HELP("compileToStencil", CompileToStencil, 1, 0,
10753 "compileToStencil(string, [options])",
10754 " Parses the given string argument as js script, returns the stencil"
10755 " for it."),
10756
10757 JS_FN_HELP("evalStencil", EvalStencil, 1, 0,
10758 "evalStencil(stencil, [options])",
10759 " Instantiates the given stencil, and evaluates the top-level script it"
10760 " defines."),
10761
10762 JS_FN_HELP("compileToStencilXDR", CompileToStencilXDR, 1, 0,
10763 "compileToStencilXDR(string, [options])",
10764 " Parses the given string argument as js script, produces the stencil"
10765 " for it, XDR-encodes the stencil, and returns an object that contains the"
10766 " XDR buffer."),
10767
10768 JS_FN_HELP("evalStencilXDR", EvalStencilXDR, 1, 0,
10769 "evalStencilXDR(stencilXDR, [options])",
10770 " Reads the given stencil XDR object, and evaluates the top-level script it"
10771 " defines."),
10772
10773 JS_FN_HELP("getExceptionInfo", GetExceptionInfo, 1, 0,
10774 "getExceptionInfo(fun)",
10775 " Calls the given function and returns information about the exception it"
10776 " throws. Returns null if the function didn't throw an exception."),
10777
10778 JS_FN_HELP("nukeCCW", NukeCCW, 1, 0,
10779 "nukeCCW(wrapper)",
10780 " Nuke a CrossCompartmentWrapper, which turns it into a DeadProxyObject."),
10781
10782 JS_FN_HELP("assertRealmFuseInvariants", AssertRealmFuseInvariants, 0, 0,
10783 "assertRealmFuseInvariants()",
10784 " Runs the realm's fuse invariant checks -- these will crash on failure. "
10785 " Only available in fuzzing or debug builds, so usage should be guarded. "),
10786
10787 JS_FN_HELP("isCCW", IsCCW, 1, 0,
10788 "isCCW(object)",
10789 " Return true if an object is a CCW."),
10790
10791 JS_FN_HELP("popAllFusesInRealm", PopAllFusesInRealm, 0, 0,
10792 "popAllFusesInRealm()",
10793 " Pops all the fuses in the current realm"),
10794
10795 JS_FN_HELP("getAllPrefNames", GetAllPrefNames, 0, 0,
10796 "getAllPrefNames()",
10797 " Returns an array containing the names of all JS prefs."),
10798
10799 JS_FN_HELP("getPrefValue", GetPrefValue, 1, 0,
10800 "getPrefValue(name)",
10801 " Return the value of the JS pref with the given name."),
10802
10803 JS_FN_HELP("hadOutOfMemory", HadOutOfMemory, 0, 0,
10804 "hadOutOfMemory()",
10805 " Return the runtime's internal hadOutOfMemory flag that is set when\n"
10806 " out of memory is hit with an exception being propagated. "),
10807
10808 JS_FS_HELP_END
10809 };
10810 // clang-format on
10811
10812 // clang-format off
10813 static const JSFunctionSpecWithHelp FuzzingUnsafeTestingFunctions[] = {
10814 JS_FN_HELP("getErrorNotes", GetErrorNotes, 1, 0,
10815 "getErrorNotes(error)",
10816 " Returns an array of error notes."),
10817
10818 JS_FN_HELP("setTimeZone", SetTimeZone, 1, 0,
10819 "setTimeZone(tzname)",
10820 " Set the 'TZ' environment variable to the given time zone and applies the new time zone.\n"
10821 " The time zone given is validated according to the current environment.\n"
10822 " An empty string or undefined resets the time zone to its default value."),
10823
10824 JS_FN_HELP("setDefaultLocale", SetDefaultLocale, 1, 0,
10825 "setDefaultLocale(locale)",
10826 " Set the runtime default locale to the given value.\n"
10827 " An empty string or undefined resets the runtime locale to its default value.\n"
10828 " NOTE: The input string is not fully validated, it must be a valid BCP-47 language tag."),
10829
10830 JS_FN_HELP("isCollectingDelazifications", IsCollectingDelazifications, 1, 0,
10831 "isCollectingDelazifications(fun)",
10832 " True if script for the function is collecting delazifications."),
10833
10834 JS_FN_HELP("isDelazificationPopulatedFor", IsDelazificationsPopulated, 1, 0,
10835 "isDelazificationPopulatedFor(fun)",
10836 " True if fun is available in the shared stencils."),
10837
10838 JS_FN_HELP("waitForDelazificationOf", WaitForDelazificationOf, 1, 0,
10839 "waitForDelazificationOf(fun)",
10840 " Block main thread execution until the function is made available in the\n"
10841 " shared stencils. If this function isn't sharing stencils, return immediately."),
10842
10843 JS_FN_HELP("waitForDone", WaitForDone, 1, 0,
10844 "waitForDone(obj)",
10845 " Loop calling `RunJobs` until the `done` value of `obj` is true"),
10846
10847 JS_FN_HELP("getInnerMostEnvironmentObject", GetInnerMostEnvironmentObject, 0, 0,
10848 "getInnerMostEnvironmentObject()",
10849 " Return the inner-most environment object for current execution."),
10850
10851 JS_FN_HELP("getEnclosingEnvironmentObject", GetEnclosingEnvironmentObject, 1, 0,
10852 "getEnclosingEnvironmentObject(env)",
10853 " Return the enclosing environment object for given environment object."),
10854
10855 JS_FN_HELP("getEnvironmentObjectType", GetEnvironmentObjectType, 1, 0,
10856 "getEnvironmentObjectType(env)",
10857 " Return a string represents the type of given environment object."),
10858
10859 JS_FN_HELP("shortestPaths", ShortestPaths, 3, 0,
10860 "shortestPaths(targets, options)",
10861 " Return an array of arrays of shortest retaining paths. There is an array of\n"
10862 " shortest retaining paths for each object in |targets|. Each element in a path\n"
10863 " is of the form |{ predecessor, edge }|. |options| may contain:\n"
10864 " \n"
10865 " maxNumPaths: The maximum number of paths returned in each of those arrays\n"
10866 " (default 3).\n"
10867 " start: The object to start all paths from. If not given, then\n"
10868 " the starting point will be the set of GC roots."),
10869
10870 JS_FN_HELP("getFuseState", GetFuseState, 0, 0,
10871 "getFuseState()",
10872 " Return an object describing the calling realm's fuse state, "
10873 " as well as the state of any runtime fuses."),
10874
10875 #if defined(DEBUG) || defined(JS_JITSPEW)
10876 JS_FN_HELP("dumpObject", DumpObject, 1, 0,
10877 "dumpObject(obj)",
10878 " Dump an internal representation of an object."),
10879
10880 JS_FN_HELP("dumpValue", DumpValue, 1, 0,
10881 "dumpValue(v)",
10882 " Dump an internal representation of a value."),
10883
10884 JS_FN_HELP("dumpValueToString", DumpValueToString, 1, 0,
10885 "dumpValue(v)",
10886 " Return a dump of an internal representation of a value."),
10887
10888 JS_FN_HELP("dumpStringRepresentation", DumpStringRepresentation, 1, 0,
10889 "dumpStringRepresentation(str)",
10890 " Print a human-readable description of how the string |str| is represented.\n"),
10891
10892 JS_FN_HELP("stringRepresentation", GetStringRepresentation, 1, 0,
10893 "stringRepresentation(str)",
10894 " Return a human-readable description of how the string |str| is represented.\n"),
10895 #endif
10896
10897 JS_FN_HELP("wasmExtractCode", WasmExtractCode, 1, 0,
10898 "wasmExtractCode(module[, tier])",
10899 " Extracts generated machine code from WebAssembly.Module. The tier is a string,\n"
10900 " 'stable', 'best', 'baseline', or 'ion'; the default is 'stable'. If the request\n"
10901 " cannot be satisfied then null is returned. If the request is 'ion' then block\n"
10902 " until background compilation is complete."),
10903
10904 JS_FN_HELP("wasmDis", WasmDisassemble, 1, 0,
10905 "wasmDis(wasmObject[, options])\n",
10906 " Disassembles generated machine code from an exported WebAssembly function,\n"
10907 " or from all the functions defined in the module or instance, exported and not.\n"
10908 " The `options` is an object with the following optional keys:\n"
10909 " asString: boolean - if true, return a string rather than printing on stderr,\n"
10910 " the default is false.\n"
10911 " tier: string - one of 'stable', 'best', 'baseline', or 'ion'; the default is\n"
10912 " 'stable'.\n"
10913 " kinds: string - if set, and the wasmObject is a module or instance, a\n"
10914 " comma-separated list of the following keys, the default is `Function`:\n"
10915 " Function - functions defined in the module\n"
10916 " InterpEntry - C++-to-wasm stubs\n"
10917 " JitEntry - jitted-js-to-wasm stubs\n"
10918 " ImportInterpExit - wasm-to-C++ stubs\n"
10919 " ImportJitExit - wasm-to-jitted-JS stubs\n"
10920 " all - all kinds, including obscure ones\n"),
10921
10922 JS_FN_HELP("wasmModuleToText", WasmModuleToText, 1, 0,
10923 "wasmModuleToText(wasmModule[, options])\n",
10924 " Converts a compiled wasm module to the wasm text format.\n"),
10925
10926 JS_FN_HELP("wasmDumpIon", WasmDumpIon, 2, 0,
10927 "wasmDumpIon(bytecode, funcIndex, [, contents])\n",
10928 "wasmDumpIon(bytecode, funcIndex, [, contents])"
10929 " Returns a dump of compiling a function in the specified module with Ion."
10930 " The `contents` flag controls what is dumped. one of:"
10931 " `mir` | `unopt-mir`: Unoptimized MIR (the default)"
10932 " `opt-mir`: Optimized MIR"
10933 " `lir`: LIR"),
10934
10935 JS_FN_HELP("wasmFunctionTier", WasmFunctionTier, 1, 0,
10936 "wasmFunctionTier(wasmFunc)\n",
10937 " Returns the best compiled tier for a function. Either 'baseline' or 'optimized'."),
10938
10939 JS_FN_HELP("wasmMetadataAnalysis", wasmMetadataAnalysis, 1, 0,
10940 "wasmMetadataAnalysis(wasmObject)",
10941 " Prints an analysis of the size of metadata on this wasm object.\n"),
10942
10943 JS_FS_HELP_END
10944 };
10945 // clang-format on
10946
10947 // clang-format off
10948 static const JSFunctionSpecWithHelp PCCountProfilingTestingFunctions[] = {
10949 JS_FN_HELP("start", PCCountProfiling_Start, 0, 0,
10950 "start()",
10951 " Start PC count profiling."),
10952
10953 JS_FN_HELP("stop", PCCountProfiling_Stop, 0, 0,
10954 "stop()",
10955 " Stop PC count profiling."),
10956
10957 JS_FN_HELP("purge", PCCountProfiling_Purge, 0, 0,
10958 "purge()",
10959 " Purge the collected PC count profiling data."),
10960
10961 JS_FN_HELP("count", PCCountProfiling_ScriptCount, 0, 0,
10962 "count()",
10963 " Return the number of profiled scripts."),
10964
10965 JS_FN_HELP("summary", PCCountProfiling_ScriptSummary, 1, 0,
10966 "summary(index)",
10967 " Return the PC count profiling summary for the given script index.\n"
10968 " The script index must be in the range [0, pc.count())."),
10969
10970 JS_FN_HELP("contents", PCCountProfiling_ScriptContents, 1, 0,
10971 "contents(index)",
10972 " Return the complete profiling contents for the given script index.\n"
10973 " The script index must be in the range [0, pc.count())."),
10974
10975 JS_FS_HELP_END
10976 };
10977 // clang-format on
10978
10979 // clang-format off
10980 static const JSFunctionSpecWithHelp FdLibMTestingFunctions[] = {
10981 JS_FN_HELP("pow", FdLibM_Pow, 2, 0,
10982 "pow(x, y)",
10983 " Return x ** y."),
10984
10985 JS_FS_HELP_END
10986 };
10987 // clang-format on
10988
10989 bool js::InitTestingFunctions() { return disasmPrinter.init(); }
10990
10991 bool js::DefineTestingFunctions(JSContext* cx, HandleObject obj,
10992 bool fuzzingSafe_, bool disableOOMFunctions_) {
10993 fuzzingSafe = fuzzingSafe_;
10994 if (EnvVarIsDefined("MOZ_FUZZING_SAFE")) {
10995 fuzzingSafe = true;
10996 }
10997
10998 disableOOMFunctions = disableOOMFunctions_;
10999
11000 if (!fuzzingSafe) {
11001 if (!JS_DefineFunctionsWithHelp(cx, obj, FuzzingUnsafeTestingFunctions)) {
11002 return false;
11003 }
11004
11005 RootedObject pccount(cx, JS_NewPlainObject(cx));
11006 if (!pccount) {
11007 return false;
11008 }
11009
11010 if (!JS_DefineProperty(cx, obj, "pccount", pccount, 0)) {
11011 return false;
11012 }
11013
11014 if (!JS_DefineFunctionsWithHelp(cx, pccount,
11015 PCCountProfilingTestingFunctions)) {
11016 return false;
11017 }
11018 }
11019
11020 RootedObject fdlibm(cx, JS_NewPlainObject(cx));
11021 if (!fdlibm) {
11022 return false;
11023 }
11024
11025 if (!JS_DefineProperty(cx, obj, "fdlibm", fdlibm, 0)) {
11026 return false;
11027 }
11028
11029 if (!JS_DefineFunctionsWithHelp(cx, fdlibm, FdLibMTestingFunctions)) {
11030 return false;
11031 }
11032
11033 return JS_DefineFunctionsWithHelp(cx, obj, TestingFunctions);
11034 }
11035
11036 #ifdef FUZZING_JS_FUZZILLI
11037 uint32_t js::FuzzilliHashDouble(double value) {
11038 // We shouldn't GC here as this is called directly from IC code.
11039 AutoUnsafeCallWithABI unsafe;
11040 uint64_t v = mozilla::BitwiseCast<uint64_t>(value);
11041 return static_cast<uint32_t>(v) + static_cast<uint32_t>(v >> 32);
11042 }
11043
11044 uint32_t js::FuzzilliHashBigInt(BigInt* bigInt) {
11045 // We shouldn't GC here as this is called directly from IC code.
11046 AutoUnsafeCallWithABI unsafe;
11047 return bigInt->hash();
11048 }
11049
11050 void js::FuzzilliHashObject(JSContext* cx, JSObject* obj) {
11051 // called from IC and baseline/interpreter
11052 uint32_t hash;
11053 FuzzilliHashObjectInl(cx, obj, &hash);
11054
11055 cx->executionHashInputs += 1;
11056 cx->executionHash = mozilla::RotateLeft(cx->executionHash + hash, 1);
11057 }
11058
11059 void js::FuzzilliHashObjectInl(JSContext* cx, JSObject* obj, uint32_t* out) {
11060 *out = 0;
11061 if (!js::SupportDifferentialTesting()) {
11062 return;
11063 }
11064
11065 RootedValue v(cx);
11066 v.setObject(*obj);
11067
11068 JSAutoStructuredCloneBuffer JSCloner(
11069 JS::StructuredCloneScope::DifferentProcess, nullptr, nullptr);
11070 if (JSCloner.write(cx, v)) {
11071 JSStructuredCloneData& data = JSCloner.data();
11072 data.ForEachDataChunk([&](const char* aData, size_t aSize) {
11073 uint32_t h = mozilla::HashBytes(aData, aSize);
11074 h = (h << 1) | 1;
11075 *out ^= h;
11076 *out *= h;
11077 return true;
11078 });
11079 } else if (JS_IsExceptionPending(cx)) {
11080 JS_ClearPendingException(cx);
11081 }
11082 }
11083 #endif