| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
/* JS shell. */ |
| 8 |
|
| 9 |
#include "mozilla/AlreadyAddRefed.h" // mozilla::already_AddRefed |
| 10 |
#include "mozilla/ArrayUtils.h" |
| 11 |
#include "mozilla/Assertions.h" // MOZ_ASSERT, MOZ_ASSERT_IF, MOZ_RELEASE_ASSERT, MOZ_CRASH |
| 12 |
#include "mozilla/Atomics.h" |
| 13 |
#include "mozilla/Attributes.h" |
| 14 |
#include "mozilla/Compression.h" |
| 15 |
#include "mozilla/DebugOnly.h" |
| 16 |
#include "mozilla/EnumSet.h" |
| 17 |
#include "mozilla/IntegerPrintfMacros.h" |
| 18 |
#include "mozilla/mozalloc.h" |
| 19 |
#include "mozilla/PodOperations.h" |
| 20 |
#include "mozilla/RandomNum.h" |
| 21 |
#include "mozilla/RefPtr.h" |
| 22 |
#include "mozilla/ScopeExit.h" |
| 23 |
#include "mozilla/Sprintf.h" |
| 24 |
#include "mozilla/TimeStamp.h" |
| 25 |
#include "mozilla/UniquePtrExtensions.h" // UniqueFreePtr |
| 26 |
#include "mozilla/Utf8.h" |
| 27 |
#include "mozilla/Variant.h" |
| 28 |
|
| 29 |
#include <algorithm> |
| 30 |
#include <cctype> |
| 31 |
#include <chrono> |
| 32 |
#ifdef XP_WIN |
| 33 |
# include <direct.h> |
| 34 |
# include <process.h> |
| 35 |
#endif |
| 36 |
#include <errno.h> |
| 37 |
#include <fcntl.h> |
| 38 |
#if defined(XP_WIN) |
| 39 |
# include <io.h> /* for isatty() */ |
| 40 |
#endif |
| 41 |
#include <locale.h> |
| 42 |
#if defined(MALLOC_H) |
| 43 |
# include MALLOC_H /* for malloc_usable_size, malloc_size, _msize */ |
| 44 |
#endif |
| 45 |
#include <ctime> |
| 46 |
#include <math.h> |
| 47 |
#ifndef __wasi__ |
| 48 |
# include <signal.h> |
| 49 |
#endif |
| 50 |
#include <stdio.h> |
| 51 |
#include <stdlib.h> |
| 52 |
#include <string.h> |
| 53 |
#include <sys/stat.h> |
| 54 |
#include <sys/types.h> |
| 55 |
#include <utility> |
| 56 |
#ifdef XP_UNIX |
| 57 |
# ifndef __wasi__ |
| 58 |
# include <sys/mman.h> |
| 59 |
# include <sys/wait.h> |
| 60 |
# endif |
| 61 |
# include <sys/stat.h> |
| 62 |
# include <unistd.h> |
| 63 |
#endif |
| 64 |
#ifdef XP_LINUX |
| 65 |
# include <sys/prctl.h> |
| 66 |
#endif |
| 67 |
|
| 68 |
#include "jsapi.h" |
| 69 |
#include "jsfriendapi.h" |
| 70 |
#include "jstypes.h" |
| 71 |
#include "fmt/format.h" |
| 72 |
#ifndef JS_WITHOUT_NSPR |
| 73 |
# include "prerror.h" |
| 74 |
# include "prlink.h" |
| 75 |
#endif |
| 76 |
|
| 77 |
#include "builtin/Array.h" |
| 78 |
#include "builtin/MapObject.h" |
| 79 |
#include "builtin/ModuleObject.h" |
| 80 |
#include "builtin/RegExp.h" |
| 81 |
#include "builtin/TestingFunctions.h" |
| 82 |
#include "builtin/TestingUtility.h" // js::ParseCompileOptions, js::ParseDebugMetadata, js::CreateScriptPrivate |
| 83 |
#include "debugger/DebugAPI.h" |
| 84 |
#include "frontend/CompilationStencil.h" |
| 85 |
#include "frontend/FrontendContext.h" // AutoReportFrontendContext |
| 86 |
#include "frontend/ModuleSharedContext.h" |
| 87 |
#include "frontend/Parser.h" |
| 88 |
#include "frontend/ScopeBindingCache.h" // js::frontend::ScopeBindingCache |
| 89 |
#include "gc/GC.h" |
| 90 |
#include "gc/PublicIterators.h" |
| 91 |
#ifdef DEBUG |
| 92 |
# include "irregexp/RegExpAPI.h" |
| 93 |
#endif |
| 94 |
|
| 95 |
#ifdef JS_SIMULATOR_ARM |
| 96 |
# include "jit/arm/Simulator-arm.h" |
| 97 |
#endif |
| 98 |
#ifdef JS_SIMULATOR_MIPS64 |
| 99 |
# include "jit/mips64/Simulator-mips64.h" |
| 100 |
#endif |
| 101 |
#ifdef JS_SIMULATOR_LOONG64 |
| 102 |
# include "jit/loong64/Simulator-loong64.h" |
| 103 |
#endif |
| 104 |
#ifdef JS_SIMULATOR_RISCV64 |
| 105 |
# include "jit/riscv64/Simulator-riscv64.h" |
| 106 |
#endif |
| 107 |
#include "jit/BaselineCompileQueue.h" |
| 108 |
#include "jit/CacheIRHealth.h" |
| 109 |
#include "jit/InlinableNatives.h" |
| 110 |
#include "jit/Ion.h" |
| 111 |
#include "jit/JitcodeMap.h" |
| 112 |
#include "jit/JitZone.h" |
| 113 |
#include "jit/shared/CodeGenerator-shared.h" |
| 114 |
#include "js/Array.h" // JS::NewArrayObject |
| 115 |
#include "js/ArrayBuffer.h" // JS::{CreateMappedArrayBufferContents,NewMappedArrayBufferWithContents,IsArrayBufferObject,GetArrayBufferLengthAndData} |
| 116 |
#include "js/BuildId.h" // JS::BuildIdCharVector, JS::SetProcessBuildIdOp |
| 117 |
#include "js/CallAndConstruct.h" // JS::Call, JS::IsCallable, JS_CallFunction, JS_CallFunctionValue |
| 118 |
#include "js/CharacterEncoding.h" // JS::StringIsASCII |
| 119 |
#include "js/CompilationAndEvaluation.h" |
| 120 |
#include "js/CompileOptions.h" // JS::ReadOnlyCompileOptions, JS::CompileOptions, JS::OwningCompileOptions, JS::DecodeOptions, JS::InstantiateOptions |
| 121 |
#include "js/ContextOptions.h" // JS::ContextOptions{,Ref} |
| 122 |
#include "js/Debug.h" // JS::dbg::ShouldAvoidSideEffects, JS::ExecutionTrace |
| 123 |
#include "js/EnvironmentChain.h" // JS::EnvironmentChain |
| 124 |
#include "js/Equality.h" // JS::SameValue |
| 125 |
#include "js/ErrorReport.h" // JS::PrintError |
| 126 |
#include "js/Exception.h" // JS::StealPendingExceptionStack |
| 127 |
#include "js/experimental/BindingAllocs.h" // JS_NewObjectWithGivenProtoAndUseAllocSite |
| 128 |
#include "js/experimental/CodeCoverage.h" // js::EnableCodeCoverage |
| 129 |
#include "js/experimental/CompileScript.h" // JS::NewFrontendContext, JS::DestroyFrontendContext, JS::HadFrontendErrors, JS::ConvertFrontendErrorsToRuntimeErrors, JS::CompileGlobalScriptToStencil, JS::CompileModuleScriptToStencil |
| 130 |
#include "js/experimental/CTypes.h" // JS::InitCTypesClass |
| 131 |
#include "js/experimental/Intl.h" // JS::AddMoz{DateTimeFormat,DisplayNames}Constructor |
| 132 |
#include "js/experimental/JitInfo.h" // JSJit{Getter,Setter,Method}CallArgs, JSJitGetterInfo, JSJit{Getter,Setter}Op, JSJitInfo |
| 133 |
#include "js/experimental/JSStencil.h" // JS::Stencil, JS::DecodeStencil, JS::InstantiateModuleStencil |
| 134 |
#include "js/experimental/SourceHook.h" // js::{Set,Forget,}SourceHook |
| 135 |
#include "js/experimental/TypedData.h" // JS_NewUint8Array |
| 136 |
#include "js/friend/DumpFunctions.h" // JS::FormatStackDump |
| 137 |
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_* |
| 138 |
#include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit |
| 139 |
#include "js/friend/WindowProxy.h" // js::IsWindowProxy, js::SetWindowProxyClass, js::ToWindowProxyIfWindow, js::ToWindowIfWindowProxy |
| 140 |
#include "js/GCAPI.h" // JS::AutoCheckCannotGC |
| 141 |
#include "js/GCVector.h" |
| 142 |
#include "js/GlobalObject.h" |
| 143 |
#include "js/Initialization.h" |
| 144 |
#include "js/Interrupt.h" |
| 145 |
#include "js/JSON.h" |
| 146 |
#include "js/MemoryCallbacks.h" |
| 147 |
#include "js/MemoryFunctions.h" |
| 148 |
#include "js/Modules.h" // JS::GetModulePrivate, JS::SetModule{DynamicImport,Metadata,Resolve}Hook, JS::SetModulePrivate, JS::CompileModule |
| 149 |
#include "js/Object.h" // JS::GetClass, JS::GetCompartment, JS::GetReservedSlot, JS::SetReservedSlot |
| 150 |
#include "js/Prefs.h" |
| 151 |
#include "js/Principals.h" |
| 152 |
#include "js/Printer.h" // QuoteString |
| 153 |
#include "js/Printf.h" |
| 154 |
#include "js/PropertyAndElement.h" // JS_DefineElement, JS_DefineFunction, JS_DefineFunctions, JS_DefineProperties, JS_DefineProperty, JS_GetElement, JS_GetProperty, JS_GetPropertyById, JS_HasProperty, JS_SetElement, JS_SetProperty, JS_SetPropertyById |
| 155 |
#include "js/PropertySpec.h" |
| 156 |
#include "js/Realm.h" |
| 157 |
#include "js/RegExp.h" // JS::ObjectIsRegExp |
| 158 |
#include "js/ScriptPrivate.h" |
| 159 |
#include "js/SourceText.h" // JS::SourceText |
| 160 |
#include "js/StableStringChars.h" |
| 161 |
#include "js/Stack.h" |
| 162 |
#include "js/StreamConsumer.h" |
| 163 |
#include "js/StructuredClone.h" |
| 164 |
#include "js/SweepingAPI.h" |
| 165 |
#include "js/Transcoding.h" // JS::TranscodeBuffer, JS::TranscodeRange, JS::IsTranscodeFailureResult |
| 166 |
#include "js/Warnings.h" // JS::SetWarningReporter |
| 167 |
#include "js/WasmFeatures.h" // JS_FOR_WASM_FEATURES |
| 168 |
#include "js/WasmModule.h" // JS::WasmModule |
| 169 |
#include "js/Wrapper.h" |
| 170 |
#include "proxy/DeadObjectProxy.h" // js::IsDeadProxyObject |
| 171 |
#include "shell/jsoptparse.h" |
| 172 |
#include "shell/jsshell.h" |
| 173 |
#include "shell/OSObject.h" |
| 174 |
#include "shell/ShellModuleObjectWrapper.h" |
| 175 |
#include "shell/WasmTesting.h" |
| 176 |
#include "threading/ConditionVariable.h" |
| 177 |
#include "threading/ExclusiveData.h" |
| 178 |
#include "threading/LockGuard.h" |
| 179 |
#include "threading/Thread.h" |
| 180 |
#include "util/CompleteFile.h" // js::FileContents, js::ReadCompleteFile |
| 181 |
#include "util/DifferentialTesting.h" |
| 182 |
#include "util/StringBuilder.h" |
| 183 |
#include "util/Text.h" |
| 184 |
#include "util/WindowsWrapper.h" |
| 185 |
#include "vm/ArgumentsObject.h" |
| 186 |
#include "vm/Compression.h" |
| 187 |
#include "vm/ErrorObject.h" |
| 188 |
#include "vm/ErrorReporting.h" |
| 189 |
#include "vm/HelperThreads.h" |
| 190 |
#include "vm/JSAtomUtils.h" // AtomizeUTF8Chars, AtomizeString, ToAtom |
| 191 |
#include "vm/JSContext.h" |
| 192 |
#include "vm/JSFunction.h" |
| 193 |
#include "vm/JSObject.h" |
| 194 |
#include "vm/JSScript.h" |
| 195 |
#include "vm/Logging.h" |
| 196 |
#include "vm/ModuleBuilder.h" // js::ModuleBuilder |
| 197 |
#include "vm/Modules.h" |
| 198 |
#include "vm/Monitor.h" |
| 199 |
#include "vm/MutexIDs.h" |
| 200 |
#include "vm/PromiseObject.h" // js::PromiseObject |
| 201 |
#include "vm/Shape.h" |
| 202 |
#include "vm/SharedArrayObject.h" |
| 203 |
#include "vm/StencilObject.h" // js::StencilObject |
| 204 |
#include "vm/Time.h" |
| 205 |
#include "vm/ToSource.h" // js::ValueToSource |
| 206 |
#include "vm/TypedArrayObject.h" |
| 207 |
#include "vm/WrapperObject.h" |
| 208 |
#include "wasm/WasmFeatures.h" |
| 209 |
#include "wasm/WasmJS.h" |
| 210 |
|
| 211 |
#include "vm/Compartment-inl.h" |
| 212 |
#include "vm/ErrorObject-inl.h" |
| 213 |
#include "vm/Interpreter-inl.h" |
| 214 |
#include "vm/JSObject-inl.h" |
| 215 |
#include "vm/Realm-inl.h" |
| 216 |
#include "vm/Stack-inl.h" |
| 217 |
|
| 218 |
#undef compress |
| 219 |
|
| 220 |
using namespace js; |
| 221 |
using namespace js::cli; |
| 222 |
using namespace js::shell; |
| 223 |
|
| 224 |
using JS::AutoStableStringChars; |
| 225 |
using JS::CompileOptions; |
| 226 |
|
| 227 |
using js::shell::RCFile; |
| 228 |
|
| 229 |
using mozilla::ArrayEqual; |
| 230 |
using mozilla::AsVariant; |
| 231 |
using mozilla::Atomic; |
| 232 |
using mozilla::MakeScopeExit; |
| 233 |
using mozilla::Maybe; |
| 234 |
using mozilla::Nothing; |
| 235 |
using mozilla::NumberEqualsInt32; |
| 236 |
using mozilla::TimeDuration; |
| 237 |
using mozilla::TimeStamp; |
| 238 |
using mozilla::Utf8Unit; |
| 239 |
using mozilla::Variant; |
| 240 |
|
| 241 |
bool InitOptionParser(OptionParser& op); |
| 242 |
bool SetGlobalOptionsPreJSInit(const OptionParser& op); |
| 243 |
bool SetGlobalOptionsPostJSInit(const OptionParser& op); |
| 244 |
bool SetContextOptions(JSContext* cx, const OptionParser& op); |
| 245 |
bool SetContextWasmOptions(JSContext* cx, const OptionParser& op); |
| 246 |
bool SetContextJITOptions(JSContext* cx, const OptionParser& op); |
| 247 |
bool SetContextGCOptions(JSContext* cx, const OptionParser& op); |
| 248 |
bool InitModuleLoader(JSContext* cx, const OptionParser& op); |
| 249 |
|
| 250 |
#ifdef FUZZING_JS_FUZZILLI |
| 251 |
# define REPRL_CRFD 100 |
| 252 |
# define REPRL_CWFD 101 |
| 253 |
# define REPRL_DRFD 102 |
| 254 |
# define REPRL_DWFD 103 |
| 255 |
|
| 256 |
# define SHM_SIZE 0x100000 |
| 257 |
# define MAX_EDGES ((SHM_SIZE - 4) * 8) |
| 258 |
|
| 259 |
struct shmem_data { |
| 260 |
uint32_t num_edges; |
| 261 |
unsigned char edges[]; |
| 262 |
}; |
| 263 |
|
| 264 |
struct shmem_data* __shmem; |
| 265 |
|
| 266 |
uint32_t *__edges_start, *__edges_stop; |
| 267 |
void __sanitizer_cov_reset_edgeguards() { |
| 268 |
uint64_t N = 0; |
| 269 |
for (uint32_t* x = __edges_start; x < __edges_stop && N < MAX_EDGES; x++) |
| 270 |
*x = ++N; |
| 271 |
} |
| 272 |
|
| 273 |
extern "C" void __sanitizer_cov_trace_pc_guard_init(uint32_t* start, |
| 274 |
uint32_t* stop) { |
| 275 |
// Avoid duplicate initialization |
| 276 |
if (start == stop || *start) return; |
| 277 |
|
| 278 |
if (__edges_start != NULL || __edges_stop != NULL) { |
| 279 |
fprintf(stderr, |
| 280 |
"Coverage instrumentation is only supported for a single module\n"); |
| 281 |
_exit(-1); |
| 282 |
} |
| 283 |
|
| 284 |
__edges_start = start; |
| 285 |
__edges_stop = stop; |
| 286 |
|
| 287 |
// Map the shared memory region |
| 288 |
const char* shm_key = getenv("SHM_ID"); |
| 289 |
if (!shm_key) { |
| 290 |
puts("[COV] no shared memory bitmap available, skipping"); |
| 291 |
__shmem = (struct shmem_data*)malloc(SHM_SIZE); |
| 292 |
} else { |
| 293 |
int fd = shm_open(shm_key, O_RDWR, S_IREAD | S_IWRITE); |
| 294 |
if (fd <= -1) { |
| 295 |
fprintf(stderr, "Failed to open shared memory region: %s\n", |
| 296 |
strerror(errno)); |
| 297 |
_exit(-1); |
| 298 |
} |
| 299 |
|
| 300 |
__shmem = (struct shmem_data*)mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, |
| 301 |
MAP_SHARED, fd, 0); |
| 302 |
if (__shmem == MAP_FAILED) { |
| 303 |
fprintf(stderr, "Failed to mmap shared memory region\n"); |
| 304 |
_exit(-1); |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
__sanitizer_cov_reset_edgeguards(); |
| 309 |
|
| 310 |
__shmem->num_edges = stop - start; |
| 311 |
printf("[COV] edge counters initialized. Shared memory: %s with %u edges\n", |
| 312 |
shm_key, __shmem->num_edges); |
| 313 |
} |
| 314 |
|
| 315 |
extern "C" void __sanitizer_cov_trace_pc_guard(uint32_t* guard) { |
| 316 |
// There's a small race condition here: if this function executes in two |
| 317 |
// threads for the same edge at the same time, the first thread might disable |
| 318 |
// the edge (by setting the guard to zero) before the second thread fetches |
| 319 |
// the guard value (and thus the index). However, our instrumentation ignores |
| 320 |
// the first edge (see libcoverage.c) and so the race is unproblematic. |
| 321 |
uint32_t index = *guard; |
| 322 |
// If this function is called before coverage instrumentation is properly |
| 323 |
// initialized we want to return early. |
| 324 |
if (!index) return; |
| 325 |
__shmem->edges[index / 8] |= 1 << (index % 8); |
| 326 |
*guard = 0; |
| 327 |
} |
| 328 |
#endif /* FUZZING_JS_FUZZILLI */ |
| 329 |
|
| 330 |
enum JSShellExitCode { |
| 331 |
EXITCODE_RUNTIME_ERROR = 3, |
| 332 |
EXITCODE_FILE_NOT_FOUND = 4, |
| 333 |
EXITCODE_OUT_OF_MEMORY = 5, |
| 334 |
EXITCODE_TIMEOUT = 6 |
| 335 |
}; |
| 336 |
|
| 337 |
struct ShellLogModule { |
| 338 |
// Since ShellLogModules have references to their levels created |
| 339 |
// we can't move them. |
| 340 |
ShellLogModule(ShellLogModule&&) = delete; |
| 341 |
|
| 342 |
const char* name; |
| 343 |
explicit ShellLogModule(const char* name) : name(name) {} |
| 344 |
mozilla::AtomicLogLevel level; |
| 345 |
}; |
| 346 |
|
| 347 |
// If asserts related to this ever fail, simply bump this number. |
| 348 |
// |
| 349 |
// This is used to construct a mozilla::Array, which is used because a |
| 350 |
// ShellLogModule cannot move once constructed to avoid invalidating |
| 351 |
// a levelRef. |
| 352 |
static const int MAX_LOG_MODULES = 64; |
| 353 |
static int initialized_modules = 0; |
| 354 |
mozilla::Array<mozilla::Maybe<ShellLogModule>, MAX_LOG_MODULES> logModules; |
| 355 |
|
| 356 |
JS::OpaqueLogger GetLoggerByName(const char* name) { |
| 357 |
// Check for pre-existing module |
| 358 |
for (auto& logger : logModules) { |
| 359 |
if (logger) { |
| 360 |
if (logger->name == name) { |
| 361 |
return logger.ptr(); |
| 362 |
} |
| 363 |
} |
| 364 |
// We've seen all initialized, not there, break out. |
| 365 |
if (!logger) break; |
| 366 |
} |
| 367 |
|
| 368 |
// Not found, allocate a new module. |
| 369 |
MOZ_RELEASE_ASSERT(initialized_modules < MAX_LOG_MODULES - 1); |
| 370 |
auto index = initialized_modules++; |
| 371 |
logModules[index].emplace(name); |
| 372 |
return logModules[index].ptr(); |
| 373 |
} |
| 374 |
|
| 375 |
mozilla::AtomicLogLevel& GetLevelRef(JS::OpaqueLogger logger) { |
| 376 |
ShellLogModule* slm = static_cast<ShellLogModule*>(logger); |
| 377 |
return slm->level; |
| 378 |
} |
| 379 |
|
| 380 |
void LogPrintVA(const JS::OpaqueLogger logger, mozilla::LogLevel level, |
| 381 |
const char* fmt, va_list ap) { |
| 382 |
ShellLogModule* mod = static_cast<ShellLogModule*>(logger); |
| 383 |
fprintf(stderr, "[%s] ", mod->name); |
| 384 |
vfprintf(stderr, fmt, ap); |
| 385 |
fprintf(stderr, "\n"); |
| 386 |
} |
| 387 |
|
| 388 |
void LogPrintFmt(const JS::OpaqueLogger logger, mozilla::LogLevel level, |
| 389 |
fmt::string_view fmt, fmt::format_args args) { |
| 390 |
ShellLogModule* mod = static_cast<ShellLogModule*>(logger); |
| 391 |
fmt::print(stderr, FMT_STRING("[{}] {}\n"), mod->name, |
| 392 |
fmt::vformat(fmt, args)); |
| 393 |
} |
| 394 |
|
| 395 |
JS::LoggingInterface shellLoggingInterface = {GetLoggerByName, LogPrintVA, |
| 396 |
LogPrintFmt, GetLevelRef}; |
| 397 |
|
| 398 |
static void ToLower(const char* src, char* dest, size_t len) { |
| 399 |
for (size_t c = 0; c < len; c++) { |
| 400 |
dest[c] = (char)(tolower(src[c])); |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
// Run this after initialiation! |
| 405 |
void ParseLoggerOptions() { |
| 406 |
char* mixedCaseOpts = getenv("MOZ_LOG"); |
| 407 |
if (!mixedCaseOpts) { |
| 408 |
return; |
| 409 |
} |
| 410 |
|
| 411 |
// Copy into a new buffer and lower case to do case insensitive matching. |
| 412 |
// |
| 413 |
// Done this way rather than just using strcasestr because Windows doesn't |
| 414 |
// have strcasestr as part of its base C library. |
| 415 |
size_t len = strlen(mixedCaseOpts); |
| 416 |
mozilla::UniqueFreePtr<char[]> logOpts( |
| 417 |
static_cast<char*>(calloc(len + 1, 1))); |
| 418 |
if (!logOpts) { |
| 419 |
return; |
| 420 |
} |
| 421 |
|
| 422 |
ToLower(mixedCaseOpts, logOpts.get(), len); |
| 423 |
|
| 424 |
// This is a really permissive parser, but will suffice! |
| 425 |
for (auto& logger : logModules) { |
| 426 |
if (logger) { |
| 427 |
// Lowercase the logger name for strstr |
| 428 |
size_t len = strlen(logger->name); |
| 429 |
mozilla::UniqueFreePtr<char[]> lowerName( |
| 430 |
static_cast<char*>(calloc(len + 1, 1))); |
| 431 |
ToLower(logger->name, lowerName.get(), len); |
| 432 |
|
| 433 |
if (char* needle = strstr(logOpts.get(), lowerName.get())) { |
| 434 |
// If the string to enable a logger is present, but no level is provided |
| 435 |
// then default to Debug level. |
| 436 |
int logLevel = static_cast<int>(mozilla::LogLevel::Debug); |
| 437 |
|
| 438 |
if (char* colon = strchr(needle, ':')) { |
| 439 |
// Parse character after colon as log level. |
| 440 |
if (*(colon + 1)) { |
| 441 |
logLevel = atoi(colon + 1); |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
fprintf(stderr, "[JS_LOG] Enabling Logger %s at level %d\n", |
| 446 |
logger->name, logLevel); |
| 447 |
logger->level = mozilla::ToLogLevel(logLevel); |
| 448 |
} |
| 449 |
} |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
/* |
| 454 |
* Limit the timeout to 30 minutes to prevent an overflow on platfoms |
| 455 |
* that represent the time internally in microseconds using 32-bit int. |
| 456 |
*/ |
| 457 |
static const double MAX_TIMEOUT_SECONDS = 1800.0; |
| 458 |
|
| 459 |
// Not necessarily in sync with the browser |
| 460 |
#ifdef ENABLE_SHARED_MEMORY |
| 461 |
# define SHARED_MEMORY_DEFAULT 1 |
| 462 |
#else |
| 463 |
# define SHARED_MEMORY_DEFAULT 0 |
| 464 |
#endif |
| 465 |
|
| 466 |
// Fuzzing support for JS runtime fuzzing |
| 467 |
#ifdef FUZZING_INTERFACES |
| 468 |
# include "shell/jsrtfuzzing/jsrtfuzzing.h" |
| 469 |
MOZ_RUNINIT static bool fuzzDoDebug = !!getenv("MOZ_FUZZ_DEBUG"); |
| 470 |
MOZ_RUNINIT static bool fuzzHaveModule = !!getenv("FUZZER"); |
| 471 |
#endif // FUZZING_INTERFACES |
| 472 |
|
| 473 |
// Code to support GCOV code coverage measurements on standalone shell |
| 474 |
#ifdef MOZ_CODE_COVERAGE |
| 475 |
# if defined(__GNUC__) && !defined(__clang__) |
| 476 |
extern "C" void __gcov_dump(); |
| 477 |
extern "C" void __gcov_reset(); |
| 478 |
|
| 479 |
void counters_dump(int) { __gcov_dump(); } |
| 480 |
|
| 481 |
void counters_reset(int) { __gcov_reset(); } |
| 482 |
# else |
| 483 |
void counters_dump(int) { /* Do nothing */ } |
| 484 |
|
| 485 |
void counters_reset(int) { /* Do nothing */ } |
| 486 |
# endif |
| 487 |
|
| 488 |
static void InstallCoverageSignalHandlers() { |
| 489 |
# ifndef XP_WIN |
| 490 |
fprintf(stderr, "[CodeCoverage] Setting handlers for process %d.\n", |
| 491 |
getpid()); |
| 492 |
|
| 493 |
struct sigaction dump_sa; |
| 494 |
dump_sa.sa_handler = counters_dump; |
| 495 |
dump_sa.sa_flags = SA_RESTART; |
| 496 |
sigemptyset(&dump_sa.sa_mask); |
| 497 |
mozilla::DebugOnly<int> r1 = sigaction(SIGUSR1, &dump_sa, nullptr); |
| 498 |
MOZ_ASSERT(r1 == 0, "Failed to install GCOV SIGUSR1 handler"); |
| 499 |
|
| 500 |
struct sigaction reset_sa; |
| 501 |
reset_sa.sa_handler = counters_reset; |
| 502 |
reset_sa.sa_flags = SA_RESTART; |
| 503 |
sigemptyset(&reset_sa.sa_mask); |
| 504 |
mozilla::DebugOnly<int> r2 = sigaction(SIGUSR2, &reset_sa, nullptr); |
| 505 |
MOZ_ASSERT(r2 == 0, "Failed to install GCOV SIGUSR2 handler"); |
| 506 |
# endif |
| 507 |
} |
| 508 |
#endif |
| 509 |
|
| 510 |
// An off-thread parse or decode job. |
| 511 |
class js::shell::OffThreadJob { |
| 512 |
static constexpr size_t kCompileStackQuota = 128 * sizeof(size_t) * 1024; |
| 513 |
static constexpr size_t kThreadStackQuota = |
| 514 |
kCompileStackQuota + 128 * sizeof(size_t) * 1024; |
| 515 |
|
| 516 |
enum State { |
| 517 |
RUNNING, // Working; no stencil. |
| 518 |
DONE, // Finished; have stencil. |
| 519 |
CANCELLED // Cancelled due to error. |
| 520 |
}; |
| 521 |
|
| 522 |
public: |
| 523 |
enum class Kind { |
| 524 |
CompileScript, |
| 525 |
CompileModule, |
| 526 |
Decode, |
| 527 |
}; |
| 528 |
|
| 529 |
OffThreadJob(ShellContext* sc, Kind kind, JS::SourceText<char16_t>&& srcBuf); |
| 530 |
OffThreadJob(ShellContext* sc, Kind kind, JS::TranscodeBuffer&& xdrBuf); |
| 531 |
|
| 532 |
~OffThreadJob(); |
| 533 |
|
| 534 |
bool init(JSContext* cx, const JS::ReadOnlyCompileOptions& options); |
| 535 |
bool dispatch(); |
| 536 |
|
| 537 |
static void OffThreadMain(OffThreadJob* self); |
| 538 |
void run(); |
| 539 |
|
| 540 |
void cancel(); |
| 541 |
void waitUntilDone(); |
| 542 |
|
| 543 |
already_AddRefed<JS::Stencil> stealStencil(JSContext* cx); |
| 544 |
|
| 545 |
public: |
| 546 |
const int32_t id; |
| 547 |
|
| 548 |
private: |
| 549 |
Kind kind_; |
| 550 |
State state_; |
| 551 |
|
| 552 |
JS::FrontendContext* fc_ = nullptr; |
| 553 |
JS::OwningCompileOptions options_; |
| 554 |
|
| 555 |
UniquePtr<Thread> thread_; |
| 556 |
|
| 557 |
JS::SourceText<char16_t> srcBuf_; |
| 558 |
JS::TranscodeBuffer xdrBuf_; |
| 559 |
|
| 560 |
RefPtr<JS::Stencil> stencil_; |
| 561 |
|
| 562 |
JS::TranscodeResult transcodeResult_ = JS::TranscodeResult::Ok; |
| 563 |
}; |
| 564 |
|
| 565 |
template <typename T> |
| 566 |
static OffThreadJob* NewOffThreadJob(JSContext* cx, OffThreadJob::Kind kind, |
| 567 |
JS::ReadOnlyCompileOptions& options, |
| 568 |
T&& source) { |
| 569 |
ShellContext* sc = GetShellContext(cx); |
| 570 |
if (sc->isWorker) { |
| 571 |
// Off-thread compilation/decode is used by main-thread, in order to improve |
| 572 |
// the responsiveness. It's not used by worker in browser, and there's not |
| 573 |
// much reason to support worker here. |
| 574 |
JS_ReportErrorASCII(cx, "Off-thread job is not supported in worker"); |
| 575 |
return nullptr; |
| 576 |
} |
| 577 |
|
| 578 |
UniquePtr<OffThreadJob> job( |
| 579 |
cx->new_<OffThreadJob>(sc, kind, std::move(source))); |
| 580 |
if (!job) { |
| 581 |
return nullptr; |
| 582 |
} |
| 583 |
|
| 584 |
if (!job->init(cx, options)) { |
| 585 |
return nullptr; |
| 586 |
} |
| 587 |
|
| 588 |
if (!sc->offThreadJobs.append(job.get())) { |
| 589 |
job->cancel(); |
| 590 |
JS_ReportErrorASCII(cx, "OOM adding off-thread job"); |
| 591 |
return nullptr; |
| 592 |
} |
| 593 |
|
| 594 |
return job.release(); |
| 595 |
} |
| 596 |
|
| 597 |
static OffThreadJob* GetSingleOffThreadJob(JSContext* cx) { |
| 598 |
ShellContext* sc = GetShellContext(cx); |
| 599 |
const auto& jobs = sc->offThreadJobs; |
| 600 |
if (jobs.empty()) { |
| 601 |
JS_ReportErrorASCII(cx, "No off-thread jobs are pending"); |
| 602 |
return nullptr; |
| 603 |
} |
| 604 |
|
| 605 |
if (jobs.length() > 1) { |
| 606 |
JS_ReportErrorASCII( |
| 607 |
cx, "Multiple off-thread jobs are pending: must specify job ID"); |
| 608 |
return nullptr; |
| 609 |
} |
| 610 |
|
| 611 |
return jobs[0]; |
| 612 |
} |
| 613 |
|
| 614 |
static OffThreadJob* LookupOffThreadJobByID(JSContext* cx, int32_t id) { |
| 615 |
if (id <= 0) { |
| 616 |
JS_ReportErrorASCII(cx, "Bad off-thread job ID"); |
| 617 |
return nullptr; |
| 618 |
} |
| 619 |
|
| 620 |
ShellContext* sc = GetShellContext(cx); |
| 621 |
const auto& jobs = sc->offThreadJobs; |
| 622 |
if (jobs.empty()) { |
| 623 |
JS_ReportErrorASCII(cx, "No off-thread jobs are pending"); |
| 624 |
return nullptr; |
| 625 |
} |
| 626 |
|
| 627 |
OffThreadJob* job = nullptr; |
| 628 |
for (auto someJob : jobs) { |
| 629 |
if (someJob->id == id) { |
| 630 |
job = someJob; |
| 631 |
break; |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
if (!job) { |
| 636 |
JS_ReportErrorASCII(cx, "Off-thread job not found"); |
| 637 |
return nullptr; |
| 638 |
} |
| 639 |
|
| 640 |
return job; |
| 641 |
} |
| 642 |
|
| 643 |
static OffThreadJob* LookupOffThreadJobForArgs(JSContext* cx, |
| 644 |
const CallArgs& args, |
| 645 |
size_t arg) { |
| 646 |
// If the optional ID argument isn't present, get the single pending job. |
| 647 |
if (args.length() <= arg) { |
| 648 |
return GetSingleOffThreadJob(cx); |
| 649 |
} |
| 650 |
|
| 651 |
// Lookup the job using the specified ID. |
| 652 |
int32_t id = 0; |
| 653 |
RootedValue value(cx, args[arg]); |
| 654 |
if (!ToInt32(cx, value, &id)) { |
| 655 |
return nullptr; |
| 656 |
} |
| 657 |
|
| 658 |
return LookupOffThreadJobByID(cx, id); |
| 659 |
} |
| 660 |
|
| 661 |
static void DeleteOffThreadJob(JSContext* cx, OffThreadJob* job) { |
| 662 |
ShellContext* sc = GetShellContext(cx); |
| 663 |
for (size_t i = 0; i < sc->offThreadJobs.length(); i++) { |
| 664 |
if (sc->offThreadJobs[i] == job) { |
| 665 |
sc->offThreadJobs.erase(&sc->offThreadJobs[i]); |
| 666 |
js_delete(job); |
| 667 |
return; |
| 668 |
} |
| 669 |
} |
| 670 |
|
| 671 |
MOZ_CRASH("Off-thread job not found"); |
| 672 |
} |
| 673 |
|
| 674 |
static void CancelOffThreadJobsForRuntime(JSContext* cx) { |
| 675 |
ShellContext* sc = GetShellContext(cx); |
| 676 |
while (!sc->offThreadJobs.empty()) { |
| 677 |
OffThreadJob* job = sc->offThreadJobs.popCopy(); |
| 678 |
job->waitUntilDone(); |
| 679 |
js_delete(job); |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
mozilla::Atomic<int32_t> gOffThreadJobSerial(1); |
| 684 |
|
| 685 |
OffThreadJob::OffThreadJob(ShellContext* sc, Kind kind, |
| 686 |
JS::SourceText<char16_t>&& srcBuf) |
| 687 |
: id(gOffThreadJobSerial++), |
| 688 |
kind_(kind), |
| 689 |
state_(RUNNING), |
| 690 |
options_(JS::OwningCompileOptions::ForFrontendContext()), |
| 691 |
srcBuf_(std::move(srcBuf)) { |
| 692 |
MOZ_RELEASE_ASSERT(id > 0, "Off-thread job IDs exhausted"); |
| 693 |
} |
| 694 |
|
| 695 |
OffThreadJob::OffThreadJob(ShellContext* sc, Kind kind, |
| 696 |
JS::TranscodeBuffer&& xdrBuf) |
| 697 |
: id(gOffThreadJobSerial++), |
| 698 |
kind_(kind), |
| 699 |
state_(RUNNING), |
| 700 |
options_(JS::OwningCompileOptions::ForFrontendContext()), |
| 701 |
xdrBuf_(std::move(xdrBuf)) { |
| 702 |
MOZ_RELEASE_ASSERT(id > 0, "Off-thread job IDs exhausted"); |
| 703 |
} |
| 704 |
|
| 705 |
OffThreadJob::~OffThreadJob() { |
| 706 |
if (fc_) { |
| 707 |
JS::DestroyFrontendContext(fc_); |
| 708 |
} |
| 709 |
MOZ_ASSERT(state_ != RUNNING); |
| 710 |
} |
| 711 |
|
| 712 |
bool OffThreadJob::init(JSContext* cx, |
| 713 |
const JS::ReadOnlyCompileOptions& options) { |
| 714 |
fc_ = JS::NewFrontendContext(); |
| 715 |
if (!fc_) { |
| 716 |
ReportOutOfMemory(cx); |
| 717 |
state_ = CANCELLED; |
| 718 |
return false; |
| 719 |
} |
| 720 |
|
| 721 |
if (!options_.copy(cx, options)) { |
| 722 |
state_ = CANCELLED; |
| 723 |
return false; |
| 724 |
} |
| 725 |
|
| 726 |
return true; |
| 727 |
} |
| 728 |
|
| 729 |
bool OffThreadJob::dispatch() { |
| 730 |
thread_ = |
| 731 |
js::MakeUnique<Thread>(Thread::Options().setStackSize(kThreadStackQuota)); |
| 732 |
if (!thread_) { |
| 733 |
state_ = CANCELLED; |
| 734 |
return false; |
| 735 |
} |
| 736 |
|
| 737 |
if (!thread_->init(OffThreadJob::OffThreadMain, this)) { |
| 738 |
state_ = CANCELLED; |
| 739 |
thread_ = nullptr; |
| 740 |
return false; |
| 741 |
} |
| 742 |
|
| 743 |
return true; |
| 744 |
} |
| 745 |
|
| 746 |
/* static */ void OffThreadJob::OffThreadMain(OffThreadJob* self) { |
| 747 |
self->run(); |
| 748 |
} |
| 749 |
|
| 750 |
void OffThreadJob::run() { |
| 751 |
MOZ_ASSERT(state_ == RUNNING); |
| 752 |
MOZ_ASSERT(!stencil_); |
| 753 |
|
| 754 |
JS::SetNativeStackQuota(fc_, kCompileStackQuota); |
| 755 |
|
| 756 |
switch (kind_) { |
| 757 |
case Kind::CompileScript: { |
| 758 |
stencil_ = JS::CompileGlobalScriptToStencil(fc_, options_, srcBuf_); |
| 759 |
break; |
| 760 |
} |
| 761 |
case Kind::CompileModule: { |
| 762 |
stencil_ = JS::CompileModuleScriptToStencil(fc_, options_, srcBuf_); |
| 763 |
break; |
| 764 |
} |
| 765 |
case Kind::Decode: { |
| 766 |
JS::DecodeOptions decodeOptions(options_); |
| 767 |
JS::TranscodeRange range(xdrBuf_.begin(), xdrBuf_.length()); |
| 768 |
transcodeResult_ = JS::DecodeStencil(fc_, decodeOptions, range, |
| 769 |
getter_AddRefs(stencil_)); |
| 770 |
break; |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
state_ = DONE; |
| 775 |
} |
| 776 |
|
| 777 |
void OffThreadJob::cancel() { |
| 778 |
MOZ_ASSERT(state_ == RUNNING); |
| 779 |
MOZ_ASSERT(!stencil_); |
| 780 |
MOZ_ASSERT(!thread_, "cannot cancel after starting a thread"); |
| 781 |
|
| 782 |
state_ = CANCELLED; |
| 783 |
} |
| 784 |
|
| 785 |
void OffThreadJob::waitUntilDone() { |
| 786 |
MOZ_ASSERT(state_ != CANCELLED); |
| 787 |
thread_->join(); |
| 788 |
} |
| 789 |
|
| 790 |
already_AddRefed<JS::Stencil> OffThreadJob::stealStencil(JSContext* cx) { |
| 791 |
JS::FrontendContext* fc = fc_; |
| 792 |
fc_ = nullptr; |
| 793 |
auto destroyFrontendContext = |
| 794 |
mozilla::MakeScopeExit([&]() { JS::DestroyFrontendContext(fc); }); |
| 795 |
|
| 796 |
MOZ_ASSERT(fc); |
| 797 |
|
| 798 |
if (JS::HadFrontendErrors(fc)) { |
| 799 |
(void)JS::ConvertFrontendErrorsToRuntimeErrors(cx, fc, options_); |
| 800 |
return nullptr; |
| 801 |
} |
| 802 |
|
| 803 |
if (!stencil_ && JS::IsTranscodeFailureResult(transcodeResult_)) { |
| 804 |
JS_ReportErrorASCII(cx, "failed to decode cache"); |
| 805 |
return nullptr; |
| 806 |
} |
| 807 |
|
| 808 |
// Report warnings. |
| 809 |
if (!JS::ConvertFrontendErrorsToRuntimeErrors(cx, fc, options_)) { |
| 810 |
return nullptr; |
| 811 |
} |
| 812 |
|
| 813 |
return stencil_.forget(); |
| 814 |
} |
| 815 |
|
| 816 |
struct ShellCompartmentPrivate { |
| 817 |
GCPtr<ArrayObject*> blackRoot; |
| 818 |
GCPtr<ArrayObject*> grayRoot; |
| 819 |
}; |
| 820 |
|
| 821 |
struct MOZ_STACK_CLASS EnvironmentPreparer |
| 822 |
: public js::ScriptEnvironmentPreparer { |
| 823 |
explicit EnvironmentPreparer(JSContext* cx) { |
| 824 |
js::SetScriptEnvironmentPreparer(cx, this); |
| 825 |
} |
| 826 |
void invoke(JS::HandleObject global, Closure& closure) override; |
| 827 |
}; |
| 828 |
|
| 829 |
const char* shell::selfHostedXDRPath = nullptr; |
| 830 |
bool shell::encodeSelfHostedCode = false; |
| 831 |
bool shell::enableCodeCoverage = false; |
| 832 |
bool shell::enableDisassemblyDumps = false; |
| 833 |
bool shell::offthreadBaselineCompilation = false; |
| 834 |
bool shell::offthreadIonCompilation = false; |
| 835 |
JS::DelazificationOption shell::defaultDelazificationMode = |
| 836 |
JS::DelazificationOption::OnDemandOnly; |
| 837 |
bool shell::enableAsmJS = false; |
| 838 |
bool shell::enableWasm = false; |
| 839 |
bool shell::enableSharedMemory = SHARED_MEMORY_DEFAULT; |
| 840 |
bool shell::enableWasmBaseline = false; |
| 841 |
bool shell::enableWasmOptimizing = false; |
| 842 |
bool shell::enableTestWasmAwaitTier2 = false; |
| 843 |
bool shell::enableSourcePragmas = true; |
| 844 |
bool shell::enableAsyncStacks = false; |
| 845 |
bool shell::enableAsyncStackCaptureDebuggeeOnly = false; |
| 846 |
bool shell::enableToSource = false; |
| 847 |
bool shell::enableImportAttributes = false; |
| 848 |
#ifdef JS_GC_ZEAL |
| 849 |
uint32_t shell::gZealBits = 0; |
| 850 |
uint32_t shell::gZealFrequency = 0; |
| 851 |
#endif |
| 852 |
bool shell::printTiming = false; |
| 853 |
RCFile* shell::gErrFile = nullptr; |
| 854 |
RCFile* shell::gOutFile = nullptr; |
| 855 |
bool shell::reportWarnings = true; |
| 856 |
bool shell::compileOnly = false; |
| 857 |
bool shell::disableOOMFunctions = false; |
| 858 |
bool shell::defaultToSameCompartment = true; |
| 859 |
|
| 860 |
#ifdef DEBUG |
| 861 |
bool shell::dumpEntrainedVariables = false; |
| 862 |
bool shell::OOM_printAllocationCount = false; |
| 863 |
#endif |
| 864 |
|
| 865 |
MOZ_RUNINIT UniqueChars shell::processWideModuleLoadPath; |
| 866 |
|
| 867 |
static bool SetTimeoutValue(JSContext* cx, double t); |
| 868 |
|
| 869 |
static void KillWatchdog(JSContext* cx); |
| 870 |
|
| 871 |
static bool ScheduleWatchdog(JSContext* cx, double t); |
| 872 |
|
| 873 |
static void CancelExecution(JSContext* cx); |
| 874 |
|
| 875 |
enum class ShellGlobalKind { |
| 876 |
GlobalObject, |
| 877 |
WindowProxy, |
| 878 |
}; |
| 879 |
|
| 880 |
static JSObject* NewGlobalObject(JSContext* cx, JS::RealmOptions& options, |
| 881 |
JSPrincipals* principals, ShellGlobalKind kind, |
| 882 |
bool immutablePrototype); |
| 883 |
|
| 884 |
/* |
| 885 |
* A toy WindowProxy class for the shell. This is intended for testing code |
| 886 |
* where global |this| is a WindowProxy. All requests are forwarded to the |
| 887 |
* underlying global and no navigation is supported. |
| 888 |
*/ |
| 889 |
const JSClass ShellWindowProxyClass = |
| 890 |
PROXY_CLASS_DEF("ShellWindowProxy", JSCLASS_HAS_RESERVED_SLOTS(1)); |
| 891 |
|
| 892 |
JSObject* NewShellWindowProxy(JSContext* cx, JS::HandleObject global) { |
| 893 |
MOZ_ASSERT(global->is<GlobalObject>()); |
| 894 |
|
| 895 |
js::WrapperOptions options; |
| 896 |
options.setClass(&ShellWindowProxyClass); |
| 897 |
|
| 898 |
JSAutoRealm ar(cx, global); |
| 899 |
JSObject* obj = |
| 900 |
js::Wrapper::New(cx, global, &js::Wrapper::singleton, options); |
| 901 |
MOZ_ASSERT_IF(obj, js::IsWindowProxy(obj)); |
| 902 |
return obj; |
| 903 |
} |
| 904 |
|
| 905 |
/* |
| 906 |
* A toy principals type for the shell. |
| 907 |
* |
| 908 |
* In the shell, a principal is simply a 32-bit mask: P subsumes Q if the |
| 909 |
* set bits in P are a superset of those in Q. Thus, the principal 0 is |
| 910 |
* subsumed by everything, and the principal ~0 subsumes everything. |
| 911 |
* |
| 912 |
* As a special case, a null pointer as a principal is treated like 0xffff. |
| 913 |
* |
| 914 |
* The 'newGlobal' function takes an option indicating which principal the |
| 915 |
* new global should have; 'evaluate' does for the new code. |
| 916 |
*/ |
| 917 |
class ShellPrincipals final : public JSPrincipals { |
| 918 |
uint32_t bits; |
| 919 |
|
| 920 |
static uint32_t getBits(JSPrincipals* p) { |
| 921 |
if (!p) { |
| 922 |
return 0xffff; |
| 923 |
} |
| 924 |
return static_cast<ShellPrincipals*>(p)->bits; |
| 925 |
} |
| 926 |
|
| 927 |
public: |
| 928 |
explicit ShellPrincipals(uint32_t bits, int32_t refcount = 0) : bits(bits) { |
| 929 |
this->refcount = refcount; |
| 930 |
} |
| 931 |
|
| 932 |
bool write(JSContext* cx, JSStructuredCloneWriter* writer) override { |
| 933 |
// The shell doesn't have a read principals hook, so it doesn't really |
| 934 |
// matter what we write here, but we have to write something so the |
| 935 |
// fuzzer is happy. |
| 936 |
return JS_WriteUint32Pair(writer, bits, 0); |
| 937 |
} |
| 938 |
|
| 939 |
bool isSystemOrAddonPrincipal() override { return true; } |
| 940 |
|
| 941 |
static void destroy(JSPrincipals* principals) { |
| 942 |
MOZ_ASSERT(principals != &fullyTrusted); |
| 943 |
MOZ_ASSERT(principals->refcount == 0); |
| 944 |
js_delete(static_cast<const ShellPrincipals*>(principals)); |
| 945 |
} |
| 946 |
|
| 947 |
static bool subsumes(JSPrincipals* first, JSPrincipals* second) { |
| 948 |
uint32_t firstBits = getBits(first); |
| 949 |
uint32_t secondBits = getBits(second); |
| 950 |
return (firstBits | secondBits) == firstBits; |
| 951 |
} |
| 952 |
|
| 953 |
static JSSecurityCallbacks securityCallbacks; |
| 954 |
|
| 955 |
// Fully-trusted principals singleton. |
| 956 |
static ShellPrincipals fullyTrusted; |
| 957 |
}; |
| 958 |
|
| 959 |
JSSecurityCallbacks ShellPrincipals::securityCallbacks = { |
| 960 |
nullptr, // contentSecurityPolicyAllows |
| 961 |
nullptr, // codeForEvalGets |
| 962 |
subsumes}; |
| 963 |
|
| 964 |
// The fully-trusted principal subsumes all other principals. |
| 965 |
MOZ_RUNINIT ShellPrincipals ShellPrincipals::fullyTrusted(-1, 1); |
| 966 |
|
| 967 |
#ifdef EDITLINE |
| 968 |
extern "C" { |
| 969 |
extern MOZ_EXPORT char* readline(const char* prompt); |
| 970 |
extern MOZ_EXPORT void add_history(char* line); |
| 971 |
} // extern "C" |
| 972 |
#endif |
| 973 |
|
| 974 |
ShellContext::ShellContext(JSContext* cx, IsWorkerEnum isWorker_) |
| 975 |
: cx_(nullptr), |
| 976 |
isWorker(isWorker_), |
| 977 |
lastWarningEnabled(false), |
| 978 |
trackUnhandledRejections(true), |
| 979 |
timeoutInterval(-1.0), |
| 980 |
startTime(PRMJ_Now()), |
| 981 |
serviceInterrupt(false), |
| 982 |
haveInterruptFunc(false), |
| 983 |
interruptFunc(cx, NullValue()), |
| 984 |
lastWarning(cx, NullValue()), |
| 985 |
promiseRejectionTrackerCallback(cx, NullValue()), |
| 986 |
unhandledRejectedPromises(cx), |
| 987 |
watchdogLock(mutexid::ShellContextWatchdog), |
| 988 |
exitCode(0), |
| 989 |
quitting(false), |
| 990 |
readLineBufPos(0), |
| 991 |
errFilePtr(nullptr), |
| 992 |
outFilePtr(nullptr), |
| 993 |
offThreadMonitor(mutexid::ShellOffThreadState), |
| 994 |
finalizationRegistryCleanupCallbacks(cx) {} |
| 995 |
|
| 996 |
ShellContext* js::shell::GetShellContext(JSContext* cx) { |
| 997 |
ShellContext* sc = static_cast<ShellContext*>(JS_GetContextPrivate(cx)); |
| 998 |
MOZ_ASSERT(sc); |
| 999 |
return sc; |
| 1000 |
} |
| 1001 |
|
| 1002 |
static void TraceRootArrays(JSTracer* trc, gc::MarkColor color) { |
| 1003 |
JSRuntime* rt = trc->runtime(); |
| 1004 |
for (ZonesIter zone(rt, SkipAtoms); !zone.done(); zone.next()) { |
| 1005 |
for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { |
| 1006 |
auto priv = static_cast<ShellCompartmentPrivate*>( |
| 1007 |
JS_GetCompartmentPrivate(comp.get())); |
| 1008 |
if (!priv) { |
| 1009 |
continue; |
| 1010 |
} |
| 1011 |
|
| 1012 |
GCPtr<ArrayObject*>& array = |
| 1013 |
(color == gc::MarkColor::Black) ? priv->blackRoot : priv->grayRoot; |
| 1014 |
TraceNullableEdge(trc, &array, "shell root array"); |
| 1015 |
|
| 1016 |
if (array) { |
| 1017 |
// Trace the array elements as part of root marking. |
| 1018 |
for (uint32_t i = 0; i < array->getDenseInitializedLength(); i++) { |
| 1019 |
Value& value = const_cast<Value&>(array->getDenseElement(i)); |
| 1020 |
TraceManuallyBarrieredEdge(trc, &value, "shell root array element"); |
| 1021 |
} |
| 1022 |
} |
| 1023 |
} |
| 1024 |
} |
| 1025 |
} |
| 1026 |
|
| 1027 |
static void TraceBlackRoots(JSTracer* trc, void* data) { |
| 1028 |
TraceRootArrays(trc, gc::MarkColor::Black); |
| 1029 |
} |
| 1030 |
|
| 1031 |
static bool TraceGrayRoots(JSTracer* trc, JS::SliceBudget& budget, void* data) { |
| 1032 |
TraceRootArrays(trc, gc::MarkColor::Gray); |
| 1033 |
return true; |
| 1034 |
} |
| 1035 |
|
| 1036 |
static inline JSString* NewStringCopyUTF8(JSContext* cx, const char* chars) { |
| 1037 |
return JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(chars, strlen(chars))); |
| 1038 |
} |
| 1039 |
|
| 1040 |
static mozilla::UniqueFreePtr<char[]> GetLine(FILE* file, const char* prompt) { |
| 1041 |
#ifdef EDITLINE |
| 1042 |
/* |
| 1043 |
* Use readline only if file is stdin, because there's no way to specify |
| 1044 |
* another handle. Are other filehandles interactive? |
| 1045 |
*/ |
| 1046 |
if (file == stdin) { |
| 1047 |
mozilla::UniqueFreePtr<char[]> linep(readline(prompt)); |
| 1048 |
/* |
| 1049 |
* We set it to zero to avoid complaining about inappropriate ioctl |
| 1050 |
* for device in the case of EOF. Looks like errno == 251 if line is |
| 1051 |
* finished with EOF and errno == 25 (EINVAL on Mac) if there is |
| 1052 |
* nothing left to read. |
| 1053 |
*/ |
| 1054 |
if (errno == 251 || errno == 25 || errno == EINVAL) { |
| 1055 |
errno = 0; |
| 1056 |
} |
| 1057 |
if (!linep) { |
| 1058 |
return nullptr; |
| 1059 |
} |
| 1060 |
if (linep[0] != '\0') { |
| 1061 |
add_history(linep.get()); |
| 1062 |
} |
| 1063 |
return linep; |
| 1064 |
} |
| 1065 |
#endif |
| 1066 |
|
| 1067 |
size_t len = 0; |
| 1068 |
if (*prompt != '\0' && gOutFile->isOpen()) { |
| 1069 |
fprintf(gOutFile->fp, "%s", prompt); |
| 1070 |
fflush(gOutFile->fp); |
| 1071 |
} |
| 1072 |
|
| 1073 |
size_t size = 80; |
| 1074 |
mozilla::UniqueFreePtr<char[]> buffer(static_cast<char*>(malloc(size))); |
| 1075 |
if (!buffer) { |
| 1076 |
return nullptr; |
| 1077 |
} |
| 1078 |
|
| 1079 |
char* current = buffer.get(); |
| 1080 |
do { |
| 1081 |
while (true) { |
| 1082 |
if (fgets(current, size - len, file)) { |
| 1083 |
break; |
| 1084 |
} |
| 1085 |
if (errno != EINTR) { |
| 1086 |
return nullptr; |
| 1087 |
} |
| 1088 |
} |
| 1089 |
|
| 1090 |
len += strlen(current); |
| 1091 |
char* t = buffer.get() + len - 1; |
| 1092 |
if (*t == '\n') { |
| 1093 |
/* Line was read. We remove '\n' and exit. */ |
| 1094 |
*t = '\0'; |
| 1095 |
break; |
| 1096 |
} |
| 1097 |
|
| 1098 |
if (len + 1 == size) { |
| 1099 |
size = size * 2; |
| 1100 |
char* raw = buffer.release(); |
| 1101 |
char* tmp = static_cast<char*>(realloc(raw, size)); |
| 1102 |
if (!tmp) { |
| 1103 |
free(raw); |
| 1104 |
return nullptr; |
| 1105 |
} |
| 1106 |
buffer.reset(tmp); |
| 1107 |
} |
| 1108 |
current = buffer.get() + len; |
| 1109 |
} while (true); |
| 1110 |
return buffer; |
| 1111 |
} |
| 1112 |
|
| 1113 |
static bool ShellInterruptCallback(JSContext* cx) { |
| 1114 |
ShellContext* sc = GetShellContext(cx); |
| 1115 |
if (!sc->serviceInterrupt) { |
| 1116 |
return true; |
| 1117 |
} |
| 1118 |
|
| 1119 |
// Reset serviceInterrupt. CancelExecution or InterruptIf will set it to |
| 1120 |
// true to distinguish watchdog or user triggered interrupts. |
| 1121 |
// Do this first to prevent other interrupts that may occur while the |
| 1122 |
// user-supplied callback is executing from re-entering the handler. |
| 1123 |
sc->serviceInterrupt = false; |
| 1124 |
|
| 1125 |
bool result; |
| 1126 |
if (sc->haveInterruptFunc) { |
| 1127 |
bool wasAlreadyThrowing = cx->isExceptionPending(); |
| 1128 |
JS::AutoSaveExceptionState savedExc(cx); |
| 1129 |
JSAutoRealm ar(cx, &sc->interruptFunc.toObject()); |
| 1130 |
RootedValue rval(cx); |
| 1131 |
|
| 1132 |
// Report any exceptions thrown by the JS interrupt callback, but do |
| 1133 |
// *not* keep it on the cx. The interrupt handler is invoked at points |
| 1134 |
// that are not expected to throw catchable exceptions, like at |
| 1135 |
// JSOp::RetRval. |
| 1136 |
// |
| 1137 |
// If the interrupted JS code was already throwing, any exceptions |
| 1138 |
// thrown by the interrupt handler are silently swallowed. |
| 1139 |
{ |
| 1140 |
Maybe<AutoReportException> are; |
| 1141 |
if (!wasAlreadyThrowing) { |
| 1142 |
are.emplace(cx); |
| 1143 |
} |
| 1144 |
result = JS_CallFunctionValue(cx, nullptr, sc->interruptFunc, |
| 1145 |
JS::HandleValueArray::empty(), &rval); |
| 1146 |
} |
| 1147 |
savedExc.restore(); |
| 1148 |
|
| 1149 |
if (rval.isBoolean()) { |
| 1150 |
result = rval.toBoolean(); |
| 1151 |
} else { |
| 1152 |
result = false; |
| 1153 |
} |
| 1154 |
} else { |
| 1155 |
result = false; |
| 1156 |
} |
| 1157 |
|
| 1158 |
if (!result && sc->exitCode == 0) { |
| 1159 |
static const char msg[] = "Script terminated by interrupt handler.\n"; |
| 1160 |
fputs(msg, stderr); |
| 1161 |
|
| 1162 |
sc->exitCode = EXITCODE_TIMEOUT; |
| 1163 |
} |
| 1164 |
|
| 1165 |
return result; |
| 1166 |
} |
| 1167 |
|
| 1168 |
static void GCSliceCallback(JSContext* cx, JS::GCProgress progress, |
| 1169 |
const JS::GCDescription& desc) { |
| 1170 |
if (progress == JS::GC_CYCLE_END) { |
| 1171 |
#if defined(MOZ_MEMORY) |
| 1172 |
// We call this here to match the browser's DOMGCSliceCallback. |
| 1173 |
jemalloc_free_dirty_pages(); |
| 1174 |
#endif |
| 1175 |
} |
| 1176 |
} |
| 1177 |
|
| 1178 |
/* |
| 1179 |
* Some UTF-8 files, notably those written using Notepad, have a Unicode |
| 1180 |
* Byte-Order-Mark (BOM) as their first character. This is useless (byte-order |
| 1181 |
* is meaningless for UTF-8) but causes a syntax error unless we skip it. |
| 1182 |
*/ |
| 1183 |
static void SkipUTF8BOM(FILE* file) { |
| 1184 |
int ch1 = fgetc(file); |
| 1185 |
int ch2 = fgetc(file); |
| 1186 |
int ch3 = fgetc(file); |
| 1187 |
|
| 1188 |
// Skip the BOM |
| 1189 |
if (ch1 == 0xEF && ch2 == 0xBB && ch3 == 0xBF) { |
| 1190 |
return; |
| 1191 |
} |
| 1192 |
|
| 1193 |
// No BOM - revert |
| 1194 |
if (ch3 != EOF) { |
| 1195 |
ungetc(ch3, file); |
| 1196 |
} |
| 1197 |
if (ch2 != EOF) { |
| 1198 |
ungetc(ch2, file); |
| 1199 |
} |
| 1200 |
if (ch1 != EOF) { |
| 1201 |
ungetc(ch1, file); |
| 1202 |
} |
| 1203 |
} |
| 1204 |
|
| 1205 |
void EnvironmentPreparer::invoke(HandleObject global, Closure& closure) { |
| 1206 |
MOZ_ASSERT(JS_IsGlobalObject(global)); |
| 1207 |
|
| 1208 |
JSContext* cx = TlsContext.get(); |
| 1209 |
MOZ_ASSERT(!JS_IsExceptionPending(cx)); |
| 1210 |
|
| 1211 |
AutoRealm ar(cx, global); |
| 1212 |
AutoReportException are(cx); |
| 1213 |
if (!closure(cx)) { |
| 1214 |
return; |
| 1215 |
} |
| 1216 |
} |
| 1217 |
|
| 1218 |
static bool RegisterScriptPathWithModuleLoader(JSContext* cx, |
| 1219 |
HandleScript script, |
| 1220 |
const char* filename) { |
| 1221 |
// Set the private value associated with a script to a object containing the |
| 1222 |
// script's filename so that the module loader can use it to resolve |
| 1223 |
// relative imports. |
| 1224 |
|
| 1225 |
RootedString path(cx, NewStringCopyUTF8(cx, filename)); |
| 1226 |
if (!path) { |
| 1227 |
return false; |
| 1228 |
} |
| 1229 |
|
| 1230 |
MOZ_ASSERT(JS::GetScriptPrivate(script).isUndefined()); |
| 1231 |
RootedObject infoObject(cx, js::CreateScriptPrivate(cx, path)); |
| 1232 |
if (!infoObject) { |
| 1233 |
return false; |
| 1234 |
} |
| 1235 |
|
| 1236 |
JS::SetScriptPrivate(script, ObjectValue(*infoObject)); |
| 1237 |
return true; |
| 1238 |
} |
| 1239 |
|
| 1240 |
enum class CompileUtf8 { |
| 1241 |
InflateToUtf16, |
| 1242 |
DontInflate, |
| 1243 |
}; |
| 1244 |
|
| 1245 |
[[nodiscard]] static bool RunFile(JSContext* cx, const char* filename, |
| 1246 |
FILE* file, CompileUtf8 compileMethod, |
| 1247 |
bool compileOnly, bool fullParse) { |
| 1248 |
SkipUTF8BOM(file); |
| 1249 |
|
| 1250 |
int64_t t1 = PRMJ_Now(); |
| 1251 |
RootedScript script(cx); |
| 1252 |
|
| 1253 |
if (!filename) filename = "-"; |
| 1254 |
|
| 1255 |
{ |
| 1256 |
CompileOptions options(cx); |
| 1257 |
options.setIntroductionType("js shell file") |
| 1258 |
.setFileAndLine(filename, 1) |
| 1259 |
.setIsRunOnce(true) |
| 1260 |
.setNoScriptRval(true); |
| 1261 |
|
| 1262 |
if (fullParse) { |
| 1263 |
options.setForceFullParse(); |
| 1264 |
} else { |
| 1265 |
options.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 1266 |
} |
| 1267 |
|
| 1268 |
if (compileMethod == CompileUtf8::DontInflate) { |
| 1269 |
script = JS::CompileUtf8File(cx, options, file); |
| 1270 |
} else { |
| 1271 |
fprintf(stderr, "(compiling '%s' after inflating to UTF-16)\n", filename); |
| 1272 |
|
| 1273 |
FileContents buffer(cx); |
| 1274 |
if (!ReadCompleteFile(cx, file, buffer)) { |
| 1275 |
return false; |
| 1276 |
} |
| 1277 |
|
| 1278 |
size_t length = buffer.length(); |
| 1279 |
auto chars = UniqueTwoByteChars( |
| 1280 |
UTF8CharsToNewTwoByteCharsZ( |
| 1281 |
cx, |
| 1282 |
JS::UTF8Chars(reinterpret_cast<const char*>(buffer.begin()), |
| 1283 |
buffer.length()), |
| 1284 |
&length, js::MallocArena) |
| 1285 |
.get()); |
| 1286 |
if (!chars) { |
| 1287 |
return false; |
| 1288 |
} |
| 1289 |
|
| 1290 |
JS::SourceText<char16_t> source; |
| 1291 |
if (!source.init(cx, std::move(chars), length)) { |
| 1292 |
return false; |
| 1293 |
} |
| 1294 |
|
| 1295 |
script = JS::Compile(cx, options, source); |
| 1296 |
} |
| 1297 |
|
| 1298 |
if (!script) { |
| 1299 |
return false; |
| 1300 |
} |
| 1301 |
} |
| 1302 |
|
| 1303 |
if (!RegisterScriptPathWithModuleLoader(cx, script, filename)) { |
| 1304 |
return false; |
| 1305 |
} |
| 1306 |
|
| 1307 |
#ifdef DEBUG |
| 1308 |
if (dumpEntrainedVariables) { |
| 1309 |
AnalyzeEntrainedVariables(cx, script); |
| 1310 |
} |
| 1311 |
#endif |
| 1312 |
if (!compileOnly) { |
| 1313 |
if (!JS_ExecuteScript(cx, script)) { |
| 1314 |
return false; |
| 1315 |
} |
| 1316 |
int64_t t2 = PRMJ_Now() - t1; |
| 1317 |
if (printTiming) { |
| 1318 |
printf("runtime = %.3f ms\n", double(t2) / PRMJ_USEC_PER_MSEC); |
| 1319 |
} |
| 1320 |
} |
| 1321 |
return true; |
| 1322 |
} |
| 1323 |
|
| 1324 |
[[nodiscard]] static bool RunModule(JSContext* cx, const char* filename, |
| 1325 |
bool compileOnly) { |
| 1326 |
ShellContext* sc = GetShellContext(cx); |
| 1327 |
|
| 1328 |
RootedString path(cx, NewStringCopyUTF8(cx, filename)); |
| 1329 |
if (!path) { |
| 1330 |
return false; |
| 1331 |
} |
| 1332 |
|
| 1333 |
path = ResolvePath(cx, path, RootRelative); |
| 1334 |
if (!path) { |
| 1335 |
return false; |
| 1336 |
} |
| 1337 |
|
| 1338 |
return sc->moduleLoader->loadRootModule(cx, path); |
| 1339 |
} |
| 1340 |
|
| 1341 |
static void ShellCleanupFinalizationRegistryCallback(JSFunction* doCleanup, |
| 1342 |
JSObject* incumbentGlobal, |
| 1343 |
void* data) { |
| 1344 |
// In the browser this queues a task. Shell jobs correspond to microtasks so |
| 1345 |
// we arrange for cleanup to happen after all jobs/microtasks have run. The |
| 1346 |
// incumbent global is ignored in the shell. |
| 1347 |
|
| 1348 |
auto sc = static_cast<ShellContext*>(data); |
| 1349 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 1350 |
if (!sc->finalizationRegistryCleanupCallbacks.append(doCleanup)) { |
| 1351 |
oomUnsafe.crash("ShellCleanupFinalizationRegistryCallback"); |
| 1352 |
} |
| 1353 |
} |
| 1354 |
|
| 1355 |
// Run any FinalizationRegistry cleanup tasks and return whether any ran. |
| 1356 |
static bool MaybeRunFinalizationRegistryCleanupTasks(JSContext* cx) { |
| 1357 |
ShellContext* sc = GetShellContext(cx); |
| 1358 |
MOZ_ASSERT(!sc->quitting); |
| 1359 |
|
| 1360 |
Rooted<ShellContext::FunctionVector> callbacks(cx); |
| 1361 |
std::swap(callbacks.get(), sc->finalizationRegistryCleanupCallbacks.get()); |
| 1362 |
|
| 1363 |
bool ranTasks = false; |
| 1364 |
|
| 1365 |
RootedFunction callback(cx); |
| 1366 |
for (JSFunction* f : callbacks) { |
| 1367 |
callback = f; |
| 1368 |
|
| 1369 |
JS::ExposeObjectToActiveJS(callback); |
| 1370 |
AutoRealm ar(cx, callback); |
| 1371 |
|
| 1372 |
{ |
| 1373 |
AutoReportException are(cx); |
| 1374 |
RootedValue unused(cx); |
| 1375 |
(void)JS_CallFunction(cx, nullptr, callback, HandleValueArray::empty(), |
| 1376 |
&unused); |
| 1377 |
} |
| 1378 |
|
| 1379 |
ranTasks = true; |
| 1380 |
|
| 1381 |
if (sc->quitting) { |
| 1382 |
break; |
| 1383 |
} |
| 1384 |
} |
| 1385 |
|
| 1386 |
return ranTasks; |
| 1387 |
} |
| 1388 |
|
| 1389 |
static bool EnqueueJob(JSContext* cx, unsigned argc, Value* vp) { |
| 1390 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1391 |
|
| 1392 |
if (!IsFunctionObject(args.get(0))) { |
| 1393 |
JS_ReportErrorASCII(cx, "EnqueueJob's first argument must be a function"); |
| 1394 |
return false; |
| 1395 |
} |
| 1396 |
|
| 1397 |
args.rval().setUndefined(); |
| 1398 |
|
| 1399 |
RootedObject job(cx, &args[0].toObject()); |
| 1400 |
return js::EnqueueJob(cx, job); |
| 1401 |
} |
| 1402 |
|
| 1403 |
static void RunShellJobs(JSContext* cx) { |
| 1404 |
ShellContext* sc = GetShellContext(cx); |
| 1405 |
if (sc->quitting) { |
| 1406 |
return; |
| 1407 |
} |
| 1408 |
|
| 1409 |
while (true) { |
| 1410 |
// Run microtasks. |
| 1411 |
js::RunJobs(cx); |
| 1412 |
if (sc->quitting) { |
| 1413 |
return; |
| 1414 |
} |
| 1415 |
|
| 1416 |
// Run tasks (only finalization registry clean tasks are possible). |
| 1417 |
bool ranTasks = MaybeRunFinalizationRegistryCleanupTasks(cx); |
| 1418 |
if (!ranTasks) { |
| 1419 |
break; |
| 1420 |
} |
| 1421 |
} |
| 1422 |
} |
| 1423 |
|
| 1424 |
static bool DrainJobQueue(JSContext* cx, unsigned argc, Value* vp) { |
| 1425 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1426 |
|
| 1427 |
if (GetShellContext(cx)->quitting) { |
| 1428 |
JS_ReportErrorASCII( |
| 1429 |
cx, "Mustn't drain the job queue when the shell is quitting"); |
| 1430 |
return false; |
| 1431 |
} |
| 1432 |
|
| 1433 |
if (cx->isEvaluatingModule != 0) { |
| 1434 |
JS_ReportErrorASCII( |
| 1435 |
cx, |
| 1436 |
"Can't drain the job queue when executing the top level of a module"); |
| 1437 |
return false; |
| 1438 |
} |
| 1439 |
|
| 1440 |
RunShellJobs(cx); |
| 1441 |
|
| 1442 |
if (GetShellContext(cx)->quitting) { |
| 1443 |
return false; |
| 1444 |
} |
| 1445 |
|
| 1446 |
args.rval().setUndefined(); |
| 1447 |
return true; |
| 1448 |
} |
| 1449 |
|
| 1450 |
static bool GlobalOfFirstJobInQueue(JSContext* cx, unsigned argc, Value* vp) { |
| 1451 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1452 |
|
| 1453 |
RootedObject job(cx, cx->internalJobQueue->maybeFront()); |
| 1454 |
if (!job) { |
| 1455 |
JS_ReportErrorASCII(cx, "Job queue is empty"); |
| 1456 |
return false; |
| 1457 |
} |
| 1458 |
|
| 1459 |
RootedObject global(cx, &job->nonCCWGlobal()); |
| 1460 |
if (!cx->compartment()->wrap(cx, &global)) { |
| 1461 |
return false; |
| 1462 |
} |
| 1463 |
|
| 1464 |
args.rval().setObject(*global); |
| 1465 |
return true; |
| 1466 |
} |
| 1467 |
|
| 1468 |
static bool TrackUnhandledRejections(JSContext* cx, JS::HandleObject promise, |
| 1469 |
JS::PromiseRejectionHandlingState state) { |
| 1470 |
ShellContext* sc = GetShellContext(cx); |
| 1471 |
if (!sc->trackUnhandledRejections) { |
| 1472 |
return true; |
| 1473 |
} |
| 1474 |
|
| 1475 |
#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) |
| 1476 |
if (cx->runningOOMTest) { |
| 1477 |
// When OOM happens, we cannot reliably track the set of unhandled |
| 1478 |
// promise rejections. Throw error only when simulated OOM is used |
| 1479 |
// *and* promises are used in the test. |
| 1480 |
JS_ReportErrorASCII( |
| 1481 |
cx, |
| 1482 |
"Can't track unhandled rejections while running simulated OOM " |
| 1483 |
"test. Call ignoreUnhandledRejections before using oomTest etc."); |
| 1484 |
return false; |
| 1485 |
} |
| 1486 |
#endif |
| 1487 |
|
| 1488 |
if (!sc->unhandledRejectedPromises) { |
| 1489 |
sc->unhandledRejectedPromises = SetObject::create(cx); |
| 1490 |
if (!sc->unhandledRejectedPromises) { |
| 1491 |
return false; |
| 1492 |
} |
| 1493 |
} |
| 1494 |
|
| 1495 |
RootedValue promiseVal(cx, ObjectValue(*promise)); |
| 1496 |
|
| 1497 |
AutoRealm ar(cx, sc->unhandledRejectedPromises); |
| 1498 |
if (!cx->compartment()->wrap(cx, &promiseVal)) { |
| 1499 |
return false; |
| 1500 |
} |
| 1501 |
|
| 1502 |
switch (state) { |
| 1503 |
case JS::PromiseRejectionHandlingState::Unhandled: |
| 1504 |
if (!sc->unhandledRejectedPromises->add(cx, promiseVal)) { |
| 1505 |
return false; |
| 1506 |
} |
| 1507 |
break; |
| 1508 |
case JS::PromiseRejectionHandlingState::Handled: |
| 1509 |
bool deleted = false; |
| 1510 |
if (!sc->unhandledRejectedPromises->delete_(cx, promiseVal, &deleted)) { |
| 1511 |
return false; |
| 1512 |
} |
| 1513 |
// We can't MOZ_ASSERT(deleted) here, because it's possible we failed to |
| 1514 |
// add the promise in the first place, due to OOM. |
| 1515 |
break; |
| 1516 |
} |
| 1517 |
|
| 1518 |
return true; |
| 1519 |
} |
| 1520 |
|
| 1521 |
static void ForwardingPromiseRejectionTrackerCallback( |
| 1522 |
JSContext* cx, bool mutedErrors, JS::HandleObject promise, |
| 1523 |
JS::PromiseRejectionHandlingState state, void* data) { |
| 1524 |
AutoReportException are(cx); |
| 1525 |
|
| 1526 |
if (!TrackUnhandledRejections(cx, promise, state)) { |
| 1527 |
return; |
| 1528 |
} |
| 1529 |
|
| 1530 |
RootedValue callback(cx, |
| 1531 |
GetShellContext(cx)->promiseRejectionTrackerCallback); |
| 1532 |
if (callback.isNull()) { |
| 1533 |
return; |
| 1534 |
} |
| 1535 |
|
| 1536 |
AutoRealm ar(cx, &callback.toObject()); |
| 1537 |
|
| 1538 |
FixedInvokeArgs<2> args(cx); |
| 1539 |
args[0].setObject(*promise); |
| 1540 |
args[1].setInt32(static_cast<int32_t>(state)); |
| 1541 |
|
| 1542 |
if (!JS_WrapValue(cx, args[0])) { |
| 1543 |
return; |
| 1544 |
} |
| 1545 |
|
| 1546 |
RootedValue rval(cx); |
| 1547 |
(void)Call(cx, callback, UndefinedHandleValue, args, &rval); |
| 1548 |
} |
| 1549 |
|
| 1550 |
static bool SetPromiseRejectionTrackerCallback(JSContext* cx, unsigned argc, |
| 1551 |
Value* vp) { |
| 1552 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1553 |
|
| 1554 |
if (!IsFunctionObject(args.get(0))) { |
| 1555 |
JS_ReportErrorASCII( |
| 1556 |
cx, |
| 1557 |
"setPromiseRejectionTrackerCallback expects a function as its sole " |
| 1558 |
"argument"); |
| 1559 |
return false; |
| 1560 |
} |
| 1561 |
|
| 1562 |
GetShellContext(cx)->promiseRejectionTrackerCallback = args[0]; |
| 1563 |
|
| 1564 |
args.rval().setUndefined(); |
| 1565 |
return true; |
| 1566 |
} |
| 1567 |
|
| 1568 |
static const char* telemetryNames[static_cast<int>(JSMetric::Count)] = { |
| 1569 |
#define LIT(NAME, _) #NAME, |
| 1570 |
FOR_EACH_JS_METRIC(LIT) |
| 1571 |
#undef LIT |
| 1572 |
}; |
| 1573 |
|
| 1574 |
// Telemetry can be executed from multiple threads, and the callback is |
| 1575 |
// responsible to avoid contention on the recorded telemetry data. |
| 1576 |
class MOZ_RAII AutoLockTelemetry : public LockGuard<Mutex> { |
| 1577 |
using Base = LockGuard<Mutex>; |
| 1578 |
|
| 1579 |
Mutex& getMutex() { |
| 1580 |
static Mutex mutex(mutexid::ShellTelemetry); |
| 1581 |
return mutex; |
| 1582 |
} |
| 1583 |
|
| 1584 |
public: |
| 1585 |
AutoLockTelemetry() : Base(getMutex()) {} |
| 1586 |
}; |
| 1587 |
|
| 1588 |
using TelemetrySamples = mozilla::Vector<uint32_t, 0, js::SystemAllocPolicy>; |
| 1589 |
MOZ_CONSTINIT static mozilla::Array<UniquePtr<TelemetrySamples>, |
| 1590 |
size_t(JSMetric::Count)> |
| 1591 |
recordedTelemetrySamples; |
| 1592 |
|
| 1593 |
static void AccumulateTelemetryDataCallback(JSMetric id, uint32_t sample) { |
| 1594 |
AutoLockTelemetry alt; |
| 1595 |
TelemetrySamples* samples = recordedTelemetrySamples[size_t(id)].get(); |
| 1596 |
if (!samples) { |
| 1597 |
return; |
| 1598 |
} |
| 1599 |
|
| 1600 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 1601 |
if (!samples->append(sample)) { |
| 1602 |
oomUnsafe.crash("AccumulateTelemetrySamplesCallback"); |
| 1603 |
} |
| 1604 |
} |
| 1605 |
|
| 1606 |
static bool LookupTelemetryName(JSContext* cx, Handle<Value> nameValue, |
| 1607 |
JSMetric* resultOut) { |
| 1608 |
static_assert(size_t(JSMetric::Count) == std::size(telemetryNames)); |
| 1609 |
MOZ_ASSERT(resultOut); |
| 1610 |
|
| 1611 |
JSString* str = ToString(cx, nameValue); |
| 1612 |
if (!str) { |
| 1613 |
return false; |
| 1614 |
} |
| 1615 |
|
| 1616 |
UniqueChars name = EncodeLatin1(cx, str); |
| 1617 |
if (!name) { |
| 1618 |
return false; |
| 1619 |
} |
| 1620 |
|
| 1621 |
for (size_t i = 0; i < std::size(telemetryNames); i++) { |
| 1622 |
if (strcmp(telemetryNames[i], name.get()) == 0) { |
| 1623 |
*resultOut = JSMetric(i); |
| 1624 |
return true; |
| 1625 |
} |
| 1626 |
} |
| 1627 |
|
| 1628 |
return false; |
| 1629 |
} |
| 1630 |
|
| 1631 |
static bool StartRecordingTelemetry(JSContext* cx, unsigned argc, Value* vp) { |
| 1632 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1633 |
if (args.length() != 1) { |
| 1634 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 1635 |
JSSMSG_INVALID_ARGS, "startRecordingTelemetry"); |
| 1636 |
return false; |
| 1637 |
} |
| 1638 |
|
| 1639 |
JSMetric id; |
| 1640 |
if (!LookupTelemetryName(cx, args[0], &id)) { |
| 1641 |
JS_ReportErrorASCII(cx, "Telemetry probe name not found"); |
| 1642 |
return false; |
| 1643 |
} |
| 1644 |
|
| 1645 |
if (recordedTelemetrySamples[size_t(id)]) { |
| 1646 |
JS_ReportErrorASCII(cx, "Already recording telemetry for this probe"); |
| 1647 |
return false; |
| 1648 |
} |
| 1649 |
|
| 1650 |
auto samples = MakeUnique<TelemetrySamples>(); |
| 1651 |
if (!samples) { |
| 1652 |
ReportOutOfMemory(cx); |
| 1653 |
return false; |
| 1654 |
} |
| 1655 |
|
| 1656 |
recordedTelemetrySamples[size_t(id)] = std::move(samples); |
| 1657 |
args.rval().setUndefined(); |
| 1658 |
return true; |
| 1659 |
} |
| 1660 |
|
| 1661 |
static bool StopRecordingTelemetry(JSContext* cx, unsigned argc, Value* vp) { |
| 1662 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1663 |
if (args.length() != 1) { |
| 1664 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 1665 |
JSSMSG_INVALID_ARGS, "stopRecordingTelemetry"); |
| 1666 |
return false; |
| 1667 |
} |
| 1668 |
|
| 1669 |
JSMetric id; |
| 1670 |
if (!LookupTelemetryName(cx, args[0], &id)) { |
| 1671 |
JS_ReportErrorASCII(cx, "Telemetry probe name not found"); |
| 1672 |
return false; |
| 1673 |
} |
| 1674 |
|
| 1675 |
if (!recordedTelemetrySamples[size_t(id)]) { |
| 1676 |
JS_ReportErrorASCII(cx, "Not recording telemetry for this probe"); |
| 1677 |
return false; |
| 1678 |
} |
| 1679 |
|
| 1680 |
recordedTelemetrySamples[size_t(id)].reset(); |
| 1681 |
args.rval().setUndefined(); |
| 1682 |
return true; |
| 1683 |
} |
| 1684 |
|
| 1685 |
static bool GetTelemetrySamples(JSContext* cx, unsigned argc, Value* vp) { |
| 1686 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1687 |
if (args.length() != 1) { |
| 1688 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 1689 |
JSSMSG_INVALID_ARGS, "getTelemetrySamples"); |
| 1690 |
return false; |
| 1691 |
} |
| 1692 |
|
| 1693 |
JSMetric id; |
| 1694 |
if (!LookupTelemetryName(cx, args[0], &id)) { |
| 1695 |
JS_ReportErrorASCII(cx, "Telemetry probe name not found"); |
| 1696 |
return false; |
| 1697 |
} |
| 1698 |
|
| 1699 |
TelemetrySamples* samples = recordedTelemetrySamples[size_t(id)].get(); |
| 1700 |
if (!samples) { |
| 1701 |
args.rval().setUndefined(); |
| 1702 |
return true; |
| 1703 |
} |
| 1704 |
|
| 1705 |
Rooted<ArrayObject*> array(cx, NewDenseEmptyArray(cx)); |
| 1706 |
if (!array) { |
| 1707 |
return false; |
| 1708 |
} |
| 1709 |
|
| 1710 |
for (uint32_t sample : *samples) { |
| 1711 |
if (!NewbornArrayPush(cx, array, NumberValue(sample))) { |
| 1712 |
return false; |
| 1713 |
} |
| 1714 |
} |
| 1715 |
|
| 1716 |
args.rval().setObject(*array); |
| 1717 |
return true; |
| 1718 |
} |
| 1719 |
|
| 1720 |
// Use Counter introspection |
| 1721 |
MOZ_RUNINIT static Mutex useCounterLock(mutexid::ShellUseCounters); |
| 1722 |
class MOZ_RAII AutoLockUseCounters : public LockGuard<Mutex> { |
| 1723 |
using Base = LockGuard<Mutex>; |
| 1724 |
|
| 1725 |
public: |
| 1726 |
AutoLockUseCounters() : Base(useCounterLock) {} |
| 1727 |
}; |
| 1728 |
|
| 1729 |
using UseCounterArray = |
| 1730 |
mozilla::Array<uint32_t, static_cast<size_t>(JSUseCounter::COUNT)>; |
| 1731 |
static UseCounterArray useCounterResults; |
| 1732 |
static void SetUseCounterCallback(JSObject* obj, JSUseCounter counter) { |
| 1733 |
MOZ_RELEASE_ASSERT(obj); |
| 1734 |
AutoLockUseCounters aluc; |
| 1735 |
// Maybe should ensure obj is a global object? |
| 1736 |
useCounterResults[static_cast<size_t>(counter)]++; |
| 1737 |
} |
| 1738 |
|
| 1739 |
static bool GetUseCounterResults(JSContext* cx, unsigned argc, Value* vp) { |
| 1740 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1741 |
Rooted<JSObject*> obj(cx, JS_NewPlainObject(cx)); |
| 1742 |
if (!obj) { |
| 1743 |
return false; |
| 1744 |
} |
| 1745 |
|
| 1746 |
// Make a private copy holding the lock then release, because we can't |
| 1747 |
// hold this mutex while doing JS_DefineProperty, which holds MemoryTracker |
| 1748 |
// mutex. |
| 1749 |
UseCounterArray local; |
| 1750 |
{ |
| 1751 |
AutoLockUseCounters aluc; |
| 1752 |
local = useCounterResults; |
| 1753 |
} |
| 1754 |
|
| 1755 |
RootedValue val(cx); |
| 1756 |
#define ADD_VALUE(ENUM, NAME) \ |
| 1757 |
val.setInt32(local[static_cast<size_t>(JSUseCounter::ENUM)]); \ |
| 1758 |
if (!JS_DefineProperty(cx, obj, #NAME, val, JSPROP_ENUMERATE)) { \ |
| 1759 |
return false; \ |
| 1760 |
} |
| 1761 |
|
| 1762 |
FOR_EACH_JS_USE_COUNTER(ADD_VALUE); |
| 1763 |
|
| 1764 |
args.rval().setObject(*obj); |
| 1765 |
return true; |
| 1766 |
} |
| 1767 |
|
| 1768 |
static bool BoundToAsyncStack(JSContext* cx, unsigned argc, Value* vp) { |
| 1769 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1770 |
|
| 1771 |
RootedValue function(cx, GetFunctionNativeReserved(&args.callee(), 0)); |
| 1772 |
RootedObject options( |
| 1773 |
cx, &GetFunctionNativeReserved(&args.callee(), 1).toObject()); |
| 1774 |
|
| 1775 |
Rooted<SavedFrame*> stack(cx, nullptr); |
| 1776 |
bool isExplicit; |
| 1777 |
|
| 1778 |
RootedValue v(cx); |
| 1779 |
|
| 1780 |
if (!JS_GetProperty(cx, options, "stack", &v)) { |
| 1781 |
return false; |
| 1782 |
} |
| 1783 |
if (!v.isObject() || !v.toObject().is<SavedFrame>()) { |
| 1784 |
JS_ReportErrorASCII(cx, |
| 1785 |
"The 'stack' property must be a SavedFrame object."); |
| 1786 |
return false; |
| 1787 |
} |
| 1788 |
stack = &v.toObject().as<SavedFrame>(); |
| 1789 |
|
| 1790 |
if (!JS_GetProperty(cx, options, "cause", &v)) { |
| 1791 |
return false; |
| 1792 |
} |
| 1793 |
RootedString causeString(cx, ToString(cx, v)); |
| 1794 |
if (!causeString) { |
| 1795 |
return false; |
| 1796 |
} |
| 1797 |
|
| 1798 |
UniqueChars cause = JS_EncodeStringToUTF8(cx, causeString); |
| 1799 |
if (!cause) { |
| 1800 |
MOZ_ASSERT(cx->isExceptionPending()); |
| 1801 |
return false; |
| 1802 |
} |
| 1803 |
|
| 1804 |
if (!JS_GetProperty(cx, options, "explicit", &v)) { |
| 1805 |
return false; |
| 1806 |
} |
| 1807 |
isExplicit = v.isUndefined() ? true : ToBoolean(v); |
| 1808 |
|
| 1809 |
auto kind = |
| 1810 |
(isExplicit ? JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::EXPLICIT |
| 1811 |
: JS::AutoSetAsyncStackForNewCalls::AsyncCallKind::IMPLICIT); |
| 1812 |
|
| 1813 |
JS::AutoSetAsyncStackForNewCalls asasfnckthxbye(cx, stack, cause.get(), kind); |
| 1814 |
return Call(cx, UndefinedHandleValue, function, JS::HandleValueArray::empty(), |
| 1815 |
args.rval()); |
| 1816 |
} |
| 1817 |
|
| 1818 |
static bool BindToAsyncStack(JSContext* cx, unsigned argc, Value* vp) { |
| 1819 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1820 |
|
| 1821 |
if (args.length() != 2) { |
| 1822 |
JS_ReportErrorASCII(cx, "bindToAsyncStack takes exactly two arguments."); |
| 1823 |
return false; |
| 1824 |
} |
| 1825 |
|
| 1826 |
if (!args[0].isObject() || !IsCallable(args[0])) { |
| 1827 |
JS_ReportErrorASCII( |
| 1828 |
cx, "bindToAsyncStack's first argument should be a function."); |
| 1829 |
return false; |
| 1830 |
} |
| 1831 |
|
| 1832 |
if (!args[1].isObject()) { |
| 1833 |
JS_ReportErrorASCII( |
| 1834 |
cx, "bindToAsyncStack's second argument should be an object."); |
| 1835 |
return false; |
| 1836 |
} |
| 1837 |
|
| 1838 |
RootedFunction bound(cx, NewFunctionWithReserved(cx, BoundToAsyncStack, 0, 0, |
| 1839 |
"bindToAsyncStack thunk")); |
| 1840 |
if (!bound) { |
| 1841 |
return false; |
| 1842 |
} |
| 1843 |
SetFunctionNativeReserved(bound, 0, args[0]); |
| 1844 |
SetFunctionNativeReserved(bound, 1, args[1]); |
| 1845 |
|
| 1846 |
args.rval().setObject(*bound); |
| 1847 |
return true; |
| 1848 |
} |
| 1849 |
|
| 1850 |
#ifdef JS_HAS_INTL_API |
| 1851 |
static bool AddIntlExtras(JSContext* cx, unsigned argc, Value* vp) { |
| 1852 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 1853 |
if (!args.get(0).isObject()) { |
| 1854 |
JS_ReportErrorASCII(cx, "addIntlExtras must be passed an object"); |
| 1855 |
return false; |
| 1856 |
} |
| 1857 |
JS::RootedObject intl(cx, &args[0].toObject()); |
| 1858 |
|
| 1859 |
static const JSFunctionSpec funcs[] = { |
| 1860 |
JS_SELF_HOSTED_FN("getCalendarInfo", "Intl_getCalendarInfo", 1, 0), |
| 1861 |
JS_FS_END, |
| 1862 |
}; |
| 1863 |
|
| 1864 |
if (!JS_DefineFunctions(cx, intl, funcs)) { |
| 1865 |
return false; |
| 1866 |
} |
| 1867 |
|
| 1868 |
if (!JS::AddMozDateTimeFormatConstructor(cx, intl)) { |
| 1869 |
return false; |
| 1870 |
} |
| 1871 |
|
| 1872 |
if (!JS::AddMozDisplayNamesConstructor(cx, intl)) { |
| 1873 |
return false; |
| 1874 |
} |
| 1875 |
|
| 1876 |
args.rval().setUndefined(); |
| 1877 |
return true; |
| 1878 |
} |
| 1879 |
#endif // JS_HAS_INTL_API |
| 1880 |
|
| 1881 |
[[nodiscard]] static bool EvalUtf8AndPrint(JSContext* cx, const char* bytes, |
| 1882 |
size_t length, int lineno, |
| 1883 |
bool compileOnly) { |
| 1884 |
// Eval. |
| 1885 |
JS::CompileOptions options(cx); |
| 1886 |
options.setIntroductionType("js shell interactive") |
| 1887 |
.setIsRunOnce(true) |
| 1888 |
.setFileAndLine("typein", lineno) |
| 1889 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 1890 |
|
| 1891 |
JS::SourceText<Utf8Unit> srcBuf; |
| 1892 |
if (!srcBuf.init(cx, bytes, length, JS::SourceOwnership::Borrowed)) { |
| 1893 |
return false; |
| 1894 |
} |
| 1895 |
|
| 1896 |
RootedScript script(cx, JS::Compile(cx, options, srcBuf)); |
| 1897 |
if (!script) { |
| 1898 |
return false; |
| 1899 |
} |
| 1900 |
if (compileOnly) { |
| 1901 |
return true; |
| 1902 |
} |
| 1903 |
RootedValue result(cx); |
| 1904 |
if (!JS_ExecuteScript(cx, script, &result)) { |
| 1905 |
return false; |
| 1906 |
} |
| 1907 |
|
| 1908 |
if (!result.isUndefined() && gOutFile->isOpen()) { |
| 1909 |
// Print. |
| 1910 |
RootedString str(cx, JS_ValueToSource(cx, result)); |
| 1911 |
if (!str) { |
| 1912 |
return false; |
| 1913 |
} |
| 1914 |
|
| 1915 |
UniqueChars utf8chars = JS_EncodeStringToUTF8(cx, str); |
| 1916 |
if (!utf8chars) { |
| 1917 |
return false; |
| 1918 |
} |
| 1919 |
fprintf(gOutFile->fp, "%s\n", utf8chars.get()); |
| 1920 |
} |
| 1921 |
return true; |
| 1922 |
} |
| 1923 |
|
| 1924 |
[[nodiscard]] static bool ReadEvalPrintLoop(JSContext* cx, FILE* in, |
| 1925 |
bool compileOnly) { |
| 1926 |
ShellContext* sc = GetShellContext(cx); |
| 1927 |
int lineno = 1; |
| 1928 |
bool hitEOF = false; |
| 1929 |
|
| 1930 |
do { |
| 1931 |
/* |
| 1932 |
* Accumulate lines until we get a 'compilable unit' - one that either |
| 1933 |
* generates an error (before running out of source) or that compiles |
| 1934 |
* cleanly. This should be whenever we get a complete statement that |
| 1935 |
* coincides with the end of a line. |
| 1936 |
*/ |
| 1937 |
int startline = lineno; |
| 1938 |
using CharBuffer = Vector<char, 32>; |
| 1939 |
RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment()); |
| 1940 |
CharBuffer buffer(cx); |
| 1941 |
do { |
| 1942 |
ScheduleWatchdog(cx, -1); |
| 1943 |
sc->serviceInterrupt = false; |
| 1944 |
errno = 0; |
| 1945 |
|
| 1946 |
mozilla::UniqueFreePtr<char[]> line = |
| 1947 |
GetLine(in, startline == lineno ? "js> " : ""); |
| 1948 |
if (!line) { |
| 1949 |
if (errno) { |
| 1950 |
if (UniqueChars error = SystemErrorMessage(cx, errno)) { |
| 1951 |
JS_ReportErrorUTF8(cx, "%s", error.get()); |
| 1952 |
} |
| 1953 |
return false; |
| 1954 |
} |
| 1955 |
hitEOF = true; |
| 1956 |
break; |
| 1957 |
} |
| 1958 |
|
| 1959 |
if (!buffer.append(line.get(), strlen(line.get())) || |
| 1960 |
!buffer.append('\n')) { |
| 1961 |
return false; |
| 1962 |
} |
| 1963 |
|
| 1964 |
lineno++; |
| 1965 |
if (!ScheduleWatchdog(cx, sc->timeoutInterval)) { |
| 1966 |
hitEOF = true; |
| 1967 |
break; |
| 1968 |
} |
| 1969 |
} while (!JS_Utf8BufferIsCompilableUnit(cx, cx->global(), buffer.begin(), |
| 1970 |
buffer.length())); |
| 1971 |
|
| 1972 |
if (hitEOF && buffer.empty()) { |
| 1973 |
break; |
| 1974 |
} |
| 1975 |
|
| 1976 |
{ |
| 1977 |
// Report exceptions but keep going. |
| 1978 |
AutoReportException are(cx); |
| 1979 |
(void)EvalUtf8AndPrint(cx, buffer.begin(), buffer.length(), startline, |
| 1980 |
compileOnly); |
| 1981 |
} |
| 1982 |
|
| 1983 |
// If a let or const fail to initialize they will remain in an unusable |
| 1984 |
// without further intervention. This call cleans up the global scope, |
| 1985 |
// setting uninitialized lexicals to undefined so that they may still |
| 1986 |
// be used. This behavior is _only_ acceptable in the context of the repl. |
| 1987 |
if (JS::ForceLexicalInitialization(cx, globalLexical) && |
| 1988 |
gErrFile->isOpen()) { |
| 1989 |
fputs( |
| 1990 |
"Warning: According to the standard, after the above exception,\n" |
| 1991 |
"Warning: the global bindings should be permanently uninitialized.\n" |
| 1992 |
"Warning: We have non-standard-ly initialized them to `undefined`" |
| 1993 |
"for you.\nWarning: This nicety only happens in the JS shell.\n", |
| 1994 |
stderr); |
| 1995 |
} |
| 1996 |
|
| 1997 |
RunShellJobs(cx); |
| 1998 |
} while (!hitEOF && !sc->quitting); |
| 1999 |
|
| 2000 |
if (gOutFile->isOpen()) { |
| 2001 |
fprintf(gOutFile->fp, "\n"); |
| 2002 |
} |
| 2003 |
|
| 2004 |
return true; |
| 2005 |
} |
| 2006 |
|
| 2007 |
enum FileKind { |
| 2008 |
PreludeScript, // UTF-8 script, fully-parsed, to avoid conflicting |
| 2009 |
// configurations. |
| 2010 |
FileScript, // UTF-8, directly parsed as such |
| 2011 |
FileScriptUtf16, // FileScript, but inflate to UTF-16 before parsing |
| 2012 |
FileModule, |
| 2013 |
}; |
| 2014 |
|
| 2015 |
[[nodiscard]] static bool Process(JSContext* cx, const char* filename, |
| 2016 |
bool forceTTY, FileKind kind) { |
| 2017 |
FILE* file; |
| 2018 |
if (forceTTY || !filename || strcmp(filename, "-") == 0) { |
| 2019 |
file = stdin; |
| 2020 |
} else { |
| 2021 |
file = OpenFile(cx, filename, "rb"); |
| 2022 |
if (!file) { |
| 2023 |
return false; |
| 2024 |
} |
| 2025 |
} |
| 2026 |
AutoCloseFile autoClose(file); |
| 2027 |
|
| 2028 |
bool fullParse = false; |
| 2029 |
if (!forceTTY && !isatty(fileno(file))) { |
| 2030 |
// It's not interactive - just execute it. |
| 2031 |
switch (kind) { |
| 2032 |
case PreludeScript: |
| 2033 |
fullParse = true; |
| 2034 |
if (!RunFile(cx, filename, file, CompileUtf8::DontInflate, compileOnly, |
| 2035 |
fullParse)) { |
| 2036 |
return false; |
| 2037 |
} |
| 2038 |
break; |
| 2039 |
case FileScript: |
| 2040 |
if (!RunFile(cx, filename, file, CompileUtf8::DontInflate, compileOnly, |
| 2041 |
fullParse)) { |
| 2042 |
return false; |
| 2043 |
} |
| 2044 |
break; |
| 2045 |
case FileScriptUtf16: |
| 2046 |
if (!RunFile(cx, filename, file, CompileUtf8::InflateToUtf16, |
| 2047 |
compileOnly, fullParse)) { |
| 2048 |
return false; |
| 2049 |
} |
| 2050 |
break; |
| 2051 |
case FileModule: |
| 2052 |
if (!RunModule(cx, filename, compileOnly)) { |
| 2053 |
return false; |
| 2054 |
} |
| 2055 |
break; |
| 2056 |
default: |
| 2057 |
MOZ_CRASH("Impossible FileKind!"); |
| 2058 |
} |
| 2059 |
} else { |
| 2060 |
// It's an interactive filehandle; drop into read-eval-print loop. |
| 2061 |
MOZ_ASSERT(kind == FileScript); |
| 2062 |
if (!ReadEvalPrintLoop(cx, file, compileOnly)) { |
| 2063 |
return false; |
| 2064 |
} |
| 2065 |
} |
| 2066 |
#ifdef FUZZING_JS_FUZZILLI |
| 2067 |
fprintf(stderr, "executionHash is 0x%x with %d inputs\n", cx->executionHash, |
| 2068 |
cx->executionHashInputs); |
| 2069 |
#endif |
| 2070 |
return true; |
| 2071 |
} |
| 2072 |
|
| 2073 |
#ifdef XP_WIN |
| 2074 |
# define GET_FD_FROM_FILE(a) int(_get_osfhandle(fileno(a))) |
| 2075 |
#else |
| 2076 |
# define GET_FD_FROM_FILE(a) fileno(a) |
| 2077 |
#endif |
| 2078 |
|
| 2079 |
static void freeExternalCallback(void* contents, void* userData) { |
| 2080 |
MOZ_ASSERT(!userData); |
| 2081 |
js_free(contents); |
| 2082 |
} |
| 2083 |
|
| 2084 |
static bool CreateExternalArrayBuffer(JSContext* cx, unsigned argc, Value* vp) { |
| 2085 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2086 |
if (args.length() != 1) { |
| 2087 |
JS_ReportErrorNumberASCII( |
| 2088 |
cx, my_GetErrorMessage, nullptr, |
| 2089 |
args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, |
| 2090 |
"createExternalArrayBuffer"); |
| 2091 |
return false; |
| 2092 |
} |
| 2093 |
|
| 2094 |
int32_t bytes = 0; |
| 2095 |
if (!ToInt32(cx, args[0], &bytes)) { |
| 2096 |
return false; |
| 2097 |
} |
| 2098 |
|
| 2099 |
if (bytes < 0) { |
| 2100 |
JS_ReportErrorASCII(cx, "Size must be non-negative"); |
| 2101 |
return false; |
| 2102 |
} |
| 2103 |
|
| 2104 |
void* buffer = js_calloc(bytes); |
| 2105 |
if (!buffer) { |
| 2106 |
JS_ReportOutOfMemory(cx); |
| 2107 |
return false; |
| 2108 |
} |
| 2109 |
|
| 2110 |
UniquePtr<void, JS::BufferContentsDeleter> ptr{buffer, |
| 2111 |
{&freeExternalCallback}}; |
| 2112 |
RootedObject arrayBuffer( |
| 2113 |
cx, JS::NewExternalArrayBuffer(cx, bytes, std::move(ptr))); |
| 2114 |
if (!arrayBuffer) { |
| 2115 |
return false; |
| 2116 |
} |
| 2117 |
|
| 2118 |
args.rval().setObject(*arrayBuffer); |
| 2119 |
return true; |
| 2120 |
} |
| 2121 |
|
| 2122 |
static bool CreateMappedArrayBuffer(JSContext* cx, unsigned argc, Value* vp) { |
| 2123 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2124 |
|
| 2125 |
if (args.length() < 1 || args.length() > 3) { |
| 2126 |
JS_ReportErrorNumberASCII( |
| 2127 |
cx, my_GetErrorMessage, nullptr, |
| 2128 |
args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, |
| 2129 |
"createMappedArrayBuffer"); |
| 2130 |
return false; |
| 2131 |
} |
| 2132 |
|
| 2133 |
RootedString rawFilenameStr(cx, JS::ToString(cx, args[0])); |
| 2134 |
if (!rawFilenameStr) { |
| 2135 |
return false; |
| 2136 |
} |
| 2137 |
// It's a little bizarre to resolve relative to the script, but for testing |
| 2138 |
// I need a file at a known location, and the only good way I know of to do |
| 2139 |
// that right now is to include it in the repo alongside the test script. |
| 2140 |
// Bug 944164 would introduce an alternative. |
| 2141 |
Rooted<JSString*> filenameStr( |
| 2142 |
cx, ResolvePath(cx, rawFilenameStr, ScriptRelative)); |
| 2143 |
if (!filenameStr) { |
| 2144 |
return false; |
| 2145 |
} |
| 2146 |
UniqueChars filename = JS_EncodeStringToUTF8(cx, filenameStr); |
| 2147 |
if (!filename) { |
| 2148 |
return false; |
| 2149 |
} |
| 2150 |
|
| 2151 |
uint32_t offset = 0; |
| 2152 |
if (args.length() >= 2) { |
| 2153 |
if (!JS::ToUint32(cx, args[1], &offset)) { |
| 2154 |
return false; |
| 2155 |
} |
| 2156 |
} |
| 2157 |
|
| 2158 |
bool sizeGiven = false; |
| 2159 |
uint32_t size; |
| 2160 |
if (args.length() >= 3) { |
| 2161 |
if (!JS::ToUint32(cx, args[2], &size)) { |
| 2162 |
return false; |
| 2163 |
} |
| 2164 |
sizeGiven = true; |
| 2165 |
if (size == 0) { |
| 2166 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 2167 |
JSMSG_BAD_ARRAY_LENGTH); |
| 2168 |
return false; |
| 2169 |
} |
| 2170 |
} |
| 2171 |
|
| 2172 |
FILE* file = OpenFile(cx, filename.get(), "rb"); |
| 2173 |
if (!file) { |
| 2174 |
return false; |
| 2175 |
} |
| 2176 |
AutoCloseFile autoClose(file); |
| 2177 |
|
| 2178 |
struct stat st; |
| 2179 |
if (fstat(fileno(file), &st) < 0) { |
| 2180 |
JS_ReportErrorASCII(cx, "Unable to stat file"); |
| 2181 |
return false; |
| 2182 |
} |
| 2183 |
|
| 2184 |
if ((st.st_mode & S_IFMT) != S_IFREG) { |
| 2185 |
JS_ReportErrorASCII(cx, "Path is not a regular file"); |
| 2186 |
return false; |
| 2187 |
} |
| 2188 |
|
| 2189 |
if (!sizeGiven) { |
| 2190 |
if (off_t(offset) >= st.st_size) { |
| 2191 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 2192 |
JSMSG_OFFSET_LARGER_THAN_FILESIZE); |
| 2193 |
return false; |
| 2194 |
} |
| 2195 |
size = st.st_size - offset; |
| 2196 |
} |
| 2197 |
|
| 2198 |
void* contents = |
| 2199 |
JS::CreateMappedArrayBufferContents(GET_FD_FROM_FILE(file), offset, size); |
| 2200 |
if (!contents) { |
| 2201 |
JS_ReportErrorASCII(cx, |
| 2202 |
"failed to allocate mapped array buffer contents " |
| 2203 |
"(possibly due to bad alignment)"); |
| 2204 |
return false; |
| 2205 |
} |
| 2206 |
|
| 2207 |
RootedObject obj(cx, |
| 2208 |
JS::NewMappedArrayBufferWithContents(cx, size, contents)); |
| 2209 |
if (!obj) { |
| 2210 |
return false; |
| 2211 |
} |
| 2212 |
|
| 2213 |
args.rval().setObject(*obj); |
| 2214 |
return true; |
| 2215 |
} |
| 2216 |
|
| 2217 |
#undef GET_FD_FROM_FILE |
| 2218 |
|
| 2219 |
class UserBufferObject : public NativeObject { |
| 2220 |
static const uint32_t BUFFER_SLOT = 0; |
| 2221 |
static const uint32_t BYTE_LENGTH_SLOT = 1; |
| 2222 |
static const uint32_t RESERVED_SLOTS = 2; |
| 2223 |
|
| 2224 |
static constexpr auto BufferMemoryUse = MemoryUse::Embedding1; |
| 2225 |
|
| 2226 |
static void finalize(JS::GCContext* gcx, JSObject* obj); |
| 2227 |
|
| 2228 |
public: |
| 2229 |
static const JSClassOps classOps_; |
| 2230 |
static const JSClass class_; |
| 2231 |
|
| 2232 |
[[nodiscard]] static UserBufferObject* create(JSContext* cx, |
| 2233 |
size_t byteLength); |
| 2234 |
|
| 2235 |
void* buffer() const { |
| 2236 |
auto& buffer = getReservedSlot(BUFFER_SLOT); |
| 2237 |
if (buffer.isUndefined()) { |
| 2238 |
return nullptr; |
| 2239 |
} |
| 2240 |
return buffer.toPrivate(); |
| 2241 |
} |
| 2242 |
|
| 2243 |
size_t byteLength() const { |
| 2244 |
return size_t(getReservedSlot(BYTE_LENGTH_SLOT).toPrivate()); |
| 2245 |
} |
| 2246 |
}; |
| 2247 |
|
| 2248 |
const JSClassOps UserBufferObject::classOps_ = { |
| 2249 |
nullptr, // addProperty |
| 2250 |
nullptr, // delProperty |
| 2251 |
nullptr, // enumerate |
| 2252 |
nullptr, // newEnumerate |
| 2253 |
nullptr, // resolve |
| 2254 |
nullptr, // mayResolve |
| 2255 |
UserBufferObject::finalize, // finalize |
| 2256 |
nullptr, // call |
| 2257 |
nullptr, // construct |
| 2258 |
nullptr, // trace |
| 2259 |
}; |
| 2260 |
|
| 2261 |
const JSClass UserBufferObject::class_ = { |
| 2262 |
"UserBufferObject", |
| 2263 |
JSCLASS_HAS_RESERVED_SLOTS(UserBufferObject::RESERVED_SLOTS) | |
| 2264 |
JSCLASS_BACKGROUND_FINALIZE, |
| 2265 |
&UserBufferObject::classOps_, |
| 2266 |
}; |
| 2267 |
|
| 2268 |
UserBufferObject* UserBufferObject::create(JSContext* cx, size_t byteLength) { |
| 2269 |
void* buffer = js_calloc(byteLength); |
| 2270 |
if (!buffer) { |
| 2271 |
JS_ReportOutOfMemory(cx); |
| 2272 |
return nullptr; |
| 2273 |
} |
| 2274 |
UniquePtr<void, JS::FreePolicy> ptr(buffer); |
| 2275 |
|
| 2276 |
auto* userBuffer = NewObjectWithGivenProto<UserBufferObject>(cx, nullptr); |
| 2277 |
if (!userBuffer) { |
| 2278 |
return nullptr; |
| 2279 |
} |
| 2280 |
|
| 2281 |
InitReservedSlot(userBuffer, BUFFER_SLOT, ptr.release(), byteLength, |
| 2282 |
BufferMemoryUse); |
| 2283 |
userBuffer->initReservedSlot(BYTE_LENGTH_SLOT, PrivateValue(byteLength)); |
| 2284 |
|
| 2285 |
return userBuffer; |
| 2286 |
} |
| 2287 |
|
| 2288 |
void UserBufferObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 2289 |
auto* userBuffer = &obj->as<UserBufferObject>(); |
| 2290 |
if (auto* buffer = userBuffer->buffer()) { |
| 2291 |
gcx->free_(userBuffer, buffer, userBuffer->byteLength(), BufferMemoryUse); |
| 2292 |
} |
| 2293 |
} |
| 2294 |
|
| 2295 |
static bool CreateUserArrayBuffer(JSContext* cx, unsigned argc, Value* vp) { |
| 2296 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2297 |
if (args.length() != 1) { |
| 2298 |
JS_ReportErrorNumberASCII( |
| 2299 |
cx, my_GetErrorMessage, nullptr, |
| 2300 |
args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, |
| 2301 |
"createUserArrayBuffer"); |
| 2302 |
return false; |
| 2303 |
} |
| 2304 |
|
| 2305 |
int32_t bytes = 0; |
| 2306 |
if (!ToInt32(cx, args[0], &bytes)) { |
| 2307 |
return false; |
| 2308 |
} |
| 2309 |
if (bytes < 0) { |
| 2310 |
JS_ReportErrorASCII(cx, "Size must be non-negative"); |
| 2311 |
return false; |
| 2312 |
} |
| 2313 |
|
| 2314 |
Rooted<UserBufferObject*> userBuffer(cx, UserBufferObject::create(cx, bytes)); |
| 2315 |
if (!userBuffer) { |
| 2316 |
return false; |
| 2317 |
} |
| 2318 |
|
| 2319 |
Rooted<JSObject*> arrayBuffer( |
| 2320 |
cx, JS::NewArrayBufferWithUserOwnedContents(cx, userBuffer->byteLength(), |
| 2321 |
userBuffer->buffer())); |
| 2322 |
if (!arrayBuffer) { |
| 2323 |
return false; |
| 2324 |
} |
| 2325 |
|
| 2326 |
// Create a strong reference from |arrayBuffer| to |userBuffer|. This ensures |
| 2327 |
// |userBuffer| can't outlive |arrayBuffer|. That way we don't have to worry |
| 2328 |
// about detaching the ArrayBuffer object when |userBuffer| gets finalized. |
| 2329 |
// The reference is made through a private name, because we don't want to |
| 2330 |
// expose |userBuffer| to user-code. |
| 2331 |
|
| 2332 |
auto* privateName = NewPrivateName(cx, cx->names().empty_.toHandle()); |
| 2333 |
if (!privateName) { |
| 2334 |
return false; |
| 2335 |
} |
| 2336 |
|
| 2337 |
Rooted<PropertyKey> id(cx, PropertyKey::Symbol(privateName)); |
| 2338 |
Rooted<JS::Value> userBufferVal(cx, ObjectValue(*userBuffer)); |
| 2339 |
if (!js::DefineDataProperty(cx, arrayBuffer, id, userBufferVal, 0)) { |
| 2340 |
return false; |
| 2341 |
} |
| 2342 |
|
| 2343 |
args.rval().setObject(*arrayBuffer); |
| 2344 |
return true; |
| 2345 |
} |
| 2346 |
|
| 2347 |
static bool AddPromiseReactions(JSContext* cx, unsigned argc, Value* vp) { |
| 2348 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2349 |
|
| 2350 |
if (args.length() != 3) { |
| 2351 |
JS_ReportErrorNumberASCII( |
| 2352 |
cx, my_GetErrorMessage, nullptr, |
| 2353 |
args.length() < 3 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, |
| 2354 |
"addPromiseReactions"); |
| 2355 |
return false; |
| 2356 |
} |
| 2357 |
|
| 2358 |
RootedObject promise(cx); |
| 2359 |
if (args[0].isObject()) { |
| 2360 |
promise = &args[0].toObject(); |
| 2361 |
} |
| 2362 |
|
| 2363 |
if (!promise || !JS::IsPromiseObject(promise)) { |
| 2364 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 2365 |
JSSMSG_INVALID_ARGS, "addPromiseReactions"); |
| 2366 |
return false; |
| 2367 |
} |
| 2368 |
|
| 2369 |
RootedObject onResolve(cx); |
| 2370 |
if (args[1].isObject()) { |
| 2371 |
onResolve = &args[1].toObject(); |
| 2372 |
} |
| 2373 |
|
| 2374 |
RootedObject onReject(cx); |
| 2375 |
if (args[2].isObject()) { |
| 2376 |
onReject = &args[2].toObject(); |
| 2377 |
} |
| 2378 |
|
| 2379 |
if (!onResolve || !onResolve->is<JSFunction>() || !onReject || |
| 2380 |
!onReject->is<JSFunction>()) { |
| 2381 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 2382 |
JSSMSG_INVALID_ARGS, "addPromiseReactions"); |
| 2383 |
return false; |
| 2384 |
} |
| 2385 |
|
| 2386 |
return JS::AddPromiseReactions(cx, promise, onResolve, onReject); |
| 2387 |
} |
| 2388 |
|
| 2389 |
static bool IgnoreUnhandledRejections(JSContext* cx, unsigned argc, Value* vp) { |
| 2390 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2391 |
|
| 2392 |
ShellContext* sc = GetShellContext(cx); |
| 2393 |
sc->trackUnhandledRejections = false; |
| 2394 |
|
| 2395 |
args.rval().setUndefined(); |
| 2396 |
return true; |
| 2397 |
} |
| 2398 |
|
| 2399 |
static bool Options(JSContext* cx, unsigned argc, Value* vp) { |
| 2400 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2401 |
|
| 2402 |
JS::ContextOptions oldContextOptions = JS::ContextOptionsRef(cx); |
| 2403 |
for (unsigned i = 0; i < args.length(); i++) { |
| 2404 |
RootedString str(cx, JS::ToString(cx, args[i])); |
| 2405 |
if (!str) { |
| 2406 |
return false; |
| 2407 |
} |
| 2408 |
|
| 2409 |
Rooted<JSLinearString*> opt(cx, str->ensureLinear(cx)); |
| 2410 |
if (!opt) { |
| 2411 |
return false; |
| 2412 |
} |
| 2413 |
|
| 2414 |
if (StringEqualsLiteral(opt, "throw_on_asmjs_validation_failure")) { |
| 2415 |
JS::ContextOptionsRef(cx).toggleThrowOnAsmJSValidationFailure(); |
| 2416 |
} else { |
| 2417 |
UniqueChars optChars = QuoteString(cx, opt, '"'); |
| 2418 |
if (!optChars) { |
| 2419 |
return false; |
| 2420 |
} |
| 2421 |
|
| 2422 |
JS_ReportErrorASCII(cx, |
| 2423 |
"unknown option name %s." |
| 2424 |
" The valid name is " |
| 2425 |
"throw_on_asmjs_validation_failure.", |
| 2426 |
optChars.get()); |
| 2427 |
return false; |
| 2428 |
} |
| 2429 |
} |
| 2430 |
|
| 2431 |
UniqueChars names = DuplicateString(""); |
| 2432 |
bool found = false; |
| 2433 |
if (names && oldContextOptions.throwOnAsmJSValidationFailure()) { |
| 2434 |
names = JS_sprintf_append(std::move(names), "%s%s", found ? "," : "", |
| 2435 |
"throw_on_asmjs_validation_failure"); |
| 2436 |
found = true; |
| 2437 |
} |
| 2438 |
if (!names) { |
| 2439 |
JS_ReportOutOfMemory(cx); |
| 2440 |
return false; |
| 2441 |
} |
| 2442 |
|
| 2443 |
JSString* str = JS_NewStringCopyZ(cx, names.get()); |
| 2444 |
if (!str) { |
| 2445 |
return false; |
| 2446 |
} |
| 2447 |
args.rval().setString(str); |
| 2448 |
return true; |
| 2449 |
} |
| 2450 |
|
| 2451 |
static bool LoadScript(JSContext* cx, unsigned argc, Value* vp, |
| 2452 |
bool scriptRelative) { |
| 2453 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2454 |
|
| 2455 |
RootedString str(cx); |
| 2456 |
for (unsigned i = 0; i < args.length(); i++) { |
| 2457 |
str = JS::ToString(cx, args[i]); |
| 2458 |
if (!str) { |
| 2459 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 2460 |
JSSMSG_INVALID_ARGS, "load"); |
| 2461 |
return false; |
| 2462 |
} |
| 2463 |
|
| 2464 |
str = ResolvePath(cx, str, scriptRelative ? ScriptRelative : RootRelative); |
| 2465 |
if (!str) { |
| 2466 |
JS_ReportErrorASCII(cx, "unable to resolve path"); |
| 2467 |
return false; |
| 2468 |
} |
| 2469 |
|
| 2470 |
UniqueChars filename = JS_EncodeStringToUTF8(cx, str); |
| 2471 |
if (!filename) { |
| 2472 |
return false; |
| 2473 |
} |
| 2474 |
|
| 2475 |
errno = 0; |
| 2476 |
|
| 2477 |
CompileOptions opts(cx); |
| 2478 |
opts.setIntroductionType("js shell load") |
| 2479 |
.setIsRunOnce(true) |
| 2480 |
.setNoScriptRval(true) |
| 2481 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 2482 |
|
| 2483 |
RootedValue unused(cx); |
| 2484 |
if (!(compileOnly |
| 2485 |
? JS::CompileUtf8Path(cx, opts, filename.get()) != nullptr |
| 2486 |
: JS::EvaluateUtf8Path(cx, opts, filename.get(), &unused))) { |
| 2487 |
return false; |
| 2488 |
} |
| 2489 |
} |
| 2490 |
|
| 2491 |
args.rval().setUndefined(); |
| 2492 |
return true; |
| 2493 |
} |
| 2494 |
|
| 2495 |
static bool Load(JSContext* cx, unsigned argc, Value* vp) { |
| 2496 |
return LoadScript(cx, argc, vp, false); |
| 2497 |
} |
| 2498 |
|
| 2499 |
static bool LoadScriptRelativeToScript(JSContext* cx, unsigned argc, |
| 2500 |
Value* vp) { |
| 2501 |
return LoadScript(cx, argc, vp, true); |
| 2502 |
} |
| 2503 |
|
| 2504 |
static void my_LargeAllocFailCallback() { |
| 2505 |
JSContext* cx = TlsContext.get(); |
| 2506 |
if (!cx) { |
| 2507 |
return; |
| 2508 |
} |
| 2509 |
|
| 2510 |
MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); |
| 2511 |
|
| 2512 |
JS::PrepareForFullGC(cx); |
| 2513 |
cx->runtime()->gc.gc(JS::GCOptions::Shrink, |
| 2514 |
JS::GCReason::SHARED_MEMORY_LIMIT); |
| 2515 |
} |
| 2516 |
|
| 2517 |
static const uint32_t CacheEntry_SOURCE = 0; |
| 2518 |
static const uint32_t CacheEntry_BYTECODE = 1; |
| 2519 |
static const uint32_t CacheEntry_OPTIONS = 2; |
| 2520 |
|
| 2521 |
// Some compile options can't be combined differently between save and load. |
| 2522 |
// |
| 2523 |
// CacheEntries store a CacheOption set, and on load an exception is thrown |
| 2524 |
// if the entries are incompatible. |
| 2525 |
|
| 2526 |
enum CacheOptions : uint32_t { |
| 2527 |
IsRunOnce, |
| 2528 |
NoScriptRval, |
| 2529 |
Global, |
| 2530 |
NonSyntactic, |
| 2531 |
SourceIsLazy, |
| 2532 |
ForceFullParse, |
| 2533 |
}; |
| 2534 |
|
| 2535 |
struct CacheOptionSet : public mozilla::EnumSet<CacheOptions> { |
| 2536 |
using mozilla::EnumSet<CacheOptions>::EnumSet; |
| 2537 |
|
| 2538 |
explicit CacheOptionSet(const CompileOptions& options) : EnumSet() { |
| 2539 |
initFromOptions(options); |
| 2540 |
} |
| 2541 |
|
| 2542 |
void initFromOptions(const CompileOptions& options) { |
| 2543 |
if (options.noScriptRval) { |
| 2544 |
*this += CacheOptions::NoScriptRval; |
| 2545 |
} |
| 2546 |
if (options.isRunOnce) { |
| 2547 |
*this += CacheOptions::IsRunOnce; |
| 2548 |
} |
| 2549 |
if (options.sourceIsLazy) { |
| 2550 |
*this += CacheOptions::SourceIsLazy; |
| 2551 |
} |
| 2552 |
if (options.forceFullParse()) { |
| 2553 |
*this += CacheOptions::ForceFullParse; |
| 2554 |
} |
| 2555 |
if (options.nonSyntacticScope) { |
| 2556 |
*this += CacheOptions::NonSyntactic; |
| 2557 |
} |
| 2558 |
} |
| 2559 |
}; |
| 2560 |
|
| 2561 |
static bool CacheOptionsCompatible(const CacheOptionSet& a, |
| 2562 |
const CacheOptionSet& b) { |
| 2563 |
// If the options are identical, they are trivially compatible. |
| 2564 |
return a == b; |
| 2565 |
} |
| 2566 |
|
| 2567 |
static const JSClass CacheEntry_class = { |
| 2568 |
"CacheEntryObject", |
| 2569 |
JSCLASS_HAS_RESERVED_SLOTS(3), |
| 2570 |
}; |
| 2571 |
|
| 2572 |
static bool CacheEntry(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 2573 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2574 |
|
| 2575 |
if (args.length() != 1 || !args[0].isString()) { |
| 2576 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 2577 |
JSSMSG_INVALID_ARGS, "CacheEntry"); |
| 2578 |
return false; |
| 2579 |
} |
| 2580 |
|
| 2581 |
RootedObject obj(cx, JS_NewObject(cx, &CacheEntry_class)); |
| 2582 |
if (!obj) { |
| 2583 |
return false; |
| 2584 |
} |
| 2585 |
|
| 2586 |
JS::SetReservedSlot(obj, CacheEntry_SOURCE, args[0]); |
| 2587 |
JS::SetReservedSlot(obj, CacheEntry_BYTECODE, UndefinedValue()); |
| 2588 |
|
| 2589 |
// Fill in empty option set. |
| 2590 |
CacheOptionSet defaultOptions; |
| 2591 |
JS::SetReservedSlot(obj, CacheEntry_OPTIONS, |
| 2592 |
Int32Value(defaultOptions.serialize())); |
| 2593 |
|
| 2594 |
args.rval().setObject(*obj); |
| 2595 |
return true; |
| 2596 |
} |
| 2597 |
|
| 2598 |
static bool CacheEntry_isCacheEntry(JSObject* cache) { |
| 2599 |
return cache->hasClass(&CacheEntry_class); |
| 2600 |
} |
| 2601 |
|
| 2602 |
static JSString* CacheEntry_getSource(JSContext* cx, HandleObject cache) { |
| 2603 |
MOZ_ASSERT(CacheEntry_isCacheEntry(cache)); |
| 2604 |
Value v = JS::GetReservedSlot(cache, CacheEntry_SOURCE); |
| 2605 |
if (!v.isString()) { |
| 2606 |
JS_ReportErrorASCII( |
| 2607 |
cx, "CacheEntry_getSource: Unexpected type of source reserved slot."); |
| 2608 |
return nullptr; |
| 2609 |
} |
| 2610 |
|
| 2611 |
return v.toString(); |
| 2612 |
} |
| 2613 |
|
| 2614 |
static bool CacheEntry_compatible(JSContext* cx, HandleObject cache, |
| 2615 |
const CacheOptionSet& currentOptionSet) { |
| 2616 |
CacheOptionSet cacheEntryOptions; |
| 2617 |
MOZ_ASSERT(CacheEntry_isCacheEntry(cache)); |
| 2618 |
Value v = JS::GetReservedSlot(cache, CacheEntry_OPTIONS); |
| 2619 |
cacheEntryOptions.deserialize(v.toInt32()); |
| 2620 |
if (!CacheOptionsCompatible(cacheEntryOptions, currentOptionSet)) { |
| 2621 |
JS_ReportErrorASCII(cx, |
| 2622 |
"CacheEntry_compatible: Incompatible cache contents"); |
| 2623 |
return false; |
| 2624 |
} |
| 2625 |
return true; |
| 2626 |
} |
| 2627 |
|
| 2628 |
static uint8_t* CacheEntry_getBytecode(JSContext* cx, HandleObject cache, |
| 2629 |
size_t* length) { |
| 2630 |
MOZ_ASSERT(CacheEntry_isCacheEntry(cache)); |
| 2631 |
Value v = JS::GetReservedSlot(cache, CacheEntry_BYTECODE); |
| 2632 |
if (!v.isObject() || !v.toObject().is<ArrayBufferObject>()) { |
| 2633 |
JS_ReportErrorASCII( |
| 2634 |
cx, |
| 2635 |
"CacheEntry_getBytecode: Unexpected type of bytecode reserved slot."); |
| 2636 |
return nullptr; |
| 2637 |
} |
| 2638 |
|
| 2639 |
ArrayBufferObject* arrayBuffer = &v.toObject().as<ArrayBufferObject>(); |
| 2640 |
*length = arrayBuffer->byteLength(); |
| 2641 |
return arrayBuffer->dataPointer(); |
| 2642 |
} |
| 2643 |
|
| 2644 |
static bool CacheEntry_setBytecode(JSContext* cx, HandleObject cache, |
| 2645 |
const CacheOptionSet& cacheOptions, |
| 2646 |
uint8_t* buffer, uint32_t length) { |
| 2647 |
MOZ_ASSERT(CacheEntry_isCacheEntry(cache)); |
| 2648 |
|
| 2649 |
using BufferContents = ArrayBufferObject::BufferContents; |
| 2650 |
|
| 2651 |
BufferContents contents = BufferContents::createMallocedUnknownArena(buffer); |
| 2652 |
Rooted<ArrayBufferObject*> arrayBuffer( |
| 2653 |
cx, ArrayBufferObject::createForContents(cx, length, contents)); |
| 2654 |
if (!arrayBuffer) { |
| 2655 |
return false; |
| 2656 |
} |
| 2657 |
|
| 2658 |
JS::SetReservedSlot(cache, CacheEntry_BYTECODE, ObjectValue(*arrayBuffer)); |
| 2659 |
JS::SetReservedSlot(cache, CacheEntry_OPTIONS, |
| 2660 |
Int32Value(cacheOptions.serialize())); |
| 2661 |
return true; |
| 2662 |
} |
| 2663 |
|
| 2664 |
static bool ConvertTranscodeResultToJSException(JSContext* cx, |
| 2665 |
JS::TranscodeResult rv) { |
| 2666 |
switch (rv) { |
| 2667 |
case JS::TranscodeResult::Ok: |
| 2668 |
return true; |
| 2669 |
|
| 2670 |
default: |
| 2671 |
[[fallthrough]]; |
| 2672 |
case JS::TranscodeResult::Failure: |
| 2673 |
MOZ_ASSERT(!cx->isExceptionPending()); |
| 2674 |
JS_ReportErrorASCII(cx, "generic warning"); |
| 2675 |
return false; |
| 2676 |
case JS::TranscodeResult::Failure_BadBuildId: |
| 2677 |
MOZ_ASSERT(!cx->isExceptionPending()); |
| 2678 |
JS_ReportErrorASCII(cx, "the build-id does not match"); |
| 2679 |
return false; |
| 2680 |
case JS::TranscodeResult::Failure_AsmJSNotSupported: |
| 2681 |
MOZ_ASSERT(!cx->isExceptionPending()); |
| 2682 |
JS_ReportErrorASCII(cx, "Asm.js is not supported by XDR"); |
| 2683 |
return false; |
| 2684 |
case JS::TranscodeResult::Failure_BadDecode: |
| 2685 |
MOZ_ASSERT(!cx->isExceptionPending()); |
| 2686 |
JS_ReportErrorASCII(cx, "XDR data corruption"); |
| 2687 |
return false; |
| 2688 |
|
| 2689 |
case JS::TranscodeResult::Throw: |
| 2690 |
MOZ_ASSERT(cx->isExceptionPending()); |
| 2691 |
return false; |
| 2692 |
} |
| 2693 |
} |
| 2694 |
|
| 2695 |
static void SetQuitting(JSContext* cx, int32_t code) { |
| 2696 |
ShellContext* sc = GetShellContext(cx); |
| 2697 |
js::StopDrainingJobQueue(cx); |
| 2698 |
sc->exitCode = code; |
| 2699 |
sc->quitting = true; |
| 2700 |
} |
| 2701 |
|
| 2702 |
static void UnsetQuitting(JSContext* cx) { |
| 2703 |
ShellContext* sc = GetShellContext(cx); |
| 2704 |
js::RestartDrainingJobQueue(cx); |
| 2705 |
sc->exitCode = 0; |
| 2706 |
sc->quitting = false; |
| 2707 |
} |
| 2708 |
|
| 2709 |
static bool Evaluate(JSContext* cx, unsigned argc, Value* vp) { |
| 2710 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 2711 |
|
| 2712 |
if (args.length() < 1 || args.length() > 2) { |
| 2713 |
JS_ReportErrorNumberASCII( |
| 2714 |
cx, my_GetErrorMessage, nullptr, |
| 2715 |
args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS, |
| 2716 |
"evaluate"); |
| 2717 |
return false; |
| 2718 |
} |
| 2719 |
|
| 2720 |
RootedString code(cx, nullptr); |
| 2721 |
RootedObject cacheEntry(cx, nullptr); |
| 2722 |
if (args[0].isString()) { |
| 2723 |
code = args[0].toString(); |
| 2724 |
} else if (args[0].isObject() && |
| 2725 |
CacheEntry_isCacheEntry(&args[0].toObject())) { |
| 2726 |
cacheEntry = &args[0].toObject(); |
| 2727 |
code = CacheEntry_getSource(cx, cacheEntry); |
| 2728 |
if (!code) { |
| 2729 |
return false; |
| 2730 |
} |
| 2731 |
} |
| 2732 |
|
| 2733 |
if (!code || (args.length() == 2 && args[1].isPrimitive())) { |
| 2734 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 2735 |
JSSMSG_INVALID_ARGS, "evaluate"); |
| 2736 |
return false; |
| 2737 |
} |
| 2738 |
|
| 2739 |
RootedObject opts(cx); |
| 2740 |
if (args.length() == 2) { |
| 2741 |
if (!args[1].isObject()) { |
| 2742 |
JS_ReportErrorASCII(cx, "evaluate: The 2nd argument must be an object"); |
| 2743 |
return false; |
| 2744 |
} |
| 2745 |
|
| 2746 |
opts = &args[1].toObject(); |
| 2747 |
} |
| 2748 |
|
| 2749 |
RootedObject global(cx, JS::CurrentGlobalOrNull(cx)); |
| 2750 |
MOZ_ASSERT(global); |
| 2751 |
|
| 2752 |
// Check "global" property before everything to use the given global's |
| 2753 |
// option as the default value. |
| 2754 |
Maybe<CompileOptions> maybeOptions; |
| 2755 |
if (opts) { |
| 2756 |
RootedValue v(cx); |
| 2757 |
if (!JS_GetProperty(cx, opts, "global", &v)) { |
| 2758 |
return false; |
| 2759 |
} |
| 2760 |
if (!v.isUndefined()) { |
| 2761 |
if (v.isObject()) { |
| 2762 |
global = js::CheckedUnwrapDynamic(&v.toObject(), cx, |
| 2763 |
/* stopAtWindowProxy = */ false); |
| 2764 |
if (!global) { |
| 2765 |
return false; |
| 2766 |
} |
| 2767 |
} |
| 2768 |
if (!global || !(JS::GetClass(global)->flags & JSCLASS_IS_GLOBAL)) { |
| 2769 |
JS_ReportErrorNumberASCII( |
| 2770 |
cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, |
| 2771 |
"\"global\" passed to evaluate()", "not a global object"); |
| 2772 |
return false; |
| 2773 |
} |
| 2774 |
|
| 2775 |
JSAutoRealm ar(cx, global); |
| 2776 |
maybeOptions.emplace(cx); |
| 2777 |
} |
| 2778 |
} |
| 2779 |
if (!maybeOptions) { |
| 2780 |
// If "global" property is not given, use the current global's option as |
| 2781 |
// the default value. |
| 2782 |
maybeOptions.emplace(cx); |
| 2783 |
} |
| 2784 |
|
| 2785 |
CompileOptions& options = maybeOptions.ref(); |
| 2786 |
UniqueChars fileNameBytes; |
| 2787 |
RootedString displayURL(cx); |
| 2788 |
RootedString sourceMapURL(cx); |
| 2789 |
bool catchTermination = false; |
| 2790 |
bool loadBytecode = false; |
| 2791 |
bool saveBytecodeWithDelazifications = false; |
| 2792 |
bool execute = true; |
| 2793 |
bool assertEqBytecode = false; |
| 2794 |
JS::EnvironmentChain envChain(cx, JS::SupportUnscopables::No); |
| 2795 |
RootedObject callerGlobal(cx, cx->global()); |
| 2796 |
|
| 2797 |
options.setIntroductionType("js shell evaluate") |
| 2798 |
.setFileAndLine("@evaluate", 1) |
| 2799 |
.setDeferDebugMetadata(); |
| 2800 |
|
| 2801 |
RootedValue privateValue(cx); |
| 2802 |
RootedString elementAttributeName(cx); |
| 2803 |
|
| 2804 |
if (opts) { |
| 2805 |
if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) { |
| 2806 |
return false; |
| 2807 |
} |
| 2808 |
if (!ParseDebugMetadata(cx, opts, &privateValue, &elementAttributeName)) { |
| 2809 |
return false; |
| 2810 |
} |
| 2811 |
if (!ParseSourceOptions(cx, opts, &displayURL, &sourceMapURL)) { |
| 2812 |
return false; |
| 2813 |
} |
| 2814 |
|
| 2815 |
RootedValue v(cx); |
| 2816 |
if (!JS_GetProperty(cx, opts, "catchTermination", &v)) { |
| 2817 |
return false; |
| 2818 |
} |
| 2819 |
if (!v.isUndefined()) { |
| 2820 |
catchTermination = ToBoolean(v); |
| 2821 |
} |
| 2822 |
|
| 2823 |
if (!JS_GetProperty(cx, opts, "loadBytecode", &v)) { |
| 2824 |
return false; |
| 2825 |
} |
| 2826 |
if (!v.isUndefined()) { |
| 2827 |
loadBytecode = ToBoolean(v); |
| 2828 |
} |
| 2829 |
|
| 2830 |
if (!JS_GetProperty(cx, opts, "saveBytecodeWithDelazifications", &v)) { |
| 2831 |
return false; |
| 2832 |
} |
| 2833 |
if (!v.isUndefined()) { |
| 2834 |
saveBytecodeWithDelazifications = ToBoolean(v); |
| 2835 |
} |
| 2836 |
|
| 2837 |
if (!JS_GetProperty(cx, opts, "execute", &v)) { |
| 2838 |
return false; |
| 2839 |
} |
| 2840 |
if (!v.isUndefined()) { |
| 2841 |
execute = ToBoolean(v); |
| 2842 |
} |
| 2843 |
|
| 2844 |
if (!JS_GetProperty(cx, opts, "assertEqBytecode", &v)) { |
| 2845 |
return false; |
| 2846 |
} |
| 2847 |
if (!v.isUndefined()) { |
| 2848 |
assertEqBytecode = ToBoolean(v); |
| 2849 |
} |
| 2850 |
|
| 2851 |
if (!JS_GetProperty(cx, opts, "envChainObject", &v)) { |
| 2852 |
return false; |
| 2853 |
} |
| 2854 |
if (!v.isUndefined()) { |
| 2855 |
if (!v.isObject()) { |
| 2856 |
JS_ReportErrorNumberASCII( |
| 2857 |
cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, |
| 2858 |
"\"envChainObject\" passed to evaluate()", "not an object"); |
| 2859 |
return false; |
| 2860 |
} |
| 2861 |
|
| 2862 |
RootedObject obj(cx, &v.toObject()); |
| 2863 |
{ |
| 2864 |
// This may be a CCW, so try to unwrap before checking |
| 2865 |
// if it is an unqualified variables object. We still append |
| 2866 |
// the original object to the environment chain however. |
| 2867 |
JSObject* unwrappedObj = js::UncheckedUnwrap(obj, cx); |
| 2868 |
if (unwrappedObj->isUnqualifiedVarObj()) { |
| 2869 |
JS_ReportErrorASCII( |
| 2870 |
cx, |
| 2871 |
"\"envChainObject\" passed to evaluate() should not be an " |
| 2872 |
"unqualified variables object"); |
| 2873 |
return false; |
| 2874 |
} |
| 2875 |
} |
| 2876 |
|
| 2877 |
if (!envChain.append(obj)) { |
| 2878 |
return false; |
| 2879 |
} |
| 2880 |
} |
| 2881 |
|
| 2882 |
if (!JS_GetProperty(cx, opts, "supportUnscopables", &v)) { |
| 2883 |
return false; |
| 2884 |
} |
| 2885 |
if (!v.isUndefined()) { |
| 2886 |
envChain.setSupportUnscopables(JS::SupportUnscopables(ToBoolean(v))); |
| 2887 |
} |
| 2888 |
|
| 2889 |
// We cannot load or save the bytecode if we have no object where the |
| 2890 |
// bytecode cache is stored. |
| 2891 |
if (loadBytecode || saveBytecodeWithDelazifications) { |
| 2892 |
if (!cacheEntry) { |
| 2893 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 2894 |
JSSMSG_INVALID_ARGS, "evaluate"); |
| 2895 |
return false; |
| 2896 |
} |
| 2897 |
} |
| 2898 |
} |
| 2899 |
|
| 2900 |
if (envChain.length() != 0) { |
| 2901 |
// Wrap the envChainObject list into target realm. |
| 2902 |
JSAutoRealm ar(cx, global); |
| 2903 |
for (size_t i = 0; i < envChain.length(); ++i) { |
| 2904 |
if (!JS_WrapObject(cx, envChain.chain()[i])) { |
| 2905 |
return false; |
| 2906 |
} |
| 2907 |
} |
| 2908 |
|
| 2909 |
options.setNonSyntacticScope(true); |
| 2910 |
} |
| 2911 |
|
| 2912 |
// The `loadBuffer` we use below outlives the Stencil we generate so we can |
| 2913 |
// use its contents directly in the Stencil. |
| 2914 |
options.borrowBuffer = true; |
| 2915 |
|
| 2916 |
// We need to track the options used to generate bytecode for a CacheEntry to |
| 2917 |
// avoid mismatches. This is primarily a concern when fuzzing the jsshell. |
| 2918 |
CacheOptionSet cacheOptions; |
| 2919 |
cacheOptions.initFromOptions(options); |
| 2920 |
|
| 2921 |
JS::TranscodeBuffer loadBuffer; |
| 2922 |
JS::TranscodeBuffer saveBuffer; |
| 2923 |
|
| 2924 |
if (loadBytecode) { |
| 2925 |
size_t loadLength = 0; |
| 2926 |
uint8_t* loadData = nullptr; |
| 2927 |
|
| 2928 |
if (!CacheEntry_compatible(cx, cacheEntry, cacheOptions)) { |
| 2929 |
return false; |
| 2930 |
} |
| 2931 |
|
| 2932 |
loadData = CacheEntry_getBytecode(cx, cacheEntry, &loadLength); |
| 2933 |
if (!loadData) { |
| 2934 |
return false; |
| 2935 |
} |
| 2936 |
if (!loadBuffer.append(loadData, loadLength)) { |
| 2937 |
JS_ReportOutOfMemory(cx); |
| 2938 |
return false; |
| 2939 |
} |
| 2940 |
} |
| 2941 |
|
| 2942 |
{ |
| 2943 |
JSAutoRealm ar(cx, global); |
| 2944 |
RefPtr<JS::Stencil> stencil; |
| 2945 |
|
| 2946 |
if (loadBytecode) { |
| 2947 |
JS::TranscodeRange range(loadBuffer.begin(), loadBuffer.length()); |
| 2948 |
JS::DecodeOptions decodeOptions(options); |
| 2949 |
|
| 2950 |
JS::TranscodeResult rv = |
| 2951 |
JS::DecodeStencil(cx, decodeOptions, range, getter_AddRefs(stencil)); |
| 2952 |
if (JS::IsTranscodeFailureResult(rv)) { |
| 2953 |
JS_ReportErrorASCII(cx, "failed to decode cache"); |
| 2954 |
return false; |
| 2955 |
} |
| 2956 |
|
| 2957 |
if (!ConvertTranscodeResultToJSException(cx, rv)) { |
| 2958 |
return false; |
| 2959 |
} |
| 2960 |
} else { |
| 2961 |
AutoStableStringChars linearChars(cx); |
| 2962 |
if (!linearChars.initTwoByte(cx, code)) { |
| 2963 |
return false; |
| 2964 |
} |
| 2965 |
|
| 2966 |
JS::SourceText<char16_t> srcBuf; |
| 2967 |
if (!srcBuf.initMaybeBorrowed(cx, linearChars)) { |
| 2968 |
return false; |
| 2969 |
} |
| 2970 |
|
| 2971 |
stencil = JS::CompileGlobalScriptToStencil(cx, options, srcBuf); |
| 2972 |
if (!stencil) { |
| 2973 |
return false; |
| 2974 |
} |
| 2975 |
} |
| 2976 |
|
| 2977 |
if (!js::ValidateLazinessOfStencilAndGlobal(cx, stencil.get())) { |
| 2978 |
return false; |
| 2979 |
} |
| 2980 |
|
| 2981 |
JS::InstantiateOptions instantiateOptions(options); |
| 2982 |
RootedScript script( |
| 2983 |
cx, JS::InstantiateGlobalStencil(cx, instantiateOptions, stencil)); |
| 2984 |
if (!script) { |
| 2985 |
return false; |
| 2986 |
} |
| 2987 |
|
| 2988 |
AutoReportFrontendContext fc(cx); |
| 2989 |
if (!SetSourceOptions(cx, &fc, script->scriptSource(), displayURL, |
| 2990 |
sourceMapURL)) { |
| 2991 |
return false; |
| 2992 |
} |
| 2993 |
|
| 2994 |
if (!JS::UpdateDebugMetadata(cx, script, instantiateOptions, privateValue, |
| 2995 |
elementAttributeName, nullptr, nullptr)) { |
| 2996 |
return false; |
| 2997 |
} |
| 2998 |
|
| 2999 |
if (saveBytecodeWithDelazifications) { |
| 3000 |
bool alreadyStarted; |
| 3001 |
if (!JS::StartCollectingDelazifications(cx, script, stencil, |
| 3002 |
alreadyStarted)) { |
| 3003 |
return false; |
| 3004 |
} |
| 3005 |
MOZ_ASSERT(!alreadyStarted); |
| 3006 |
} |
| 3007 |
|
| 3008 |
if (execute) { |
| 3009 |
if (!(envChain.empty() |
| 3010 |
? JS_ExecuteScript(cx, script, args.rval()) |
| 3011 |
: JS_ExecuteScript(cx, envChain, script, args.rval()))) { |
| 3012 |
if (catchTermination && !JS_IsExceptionPending(cx)) { |
| 3013 |
ShellContext* sc = GetShellContext(cx); |
| 3014 |
if (sc->quitting) { |
| 3015 |
UnsetQuitting(cx); |
| 3016 |
} |
| 3017 |
|
| 3018 |
JSAutoRealm ar1(cx, callerGlobal); |
| 3019 |
JSString* str = JS_NewStringCopyZ(cx, "terminated"); |
| 3020 |
if (!str) { |
| 3021 |
return false; |
| 3022 |
} |
| 3023 |
args.rval().setString(str); |
| 3024 |
return true; |
| 3025 |
} |
| 3026 |
return false; |
| 3027 |
} |
| 3028 |
} |
| 3029 |
|
| 3030 |
// Serialize the encoded bytecode, recorded before the execution, into a |
| 3031 |
// buffer which can be deserialized linearly. |
| 3032 |
if (saveBytecodeWithDelazifications) { |
| 3033 |
if (!FinishCollectingDelazifications(cx, script, saveBuffer)) { |
| 3034 |
return false; |
| 3035 |
} |
| 3036 |
} |
| 3037 |
} |
| 3038 |
|
| 3039 |
if (saveBytecodeWithDelazifications) { |
| 3040 |
// If we are both loading and saving, we assert that we are going to |
| 3041 |
// replace the current bytecode by the same stream of bytes. |
| 3042 |
if (loadBytecode && assertEqBytecode) { |
| 3043 |
if (saveBuffer.length() != loadBuffer.length()) { |
| 3044 |
char loadLengthStr[16]; |
| 3045 |
SprintfLiteral(loadLengthStr, "%zu", loadBuffer.length()); |
| 3046 |
char saveLengthStr[16]; |
| 3047 |
SprintfLiteral(saveLengthStr, "%zu", saveBuffer.length()); |
| 3048 |
|
| 3049 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3050 |
JSSMSG_CACHE_EQ_SIZE_FAILED, loadLengthStr, |
| 3051 |
saveLengthStr); |
| 3052 |
return false; |
| 3053 |
} |
| 3054 |
|
| 3055 |
if (!ArrayEqual(loadBuffer.begin(), saveBuffer.begin(), |
| 3056 |
loadBuffer.length())) { |
| 3057 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3058 |
JSSMSG_CACHE_EQ_CONTENT_FAILED); |
| 3059 |
return false; |
| 3060 |
} |
| 3061 |
} |
| 3062 |
|
| 3063 |
size_t saveLength = saveBuffer.length(); |
| 3064 |
if (saveLength >= INT32_MAX) { |
| 3065 |
JS_ReportErrorASCII(cx, "Cannot save large cache entry content"); |
| 3066 |
return false; |
| 3067 |
} |
| 3068 |
uint8_t* saveData = saveBuffer.extractOrCopyRawBuffer(); |
| 3069 |
if (!CacheEntry_setBytecode(cx, cacheEntry, cacheOptions, saveData, |
| 3070 |
saveLength)) { |
| 3071 |
js_free(saveData); |
| 3072 |
return false; |
| 3073 |
} |
| 3074 |
} |
| 3075 |
|
| 3076 |
return JS_WrapValue(cx, args.rval()); |
| 3077 |
} |
| 3078 |
|
| 3079 |
JSString* js::shell::FileAsString(JSContext* cx, JS::HandleString pathnameStr) { |
| 3080 |
UniqueChars pathname = JS_EncodeStringToUTF8(cx, pathnameStr); |
| 3081 |
if (!pathname) { |
| 3082 |
return nullptr; |
| 3083 |
} |
| 3084 |
|
| 3085 |
FILE* file = OpenFile(cx, pathname.get(), "rb"); |
| 3086 |
if (!file) { |
| 3087 |
return nullptr; |
| 3088 |
} |
| 3089 |
|
| 3090 |
AutoCloseFile autoClose(file); |
| 3091 |
|
| 3092 |
struct stat st; |
| 3093 |
if (fstat(fileno(file), &st) != 0) { |
| 3094 |
JS_ReportErrorUTF8(cx, "can't stat %s", pathname.get()); |
| 3095 |
return nullptr; |
| 3096 |
} |
| 3097 |
|
| 3098 |
if ((st.st_mode & S_IFMT) != S_IFREG) { |
| 3099 |
JS_ReportErrorUTF8(cx, "can't read non-regular file %s", pathname.get()); |
| 3100 |
return nullptr; |
| 3101 |
} |
| 3102 |
|
| 3103 |
size_t len; |
| 3104 |
if (!FileSize(cx, pathname.get(), file, &len)) { |
| 3105 |
return nullptr; |
| 3106 |
} |
| 3107 |
|
| 3108 |
UniqueChars buf(js_pod_malloc<char>(len + 1)); |
| 3109 |
if (!buf) { |
| 3110 |
JS_ReportErrorUTF8(cx, "out of memory reading %s", pathname.get()); |
| 3111 |
return nullptr; |
| 3112 |
} |
| 3113 |
|
| 3114 |
if (!ReadFile(cx, pathname.get(), file, buf.get(), len)) { |
| 3115 |
return nullptr; |
| 3116 |
} |
| 3117 |
|
| 3118 |
UniqueTwoByteChars ucbuf( |
| 3119 |
JS::LossyUTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(buf.get(), len), |
| 3120 |
&len, js::MallocArena) |
| 3121 |
.get()); |
| 3122 |
if (!ucbuf) { |
| 3123 |
JS_ReportErrorUTF8(cx, "Invalid UTF-8 in file '%s'", pathname.get()); |
| 3124 |
return nullptr; |
| 3125 |
} |
| 3126 |
|
| 3127 |
return JS_NewUCStringCopyN(cx, ucbuf.get(), len); |
| 3128 |
} |
| 3129 |
|
| 3130 |
/* |
| 3131 |
* Function to run scripts and return compilation + execution time. Semantics |
| 3132 |
* are closely modelled after the equivalent function in WebKit, as this is used |
| 3133 |
* to produce benchmark timings by SunSpider. |
| 3134 |
*/ |
| 3135 |
static bool Run(JSContext* cx, unsigned argc, Value* vp) { |
| 3136 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3137 |
if (args.length() != 1) { |
| 3138 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3139 |
JSSMSG_INVALID_ARGS, "run"); |
| 3140 |
return false; |
| 3141 |
} |
| 3142 |
|
| 3143 |
RootedString str(cx, JS::ToString(cx, args[0])); |
| 3144 |
if (!str) { |
| 3145 |
return false; |
| 3146 |
} |
| 3147 |
args[0].setString(str); |
| 3148 |
|
| 3149 |
str = FileAsString(cx, str); |
| 3150 |
if (!str) { |
| 3151 |
return false; |
| 3152 |
} |
| 3153 |
|
| 3154 |
AutoStableStringChars linearChars(cx); |
| 3155 |
if (!linearChars.initTwoByte(cx, str)) { |
| 3156 |
return false; |
| 3157 |
} |
| 3158 |
|
| 3159 |
JS::SourceText<char16_t> srcBuf; |
| 3160 |
if (!srcBuf.initMaybeBorrowed(cx, linearChars)) { |
| 3161 |
return false; |
| 3162 |
} |
| 3163 |
|
| 3164 |
RootedScript script(cx); |
| 3165 |
int64_t startClock = PRMJ_Now(); |
| 3166 |
{ |
| 3167 |
UniqueChars filename = JS_EncodeStringToUTF8(cx, str); |
| 3168 |
if (!filename) { |
| 3169 |
return false; |
| 3170 |
} |
| 3171 |
|
| 3172 |
JS::CompileOptions options(cx); |
| 3173 |
options.setIntroductionType("js shell run") |
| 3174 |
.setFileAndLine(filename.get(), 1) |
| 3175 |
.setIsRunOnce(true) |
| 3176 |
.setNoScriptRval(true) |
| 3177 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 3178 |
|
| 3179 |
script = JS::Compile(cx, options, srcBuf); |
| 3180 |
if (!script) { |
| 3181 |
return false; |
| 3182 |
} |
| 3183 |
} |
| 3184 |
|
| 3185 |
if (!JS_ExecuteScript(cx, script)) { |
| 3186 |
return false; |
| 3187 |
} |
| 3188 |
|
| 3189 |
int64_t endClock = PRMJ_Now(); |
| 3190 |
|
| 3191 |
args.rval().setDouble((endClock - startClock) / double(PRMJ_USEC_PER_MSEC)); |
| 3192 |
return true; |
| 3193 |
} |
| 3194 |
|
| 3195 |
static int js_fgets(char* buf, int size, FILE* file) { |
| 3196 |
int n, i, c; |
| 3197 |
bool crflag; |
| 3198 |
|
| 3199 |
n = size - 1; |
| 3200 |
if (n < 0) { |
| 3201 |
return -1; |
| 3202 |
} |
| 3203 |
|
| 3204 |
// Use the fastest available getc. |
| 3205 |
auto fast_getc = |
| 3206 |
#if defined(HAVE_GETC_UNLOCKED) |
| 3207 |
getc_unlocked |
| 3208 |
#elif defined(HAVE__GETC_NOLOCK) |
| 3209 |
_getc_nolock |
| 3210 |
#else |
| 3211 |
getc |
| 3212 |
#endif |
| 3213 |
; |
| 3214 |
|
| 3215 |
crflag = false; |
| 3216 |
for (i = 0; i < n && (c = fast_getc(file)) != EOF; i++) { |
| 3217 |
buf[i] = c; |
| 3218 |
if (c == '\n') { // any \n ends a line |
| 3219 |
i++; // keep the \n; we know there is room for \0 |
| 3220 |
break; |
| 3221 |
} |
| 3222 |
if (crflag) { // \r not followed by \n ends line at the \r |
| 3223 |
ungetc(c, file); |
| 3224 |
break; // and overwrite c in buf with \0 |
| 3225 |
} |
| 3226 |
crflag = (c == '\r'); |
| 3227 |
} |
| 3228 |
|
| 3229 |
buf[i] = '\0'; |
| 3230 |
return i; |
| 3231 |
} |
| 3232 |
|
| 3233 |
/* |
| 3234 |
* function readline() |
| 3235 |
* Provides a hook for scripts to read a line from stdin. |
| 3236 |
*/ |
| 3237 |
static bool ReadLine(JSContext* cx, unsigned argc, Value* vp) { |
| 3238 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3239 |
|
| 3240 |
static constexpr size_t BUFSIZE = 256; |
| 3241 |
FILE* from = stdin; |
| 3242 |
size_t buflength = 0; |
| 3243 |
size_t bufsize = BUFSIZE; |
| 3244 |
char* buf = (char*)JS_malloc(cx, bufsize); |
| 3245 |
if (!buf) { |
| 3246 |
JS_ReportOutOfMemory(cx); |
| 3247 |
return false; |
| 3248 |
} |
| 3249 |
auto freeBuf = mozilla::MakeScopeExit([&]() { |
| 3250 |
JS_free(cx, buf); |
| 3251 |
buf = nullptr; |
| 3252 |
}); |
| 3253 |
|
| 3254 |
bool sawNewline = false; |
| 3255 |
size_t gotlength; |
| 3256 |
while ((gotlength = js_fgets(buf + buflength, bufsize - buflength, from)) > |
| 3257 |
0) { |
| 3258 |
buflength += gotlength; |
| 3259 |
|
| 3260 |
/* Are we done? */ |
| 3261 |
if (buf[buflength - 1] == '\n') { |
| 3262 |
buf[buflength - 1] = '\0'; |
| 3263 |
sawNewline = true; |
| 3264 |
break; |
| 3265 |
} else if (buflength < bufsize - 1) { |
| 3266 |
break; |
| 3267 |
} |
| 3268 |
|
| 3269 |
/* Else, grow our buffer for another pass. */ |
| 3270 |
bufsize *= 2; |
| 3271 |
if (bufsize <= buflength) { |
| 3272 |
JS_ReportAllocationOverflow(cx); |
| 3273 |
return false; |
| 3274 |
} |
| 3275 |
char* tmp = static_cast<char*>(JS_realloc(cx, buf, bufsize / 2, bufsize)); |
| 3276 |
if (!tmp) { |
| 3277 |
JS_ReportOutOfMemory(cx); |
| 3278 |
return false; |
| 3279 |
} |
| 3280 |
buf = tmp; |
| 3281 |
} |
| 3282 |
|
| 3283 |
/* Treat the empty string specially. */ |
| 3284 |
if (buflength == 0) { |
| 3285 |
args.rval().set(feof(from) ? NullValue() : JS_GetEmptyStringValue(cx)); |
| 3286 |
return true; |
| 3287 |
} |
| 3288 |
|
| 3289 |
/* |
| 3290 |
* Turn buf into a JSString. Note that buflength includes the trailing null |
| 3291 |
* character. |
| 3292 |
*/ |
| 3293 |
JSString* str = |
| 3294 |
JS_NewStringCopyN(cx, buf, sawNewline ? buflength - 1 : buflength); |
| 3295 |
if (!str) { |
| 3296 |
return false; |
| 3297 |
} |
| 3298 |
|
| 3299 |
args.rval().setString(str); |
| 3300 |
return true; |
| 3301 |
} |
| 3302 |
|
| 3303 |
/* |
| 3304 |
* function readlineBuf() |
| 3305 |
* Provides a hook for scripts to emulate readline() using a string object. |
| 3306 |
*/ |
| 3307 |
static bool ReadLineBuf(JSContext* cx, unsigned argc, Value* vp) { |
| 3308 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3309 |
ShellContext* sc = GetShellContext(cx); |
| 3310 |
|
| 3311 |
if (!args.length()) { |
| 3312 |
if (!sc->readLineBuf) { |
| 3313 |
JS_ReportErrorASCII(cx, |
| 3314 |
"No source buffer set. You must initially " |
| 3315 |
"call readlineBuf with an argument."); |
| 3316 |
return false; |
| 3317 |
} |
| 3318 |
|
| 3319 |
char* currentBuf = sc->readLineBuf.get() + sc->readLineBufPos; |
| 3320 |
size_t buflen = strlen(currentBuf); |
| 3321 |
|
| 3322 |
if (!buflen) { |
| 3323 |
args.rval().setNull(); |
| 3324 |
return true; |
| 3325 |
} |
| 3326 |
|
| 3327 |
size_t len = 0; |
| 3328 |
while (len < buflen) { |
| 3329 |
if (currentBuf[len] == '\n') { |
| 3330 |
break; |
| 3331 |
} |
| 3332 |
len++; |
| 3333 |
} |
| 3334 |
|
| 3335 |
JSString* str = JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(currentBuf, len)); |
| 3336 |
if (!str) { |
| 3337 |
return false; |
| 3338 |
} |
| 3339 |
|
| 3340 |
if (currentBuf[len] == '\0') { |
| 3341 |
sc->readLineBufPos += len; |
| 3342 |
} else { |
| 3343 |
sc->readLineBufPos += len + 1; |
| 3344 |
} |
| 3345 |
|
| 3346 |
args.rval().setString(str); |
| 3347 |
return true; |
| 3348 |
} |
| 3349 |
|
| 3350 |
if (args.length() == 1) { |
| 3351 |
sc->readLineBuf = nullptr; |
| 3352 |
sc->readLineBufPos = 0; |
| 3353 |
|
| 3354 |
RootedString str(cx, JS::ToString(cx, args[0])); |
| 3355 |
if (!str) { |
| 3356 |
return false; |
| 3357 |
} |
| 3358 |
sc->readLineBuf = JS_EncodeStringToUTF8(cx, str); |
| 3359 |
if (!sc->readLineBuf) { |
| 3360 |
return false; |
| 3361 |
} |
| 3362 |
|
| 3363 |
args.rval().setUndefined(); |
| 3364 |
return true; |
| 3365 |
} |
| 3366 |
|
| 3367 |
JS_ReportErrorASCII(cx, "Must specify at most one argument"); |
| 3368 |
return false; |
| 3369 |
} |
| 3370 |
|
| 3371 |
static bool PutStr(JSContext* cx, unsigned argc, Value* vp) { |
| 3372 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3373 |
|
| 3374 |
if (args.length() != 0) { |
| 3375 |
if (!gOutFile->isOpen()) { |
| 3376 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 3377 |
return false; |
| 3378 |
} |
| 3379 |
|
| 3380 |
RootedString str(cx, JS::ToString(cx, args[0])); |
| 3381 |
if (!str) { |
| 3382 |
return false; |
| 3383 |
} |
| 3384 |
UniqueChars bytes = JS_EncodeStringToUTF8(cx, str); |
| 3385 |
if (!bytes) { |
| 3386 |
return false; |
| 3387 |
} |
| 3388 |
fputs(bytes.get(), gOutFile->fp); |
| 3389 |
fflush(gOutFile->fp); |
| 3390 |
} |
| 3391 |
|
| 3392 |
args.rval().setUndefined(); |
| 3393 |
return true; |
| 3394 |
} |
| 3395 |
|
| 3396 |
static bool Now(JSContext* cx, unsigned argc, Value* vp) { |
| 3397 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3398 |
double now = PRMJ_Now() / double(PRMJ_USEC_PER_MSEC); |
| 3399 |
args.rval().setDouble(now); |
| 3400 |
return true; |
| 3401 |
} |
| 3402 |
|
| 3403 |
static bool CpuNow(JSContext* cx, unsigned argc, Value* vp) { |
| 3404 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3405 |
double now = double(std::clock()) / double(CLOCKS_PER_SEC); |
| 3406 |
args.rval().setDouble(now); |
| 3407 |
return true; |
| 3408 |
} |
| 3409 |
|
| 3410 |
static bool PrintInternal(JSContext* cx, const CallArgs& args, RCFile* file) { |
| 3411 |
if (!file->isOpen()) { |
| 3412 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 3413 |
return false; |
| 3414 |
} |
| 3415 |
|
| 3416 |
for (unsigned i = 0; i < args.length(); i++) { |
| 3417 |
RootedString str(cx, JS::ToString(cx, args[i])); |
| 3418 |
if (!str) { |
| 3419 |
return false; |
| 3420 |
} |
| 3421 |
UniqueChars bytes = JS_EncodeStringToUTF8(cx, str); |
| 3422 |
if (!bytes) { |
| 3423 |
return false; |
| 3424 |
} |
| 3425 |
fprintf(file->fp, "%s%s", i ? " " : "", bytes.get()); |
| 3426 |
} |
| 3427 |
|
| 3428 |
fputc('\n', file->fp); |
| 3429 |
fflush(file->fp); |
| 3430 |
|
| 3431 |
args.rval().setUndefined(); |
| 3432 |
return true; |
| 3433 |
} |
| 3434 |
|
| 3435 |
static bool Print(JSContext* cx, unsigned argc, Value* vp) { |
| 3436 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3437 |
#ifdef FUZZING_INTERFACES |
| 3438 |
if (fuzzHaveModule && !fuzzDoDebug) { |
| 3439 |
// When fuzzing and not debugging, suppress any print() output, |
| 3440 |
// as it slows down fuzzing and makes libFuzzer's output hard |
| 3441 |
// to read. |
| 3442 |
args.rval().setUndefined(); |
| 3443 |
return true; |
| 3444 |
} |
| 3445 |
#endif // FUZZING_INTERFACES |
| 3446 |
return PrintInternal(cx, args, gOutFile); |
| 3447 |
} |
| 3448 |
|
| 3449 |
static bool PrintErr(JSContext* cx, unsigned argc, Value* vp) { |
| 3450 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3451 |
return PrintInternal(cx, args, gErrFile); |
| 3452 |
} |
| 3453 |
|
| 3454 |
static bool Help(JSContext* cx, unsigned argc, Value* vp); |
| 3455 |
|
| 3456 |
static bool Quit(JSContext* cx, unsigned argc, Value* vp) { |
| 3457 |
// Print a message to stderr in differential testing to help jsfunfuzz |
| 3458 |
// find uncatchable-exception bugs. |
| 3459 |
if (js::SupportDifferentialTesting()) { |
| 3460 |
fprintf(stderr, "quit called\n"); |
| 3461 |
} |
| 3462 |
|
| 3463 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3464 |
int32_t code; |
| 3465 |
if (!ToInt32(cx, args.get(0), &code)) { |
| 3466 |
return false; |
| 3467 |
} |
| 3468 |
|
| 3469 |
// The fuzzers check the shell's exit code and assume a value >= 128 means |
| 3470 |
// the process crashed (for instance, SIGSEGV will result in code 139). On |
| 3471 |
// POSIX platforms, the exit code is 8-bit and negative values can also |
| 3472 |
// result in an exit code >= 128. We restrict the value to range [0, 127] to |
| 3473 |
// avoid false positives. |
| 3474 |
if (code < 0 || code >= 128) { |
| 3475 |
JS_ReportErrorASCII(cx, "quit exit code should be in range 0-127"); |
| 3476 |
return false; |
| 3477 |
} |
| 3478 |
|
| 3479 |
SetQuitting(cx, code); |
| 3480 |
JS::ReportUncatchableException(cx); |
| 3481 |
return false; |
| 3482 |
} |
| 3483 |
|
| 3484 |
static bool StartTimingMutator(JSContext* cx, unsigned argc, Value* vp) { |
| 3485 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3486 |
if (args.length() > 0) { |
| 3487 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3488 |
JSSMSG_TOO_MANY_ARGS, "startTimingMutator"); |
| 3489 |
return false; |
| 3490 |
} |
| 3491 |
|
| 3492 |
if (!cx->runtime()->gc.stats().startTimingMutator()) { |
| 3493 |
JS_ReportErrorASCII( |
| 3494 |
cx, "StartTimingMutator should only be called from outside of GC"); |
| 3495 |
return false; |
| 3496 |
} |
| 3497 |
|
| 3498 |
args.rval().setUndefined(); |
| 3499 |
return true; |
| 3500 |
} |
| 3501 |
|
| 3502 |
static bool StopTimingMutator(JSContext* cx, unsigned argc, Value* vp) { |
| 3503 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3504 |
if (args.length() > 0) { |
| 3505 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3506 |
JSSMSG_TOO_MANY_ARGS, "stopTimingMutator"); |
| 3507 |
return false; |
| 3508 |
} |
| 3509 |
|
| 3510 |
double mutator_ms, gc_ms; |
| 3511 |
if (!cx->runtime()->gc.stats().stopTimingMutator(mutator_ms, gc_ms)) { |
| 3512 |
JS_ReportErrorASCII(cx, |
| 3513 |
"stopTimingMutator called when not timing the mutator"); |
| 3514 |
return false; |
| 3515 |
} |
| 3516 |
double total_ms = mutator_ms + gc_ms; |
| 3517 |
if (total_ms > 0 && gOutFile->isOpen()) { |
| 3518 |
fprintf(gOutFile->fp, "Mutator: %.3fms (%.1f%%), GC: %.3fms (%.1f%%)\n", |
| 3519 |
mutator_ms, mutator_ms / total_ms * 100.0, gc_ms, |
| 3520 |
gc_ms / total_ms * 100.0); |
| 3521 |
} |
| 3522 |
|
| 3523 |
args.rval().setUndefined(); |
| 3524 |
return true; |
| 3525 |
} |
| 3526 |
|
| 3527 |
static const char* ToSource(JSContext* cx, HandleValue vp, UniqueChars* bytes) { |
| 3528 |
RootedString str(cx, JS_ValueToSource(cx, vp)); |
| 3529 |
if (str) { |
| 3530 |
*bytes = JS_EncodeStringToUTF8(cx, str); |
| 3531 |
if (*bytes) { |
| 3532 |
return bytes->get(); |
| 3533 |
} |
| 3534 |
} |
| 3535 |
JS_ClearPendingException(cx); |
| 3536 |
return "<<error converting value to string>>"; |
| 3537 |
} |
| 3538 |
|
| 3539 |
static bool AssertEq(JSContext* cx, unsigned argc, Value* vp) { |
| 3540 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3541 |
if (!(args.length() == 2 || (args.length() == 3 && args[2].isString()))) { |
| 3542 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3543 |
(args.length() < 2) ? JSSMSG_NOT_ENOUGH_ARGS |
| 3544 |
: (args.length() == 3) ? JSSMSG_INVALID_ARGS |
| 3545 |
: JSSMSG_TOO_MANY_ARGS, |
| 3546 |
"assertEq"); |
| 3547 |
return false; |
| 3548 |
} |
| 3549 |
|
| 3550 |
bool same; |
| 3551 |
if (!JS::SameValue(cx, args[0], args[1], &same)) { |
| 3552 |
return false; |
| 3553 |
} |
| 3554 |
if (!same) { |
| 3555 |
UniqueChars bytes0, bytes1; |
| 3556 |
const char* actual = ToSource(cx, args[0], &bytes0); |
| 3557 |
const char* expected = ToSource(cx, args[1], &bytes1); |
| 3558 |
if (args.length() == 2) { |
| 3559 |
JS_ReportErrorNumberUTF8(cx, my_GetErrorMessage, nullptr, |
| 3560 |
JSSMSG_ASSERT_EQ_FAILED, actual, expected); |
| 3561 |
} else { |
| 3562 |
RootedString message(cx, args[2].toString()); |
| 3563 |
UniqueChars bytes2 = QuoteString(cx, message); |
| 3564 |
if (!bytes2) { |
| 3565 |
return false; |
| 3566 |
} |
| 3567 |
JS_ReportErrorNumberUTF8(cx, my_GetErrorMessage, nullptr, |
| 3568 |
JSSMSG_ASSERT_EQ_FAILED_MSG, actual, expected, |
| 3569 |
bytes2.get()); |
| 3570 |
} |
| 3571 |
return false; |
| 3572 |
} |
| 3573 |
args.rval().setUndefined(); |
| 3574 |
return true; |
| 3575 |
} |
| 3576 |
|
| 3577 |
static JSScript* GetTopScript(JSContext* cx) { |
| 3578 |
NonBuiltinScriptFrameIter iter(cx); |
| 3579 |
return iter.done() ? nullptr : iter.script(); |
| 3580 |
} |
| 3581 |
|
| 3582 |
static bool GetScriptAndPCArgs(JSContext* cx, CallArgs& args, |
| 3583 |
MutableHandleScript scriptp, int32_t* ip) { |
| 3584 |
RootedScript script(cx, GetTopScript(cx)); |
| 3585 |
*ip = 0; |
| 3586 |
if (!args.get(0).isUndefined()) { |
| 3587 |
HandleValue v = args[0]; |
| 3588 |
unsigned intarg = 0; |
| 3589 |
if (v.isObject() && JS::GetClass(&v.toObject())->isJSFunction()) { |
| 3590 |
script = TestingFunctionArgumentToScript(cx, v); |
| 3591 |
if (!script) { |
| 3592 |
return false; |
| 3593 |
} |
| 3594 |
intarg++; |
| 3595 |
} |
| 3596 |
if (!args.get(intarg).isUndefined()) { |
| 3597 |
if (!JS::ToInt32(cx, args[intarg], ip)) { |
| 3598 |
return false; |
| 3599 |
} |
| 3600 |
if ((uint32_t)*ip >= script->length()) { |
| 3601 |
JS_ReportErrorASCII(cx, "Invalid PC"); |
| 3602 |
return false; |
| 3603 |
} |
| 3604 |
} |
| 3605 |
} |
| 3606 |
|
| 3607 |
scriptp.set(script); |
| 3608 |
|
| 3609 |
return true; |
| 3610 |
} |
| 3611 |
|
| 3612 |
static bool LineToPC(JSContext* cx, unsigned argc, Value* vp) { |
| 3613 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3614 |
|
| 3615 |
if (args.length() == 0) { |
| 3616 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3617 |
JSSMSG_LINE2PC_USAGE); |
| 3618 |
return false; |
| 3619 |
} |
| 3620 |
|
| 3621 |
RootedScript script(cx, GetTopScript(cx)); |
| 3622 |
int32_t lineArg = 0; |
| 3623 |
if (args[0].isObject() && args[0].toObject().is<JSFunction>()) { |
| 3624 |
script = TestingFunctionArgumentToScript(cx, args[0]); |
| 3625 |
if (!script) { |
| 3626 |
return false; |
| 3627 |
} |
| 3628 |
lineArg++; |
| 3629 |
} |
| 3630 |
|
| 3631 |
uint32_t lineno; |
| 3632 |
if (!ToUint32(cx, args.get(lineArg), &lineno)) { |
| 3633 |
return false; |
| 3634 |
} |
| 3635 |
|
| 3636 |
jsbytecode* pc = LineNumberToPC(script, lineno); |
| 3637 |
if (!pc) { |
| 3638 |
return false; |
| 3639 |
} |
| 3640 |
args.rval().setInt32(script->pcToOffset(pc)); |
| 3641 |
return true; |
| 3642 |
} |
| 3643 |
|
| 3644 |
static bool PCToLine(JSContext* cx, unsigned argc, Value* vp) { |
| 3645 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3646 |
RootedScript script(cx); |
| 3647 |
int32_t i; |
| 3648 |
unsigned lineno; |
| 3649 |
|
| 3650 |
if (!GetScriptAndPCArgs(cx, args, &script, &i)) { |
| 3651 |
return false; |
| 3652 |
} |
| 3653 |
lineno = PCToLineNumber(script, script->offsetToPC(i)); |
| 3654 |
if (!lineno) { |
| 3655 |
return false; |
| 3656 |
} |
| 3657 |
args.rval().setInt32(lineno); |
| 3658 |
return true; |
| 3659 |
} |
| 3660 |
|
| 3661 |
#if defined(DEBUG) || defined(JS_JITSPEW) |
| 3662 |
|
| 3663 |
static bool Notes(JSContext* cx, unsigned argc, Value* vp) { |
| 3664 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3665 |
JSSprinter sprinter(cx); |
| 3666 |
if (!sprinter.init()) { |
| 3667 |
return false; |
| 3668 |
} |
| 3669 |
|
| 3670 |
for (unsigned i = 0; i < args.length(); i++) { |
| 3671 |
RootedScript script(cx, TestingFunctionArgumentToScript(cx, args[i])); |
| 3672 |
if (!script) { |
| 3673 |
return false; |
| 3674 |
} |
| 3675 |
|
| 3676 |
if (!JSScript::dumpSrcNotes(cx, script, &sprinter)) { |
| 3677 |
return false; |
| 3678 |
} |
| 3679 |
} |
| 3680 |
|
| 3681 |
JSString* str = sprinter.release(cx); |
| 3682 |
if (!str) { |
| 3683 |
return false; |
| 3684 |
} |
| 3685 |
args.rval().setString(str); |
| 3686 |
return true; |
| 3687 |
} |
| 3688 |
|
| 3689 |
namespace { |
| 3690 |
|
| 3691 |
struct DisassembleOptionParser { |
| 3692 |
unsigned argc; |
| 3693 |
Value* argv; |
| 3694 |
JSScript::DumpOptions options; |
| 3695 |
|
| 3696 |
DisassembleOptionParser(unsigned argc, Value* argv) |
| 3697 |
: argc(argc), argv(argv) {} |
| 3698 |
|
| 3699 |
bool parse(JSContext* cx) { |
| 3700 |
options.recursive = false; |
| 3701 |
|
| 3702 |
/* Read options off early arguments */ |
| 3703 |
while (argc > 0 && argv[0].isString()) { |
| 3704 |
JSString* str = argv[0].toString(); |
| 3705 |
JSLinearString* linearStr = JS_EnsureLinearString(cx, str); |
| 3706 |
if (!linearStr) { |
| 3707 |
return false; |
| 3708 |
} |
| 3709 |
if (JS_LinearStringEqualsLiteral(linearStr, "-r")) { |
| 3710 |
options.recursive = true; |
| 3711 |
} else { |
| 3712 |
break; |
| 3713 |
} |
| 3714 |
argv++; |
| 3715 |
argc--; |
| 3716 |
} |
| 3717 |
return true; |
| 3718 |
} |
| 3719 |
}; |
| 3720 |
|
| 3721 |
} /* anonymous namespace */ |
| 3722 |
|
| 3723 |
static bool DisassembleToSprinter(JSContext* cx, unsigned argc, Value* vp, |
| 3724 |
StringPrinter* sp) { |
| 3725 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3726 |
DisassembleOptionParser p(args.length(), args.array()); |
| 3727 |
if (!p.parse(cx)) { |
| 3728 |
return false; |
| 3729 |
} |
| 3730 |
|
| 3731 |
if (p.argc == 0) { |
| 3732 |
/* Without arguments, disassemble the current script. */ |
| 3733 |
RootedScript script(cx, GetTopScript(cx)); |
| 3734 |
if (script) { |
| 3735 |
JSAutoRealm ar(cx, script); |
| 3736 |
if (!JSScript::dump(cx, script, p.options, sp)) { |
| 3737 |
return false; |
| 3738 |
} |
| 3739 |
} |
| 3740 |
} else { |
| 3741 |
for (unsigned i = 0; i < p.argc; i++) { |
| 3742 |
RootedFunction fun(cx); |
| 3743 |
RootedScript script(cx); |
| 3744 |
RootedValue value(cx, p.argv[i]); |
| 3745 |
if (value.isObject() && value.toObject().is<ShellModuleObjectWrapper>()) { |
| 3746 |
auto* module = value.toObject().as<ShellModuleObjectWrapper>().get(); |
| 3747 |
script = module->maybeScript(); |
| 3748 |
if (!script) { |
| 3749 |
JS_ReportErrorASCII(cx, "module does not have an associated script"); |
| 3750 |
return false; |
| 3751 |
} |
| 3752 |
} else { |
| 3753 |
script = TestingFunctionArgumentToScript(cx, value, fun.address()); |
| 3754 |
if (!script) { |
| 3755 |
return false; |
| 3756 |
} |
| 3757 |
} |
| 3758 |
|
| 3759 |
if (!JSScript::dump(cx, script, p.options, sp)) { |
| 3760 |
return false; |
| 3761 |
} |
| 3762 |
} |
| 3763 |
} |
| 3764 |
|
| 3765 |
return true; |
| 3766 |
} |
| 3767 |
|
| 3768 |
static bool DisassembleToString(JSContext* cx, unsigned argc, Value* vp) { |
| 3769 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3770 |
JSSprinter sprinter(cx); |
| 3771 |
if (!sprinter.init()) { |
| 3772 |
return false; |
| 3773 |
} |
| 3774 |
if (!DisassembleToSprinter(cx, args.length(), vp, &sprinter)) { |
| 3775 |
return false; |
| 3776 |
} |
| 3777 |
|
| 3778 |
JSString* str = sprinter.release(cx); |
| 3779 |
if (!str) { |
| 3780 |
return false; |
| 3781 |
} |
| 3782 |
args.rval().setString(str); |
| 3783 |
return true; |
| 3784 |
} |
| 3785 |
|
| 3786 |
static bool Disassemble(JSContext* cx, unsigned argc, Value* vp) { |
| 3787 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3788 |
|
| 3789 |
if (!gOutFile->isOpen()) { |
| 3790 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 3791 |
return false; |
| 3792 |
} |
| 3793 |
|
| 3794 |
Sprinter sprinter(cx); |
| 3795 |
if (!sprinter.init()) { |
| 3796 |
return false; |
| 3797 |
} |
| 3798 |
if (!DisassembleToSprinter(cx, args.length(), vp, &sprinter)) { |
| 3799 |
return false; |
| 3800 |
} |
| 3801 |
|
| 3802 |
JS::UniqueChars str = sprinter.release(); |
| 3803 |
if (!str) { |
| 3804 |
return false; |
| 3805 |
} |
| 3806 |
fprintf(gOutFile->fp, "%s\n", str.get()); |
| 3807 |
args.rval().setUndefined(); |
| 3808 |
return true; |
| 3809 |
} |
| 3810 |
|
| 3811 |
static bool DisassFile(JSContext* cx, unsigned argc, Value* vp) { |
| 3812 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3813 |
|
| 3814 |
if (!gOutFile->isOpen()) { |
| 3815 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 3816 |
return false; |
| 3817 |
} |
| 3818 |
|
| 3819 |
/* Support extra options at the start, just like Disassemble. */ |
| 3820 |
DisassembleOptionParser p(args.length(), args.array()); |
| 3821 |
if (!p.parse(cx)) { |
| 3822 |
return false; |
| 3823 |
} |
| 3824 |
|
| 3825 |
if (!p.argc) { |
| 3826 |
args.rval().setUndefined(); |
| 3827 |
return true; |
| 3828 |
} |
| 3829 |
|
| 3830 |
// We should change DisassembleOptionParser to store CallArgs. |
| 3831 |
Rooted<JSString*> str( |
| 3832 |
cx, JS::ToString(cx, HandleValue::fromMarkedLocation(&p.argv[0]))); |
| 3833 |
if (!str) { |
| 3834 |
return false; |
| 3835 |
} |
| 3836 |
UniqueChars filename = JS_EncodeStringToUTF8(cx, str); |
| 3837 |
if (!filename) { |
| 3838 |
return false; |
| 3839 |
} |
| 3840 |
RootedScript script(cx); |
| 3841 |
|
| 3842 |
{ |
| 3843 |
CompileOptions options(cx); |
| 3844 |
options.setIntroductionType("js shell disFile") |
| 3845 |
.setFileAndLine(filename.get(), 1) |
| 3846 |
.setIsRunOnce(true) |
| 3847 |
.setNoScriptRval(true) |
| 3848 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 3849 |
|
| 3850 |
script = JS::CompileUtf8Path(cx, options, filename.get()); |
| 3851 |
if (!script) { |
| 3852 |
return false; |
| 3853 |
} |
| 3854 |
} |
| 3855 |
|
| 3856 |
Sprinter sprinter(cx); |
| 3857 |
if (!sprinter.init()) { |
| 3858 |
return false; |
| 3859 |
} |
| 3860 |
if (!JSScript::dump(cx, script, p.options, &sprinter)) { |
| 3861 |
return false; |
| 3862 |
} |
| 3863 |
|
| 3864 |
JS::UniqueChars chars = sprinter.release(); |
| 3865 |
if (!chars) { |
| 3866 |
return false; |
| 3867 |
} |
| 3868 |
fprintf(gOutFile->fp, "%s\n", chars.get()); |
| 3869 |
|
| 3870 |
args.rval().setUndefined(); |
| 3871 |
return true; |
| 3872 |
} |
| 3873 |
|
| 3874 |
static bool DisassWithSrc(JSContext* cx, unsigned argc, Value* vp) { |
| 3875 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3876 |
|
| 3877 |
if (!gOutFile->isOpen()) { |
| 3878 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 3879 |
return false; |
| 3880 |
} |
| 3881 |
|
| 3882 |
const size_t lineBufLen = 512; |
| 3883 |
unsigned len, line1, line2, bupline; |
| 3884 |
char linebuf[lineBufLen]; |
| 3885 |
static const char sep[] = ";-------------------------"; |
| 3886 |
|
| 3887 |
RootedScript script(cx); |
| 3888 |
for (unsigned i = 0; i < args.length(); i++) { |
| 3889 |
script = TestingFunctionArgumentToScript(cx, args[i]); |
| 3890 |
if (!script) { |
| 3891 |
return false; |
| 3892 |
} |
| 3893 |
|
| 3894 |
if (!script->filename()) { |
| 3895 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 3896 |
JSSMSG_FILE_SCRIPTS_ONLY); |
| 3897 |
return false; |
| 3898 |
} |
| 3899 |
|
| 3900 |
FILE* file = OpenFile(cx, script->filename(), "rb"); |
| 3901 |
if (!file) { |
| 3902 |
return false; |
| 3903 |
} |
| 3904 |
auto closeFile = MakeScopeExit([file] { fclose(file); }); |
| 3905 |
|
| 3906 |
jsbytecode* pc = script->code(); |
| 3907 |
jsbytecode* end = script->codeEnd(); |
| 3908 |
|
| 3909 |
Sprinter sprinter(cx); |
| 3910 |
if (!sprinter.init()) { |
| 3911 |
return false; |
| 3912 |
} |
| 3913 |
|
| 3914 |
/* burn the leading lines */ |
| 3915 |
line2 = PCToLineNumber(script, pc); |
| 3916 |
for (line1 = 0; line1 < line2 - 1; line1++) { |
| 3917 |
char* tmp = fgets(linebuf, lineBufLen, file); |
| 3918 |
if (!tmp) { |
| 3919 |
JS_ReportErrorUTF8(cx, "failed to read %s fully", script->filename()); |
| 3920 |
return false; |
| 3921 |
} |
| 3922 |
} |
| 3923 |
|
| 3924 |
bupline = 0; |
| 3925 |
while (pc < end) { |
| 3926 |
line2 = PCToLineNumber(script, pc); |
| 3927 |
|
| 3928 |
if (line2 < line1) { |
| 3929 |
if (bupline != line2) { |
| 3930 |
bupline = line2; |
| 3931 |
sprinter.printf("%s %3u: BACKUP\n", sep, line2); |
| 3932 |
} |
| 3933 |
} else { |
| 3934 |
if (bupline && line1 == line2) { |
| 3935 |
sprinter.printf("%s %3u: RESTORE\n", sep, line2); |
| 3936 |
} |
| 3937 |
bupline = 0; |
| 3938 |
while (line1 < line2) { |
| 3939 |
if (!fgets(linebuf, lineBufLen, file)) { |
| 3940 |
JS_ReportErrorNumberUTF8(cx, my_GetErrorMessage, nullptr, |
| 3941 |
JSSMSG_UNEXPECTED_EOF, script->filename()); |
| 3942 |
return false; |
| 3943 |
} |
| 3944 |
line1++; |
| 3945 |
sprinter.printf("%s %3u: %s", sep, line1, linebuf); |
| 3946 |
} |
| 3947 |
} |
| 3948 |
|
| 3949 |
len = |
| 3950 |
Disassemble1(cx, script, pc, script->pcToOffset(pc), true, &sprinter); |
| 3951 |
if (!len) { |
| 3952 |
return false; |
| 3953 |
} |
| 3954 |
|
| 3955 |
pc += len; |
| 3956 |
} |
| 3957 |
|
| 3958 |
JS::UniqueChars str = sprinter.release(); |
| 3959 |
if (!str) { |
| 3960 |
return false; |
| 3961 |
} |
| 3962 |
fprintf(gOutFile->fp, "%s\n", str.get()); |
| 3963 |
} |
| 3964 |
|
| 3965 |
args.rval().setUndefined(); |
| 3966 |
return true; |
| 3967 |
} |
| 3968 |
|
| 3969 |
#endif /* defined(DEBUG) || defined(JS_JITSPEW) */ |
| 3970 |
|
| 3971 |
#ifdef JS_CACHEIR_SPEW |
| 3972 |
static bool CacheIRHealthReport(JSContext* cx, unsigned argc, Value* vp) { |
| 3973 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 3974 |
|
| 3975 |
js::jit::CacheIRHealth cih; |
| 3976 |
RootedScript script(cx); |
| 3977 |
|
| 3978 |
// In the case that we are calling this function from the shell and |
| 3979 |
// the environment variable is not set, AutoSpewChannel automatically |
| 3980 |
// sets and unsets the proper channel for the duration of spewing |
| 3981 |
// a health report. |
| 3982 |
AutoSpewChannel channel(cx, SpewChannel::CacheIRHealthReport, script); |
| 3983 |
if (!argc) { |
| 3984 |
// Calling CacheIRHealthReport without any arguments will create health |
| 3985 |
// reports for all scripts in the zone. |
| 3986 |
if (jit::JitZone* jitZone = cx->zone()->jitZone()) { |
| 3987 |
jitZone->forEachJitScript([&](jit::JitScript* jitScript) { |
| 3988 |
script = jitScript->owningScript(); |
| 3989 |
if (!script->selfHosted()) { |
| 3990 |
cih.healthReportForScript(cx, script, js::jit::SpewContext::Shell); |
| 3991 |
} |
| 3992 |
}); |
| 3993 |
} |
| 3994 |
} else { |
| 3995 |
RootedValue value(cx, args.get(0)); |
| 3996 |
|
| 3997 |
if (value.isObject() && value.toObject().is<ShellModuleObjectWrapper>()) { |
| 3998 |
script = |
| 3999 |
value.toObject().as<ShellModuleObjectWrapper>().get()->maybeScript(); |
| 4000 |
if (!script) { |
| 4001 |
JS_ReportErrorASCII(cx, "module does not have an associated script"); |
| 4002 |
return false; |
| 4003 |
} |
| 4004 |
} else { |
| 4005 |
script = TestingFunctionArgumentToScript(cx, args.get(0)); |
| 4006 |
if (!script) { |
| 4007 |
return false; |
| 4008 |
} |
| 4009 |
} |
| 4010 |
|
| 4011 |
cih.healthReportForScript(cx, script, js::jit::SpewContext::Shell); |
| 4012 |
} |
| 4013 |
|
| 4014 |
args.rval().setUndefined(); |
| 4015 |
return true; |
| 4016 |
} |
| 4017 |
#endif /* JS_CACHEIR_SPEW */ |
| 4018 |
|
| 4019 |
/* Pretend we can always preserve wrappers for dummy DOM objects. */ |
| 4020 |
static bool DummyPreserveWrapperCallback(JSContext* cx, HandleObject obj) { |
| 4021 |
return true; |
| 4022 |
} |
| 4023 |
|
| 4024 |
static bool DummyHasReleasedWrapperCallback(HandleObject obj) { return true; } |
| 4025 |
|
| 4026 |
#ifdef FUZZING_JS_FUZZILLI |
| 4027 |
static bool fuzzilli_hash(JSContext* cx, unsigned argc, Value* vp) { |
| 4028 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4029 |
args.rval().setUndefined(); |
| 4030 |
|
| 4031 |
if (argc != 1) { |
| 4032 |
return true; |
| 4033 |
} |
| 4034 |
uint32_t hash; |
| 4035 |
JS::Handle<JS::Value> v = args.get(0); |
| 4036 |
if (v.isInt32()) { |
| 4037 |
int32_t i = v.toInt32(); |
| 4038 |
hash = FuzzilliHashDouble((double)i); |
| 4039 |
} else if (v.isDouble()) { |
| 4040 |
double d = v.toDouble(); |
| 4041 |
d = JS::CanonicalizeNaN(d); |
| 4042 |
hash = FuzzilliHashDouble(d); |
| 4043 |
} else if (v.isNull()) { |
| 4044 |
hash = FuzzilliHashDouble(1.0); |
| 4045 |
} else if (v.isUndefined()) { |
| 4046 |
hash = FuzzilliHashDouble(2.0); |
| 4047 |
} else if (v.isBoolean()) { |
| 4048 |
hash = FuzzilliHashDouble(3.0 + v.toBoolean()); |
| 4049 |
} else if (v.isBigInt()) { |
| 4050 |
JS::BigInt* bigInt = v.toBigInt(); |
| 4051 |
hash = FuzzilliHashBigInt(bigInt); |
| 4052 |
} else if (v.isObject()) { |
| 4053 |
JSObject& obj = v.toObject(); |
| 4054 |
FuzzilliHashObject(cx, &obj); |
| 4055 |
return true; |
| 4056 |
} else { |
| 4057 |
hash = 0; |
| 4058 |
} |
| 4059 |
|
| 4060 |
cx->executionHashInputs += 1; |
| 4061 |
cx->executionHash = mozilla::RotateLeft(cx->executionHash + hash, 1); |
| 4062 |
return true; |
| 4063 |
} |
| 4064 |
|
| 4065 |
// We have to assume that the fuzzer will be able to call this function e.g. by |
| 4066 |
// enumerating the properties of the global object and eval'ing them. As such |
| 4067 |
// this function is implemented in a way that requires passing some magic value |
| 4068 |
// as first argument (with the idea being that the fuzzer won't be able to |
| 4069 |
// generate this value) which then also acts as a selector for the operation |
| 4070 |
// to perform. |
| 4071 |
static bool Fuzzilli(JSContext* cx, unsigned argc, Value* vp) { |
| 4072 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4073 |
|
| 4074 |
RootedString arg(cx, JS::ToString(cx, args.get(0))); |
| 4075 |
if (!arg) { |
| 4076 |
return false; |
| 4077 |
} |
| 4078 |
Rooted<JSLinearString*> operation(cx, StringToLinearString(cx, arg)); |
| 4079 |
if (!operation) { |
| 4080 |
return false; |
| 4081 |
} |
| 4082 |
|
| 4083 |
if (StringEqualsAscii(operation, "FUZZILLI_CRASH")) { |
| 4084 |
int type; |
| 4085 |
if (!ToInt32(cx, args.get(1), &type)) { |
| 4086 |
return false; |
| 4087 |
} |
| 4088 |
|
| 4089 |
// With this, we can test the various ways the JS shell can crash and make |
| 4090 |
// sure that Fuzzilli is able to detect all of these failures properly. |
| 4091 |
switch (type) { |
| 4092 |
case 0: |
| 4093 |
*((int*)0x41414141) = 0x1337; |
| 4094 |
break; |
| 4095 |
case 1: |
| 4096 |
MOZ_RELEASE_ASSERT(false); |
| 4097 |
break; |
| 4098 |
case 2: |
| 4099 |
MOZ_ASSERT(false); |
| 4100 |
break; |
| 4101 |
case 3: |
| 4102 |
# if defined(JS_CODEGEN_X64) || defined(JS_CODEGEN_X86) |
| 4103 |
__asm__("int3"); |
| 4104 |
# elif defined(JS_CODEGEN_ARM64) |
| 4105 |
__asm__("brk #0"); |
| 4106 |
# endif |
| 4107 |
break; |
| 4108 |
default: |
| 4109 |
exit(1); |
| 4110 |
} |
| 4111 |
} else if (StringEqualsAscii(operation, "FUZZILLI_PRINT")) { |
| 4112 |
static FILE* fzliout = fdopen(REPRL_DWFD, "w"); |
| 4113 |
if (!fzliout) { |
| 4114 |
fprintf( |
| 4115 |
stderr, |
| 4116 |
"Fuzzer output channel not available, printing to stdout instead\n"); |
| 4117 |
fzliout = stdout; |
| 4118 |
} |
| 4119 |
|
| 4120 |
RootedString str(cx, JS::ToString(cx, args.get(1))); |
| 4121 |
if (!str) { |
| 4122 |
return false; |
| 4123 |
} |
| 4124 |
UniqueChars bytes = JS_EncodeStringToUTF8(cx, str); |
| 4125 |
if (!bytes) { |
| 4126 |
return false; |
| 4127 |
} |
| 4128 |
fprintf(fzliout, "%s\n", bytes.get()); |
| 4129 |
fflush(fzliout); |
| 4130 |
} else if (StringEqualsAscii(operation, "FUZZILLI_RANDOM")) { |
| 4131 |
// This is an entropy source which can be called during fuzzing. |
| 4132 |
// Its currently used to tests whether Fuzzilli detects non-deterministic |
| 4133 |
// behavior. |
| 4134 |
args.rval().setInt32(static_cast<uint32_t>(mozilla::RandomUint64OrDie())); |
| 4135 |
return true; |
| 4136 |
} |
| 4137 |
|
| 4138 |
args.rval().setUndefined(); |
| 4139 |
return true; |
| 4140 |
} |
| 4141 |
|
| 4142 |
static bool FuzzilliReprlGetAndRun(JSContext* cx) { |
| 4143 |
size_t scriptSize = 0; |
| 4144 |
|
| 4145 |
unsigned action; |
| 4146 |
MOZ_RELEASE_ASSERT(read(REPRL_CRFD, &action, 4) == 4); |
| 4147 |
if (action == 'cexe') { |
| 4148 |
MOZ_RELEASE_ASSERT(read(REPRL_CRFD, &scriptSize, 8) == 8); |
| 4149 |
} else { |
| 4150 |
fprintf(stderr, "Unknown action: %u\n", action); |
| 4151 |
_exit(-1); |
| 4152 |
} |
| 4153 |
|
| 4154 |
CompileOptions options(cx); |
| 4155 |
options.setIntroductionType("reprl") |
| 4156 |
.setFileAndLine("reprl", 1) |
| 4157 |
.setIsRunOnce(true) |
| 4158 |
.setNoScriptRval(true) |
| 4159 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 4160 |
|
| 4161 |
char* scriptSrc = static_cast<char*>(js_malloc(scriptSize)); |
| 4162 |
|
| 4163 |
char* ptr = scriptSrc; |
| 4164 |
size_t remaining = scriptSize; |
| 4165 |
while (remaining > 0) { |
| 4166 |
ssize_t rv = read(REPRL_DRFD, ptr, remaining); |
| 4167 |
if (rv <= 0) { |
| 4168 |
fprintf(stderr, "Failed to load script\n"); |
| 4169 |
_exit(-1); |
| 4170 |
} |
| 4171 |
remaining -= rv; |
| 4172 |
ptr += rv; |
| 4173 |
} |
| 4174 |
|
| 4175 |
JS::SourceText<Utf8Unit> srcBuf; |
| 4176 |
if (!srcBuf.init(cx, scriptSrc, scriptSize, |
| 4177 |
JS::SourceOwnership::TakeOwnership)) { |
| 4178 |
return false; |
| 4179 |
} |
| 4180 |
|
| 4181 |
RootedScript script(cx, JS::Compile(cx, options, srcBuf)); |
| 4182 |
if (!script) { |
| 4183 |
return false; |
| 4184 |
} |
| 4185 |
|
| 4186 |
if (!JS_ExecuteScript(cx, script)) { |
| 4187 |
return false; |
| 4188 |
} |
| 4189 |
|
| 4190 |
return true; |
| 4191 |
} |
| 4192 |
|
| 4193 |
#endif /* FUZZING_JS_FUZZILLI */ |
| 4194 |
|
| 4195 |
static bool FuzzilliUseReprlMode(OptionParser* op) { |
| 4196 |
#ifdef FUZZING_JS_FUZZILLI |
| 4197 |
// Check if we should use REPRL mode |
| 4198 |
bool reprl_mode = op->getBoolOption("reprl"); |
| 4199 |
if (reprl_mode) { |
| 4200 |
// Check in with parent |
| 4201 |
char helo[] = "HELO"; |
| 4202 |
if (write(REPRL_CWFD, helo, 4) != 4 || read(REPRL_CRFD, helo, 4) != 4) { |
| 4203 |
reprl_mode = false; |
| 4204 |
} |
| 4205 |
|
| 4206 |
if (memcmp(helo, "HELO", 4) != 0) { |
| 4207 |
fprintf(stderr, "Invalid response from parent\n"); |
| 4208 |
_exit(-1); |
| 4209 |
} |
| 4210 |
} |
| 4211 |
return reprl_mode; |
| 4212 |
#else |
| 4213 |
return false; |
| 4214 |
#endif /* FUZZING_JS_FUZZILLI */ |
| 4215 |
} |
| 4216 |
|
| 4217 |
static bool Crash(JSContext* cx, unsigned argc, Value* vp) { |
| 4218 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4219 |
if (args.length() == 0) { |
| 4220 |
MOZ_CRASH("forced crash"); |
| 4221 |
} |
| 4222 |
RootedString message(cx, JS::ToString(cx, args[0])); |
| 4223 |
if (!message) { |
| 4224 |
return false; |
| 4225 |
} |
| 4226 |
UniqueChars utf8chars = JS_EncodeStringToUTF8(cx, message); |
| 4227 |
if (!utf8chars) { |
| 4228 |
return false; |
| 4229 |
} |
| 4230 |
if (args.get(1).isObject()) { |
| 4231 |
RootedValue v(cx); |
| 4232 |
RootedObject opts(cx, &args[1].toObject()); |
| 4233 |
if (!JS_GetProperty(cx, opts, "suppress_minidump", &v)) { |
| 4234 |
return false; |
| 4235 |
} |
| 4236 |
if (v.isBoolean() && v.toBoolean()) { |
| 4237 |
js::NoteIntentionalCrash(); |
| 4238 |
} |
| 4239 |
} |
| 4240 |
#ifndef DEBUG |
| 4241 |
MOZ_ReportCrash(utf8chars.get(), __FILE__, __LINE__); |
| 4242 |
#endif |
| 4243 |
MOZ_CRASH_UNSAFE(utf8chars.get()); |
| 4244 |
} |
| 4245 |
|
| 4246 |
static bool GetSLX(JSContext* cx, unsigned argc, Value* vp) { |
| 4247 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4248 |
RootedScript script(cx); |
| 4249 |
|
| 4250 |
script = TestingFunctionArgumentToScript(cx, args.get(0)); |
| 4251 |
if (!script) { |
| 4252 |
return false; |
| 4253 |
} |
| 4254 |
args.rval().setInt32(GetScriptLineExtent(script)); |
| 4255 |
return true; |
| 4256 |
} |
| 4257 |
|
| 4258 |
static bool ThrowError(JSContext* cx, unsigned argc, Value* vp) { |
| 4259 |
JS_ReportErrorASCII(cx, "This is an error"); |
| 4260 |
return false; |
| 4261 |
} |
| 4262 |
|
| 4263 |
static bool CopyErrorReportToObject(JSContext* cx, JSErrorReport* report, |
| 4264 |
HandleObject obj) { |
| 4265 |
RootedString nameStr(cx); |
| 4266 |
if (report->exnType == JSEXN_WARN) { |
| 4267 |
nameStr = JS_NewStringCopyZ(cx, "Warning"); |
| 4268 |
if (!nameStr) { |
| 4269 |
return false; |
| 4270 |
} |
| 4271 |
} else { |
| 4272 |
nameStr = GetErrorTypeName(cx, report->exnType); |
| 4273 |
// GetErrorTypeName doesn't set an exception, but |
| 4274 |
// can fail for InternalError or non-error objects. |
| 4275 |
if (!nameStr) { |
| 4276 |
nameStr = cx->runtime()->emptyString; |
| 4277 |
} |
| 4278 |
} |
| 4279 |
RootedValue nameVal(cx, StringValue(nameStr)); |
| 4280 |
if (!DefineDataProperty(cx, obj, cx->names().name, nameVal)) { |
| 4281 |
return false; |
| 4282 |
} |
| 4283 |
|
| 4284 |
RootedString messageStr(cx, report->newMessageString(cx)); |
| 4285 |
if (!messageStr) { |
| 4286 |
return false; |
| 4287 |
} |
| 4288 |
RootedValue messageVal(cx, StringValue(messageStr)); |
| 4289 |
if (!DefineDataProperty(cx, obj, cx->names().message, messageVal)) { |
| 4290 |
return false; |
| 4291 |
} |
| 4292 |
|
| 4293 |
RootedValue linenoVal(cx, Int32Value(report->lineno)); |
| 4294 |
if (!DefineDataProperty(cx, obj, cx->names().lineNumber, linenoVal)) { |
| 4295 |
return false; |
| 4296 |
} |
| 4297 |
|
| 4298 |
RootedValue columnVal(cx, Int32Value(report->column.oneOriginValue())); |
| 4299 |
if (!DefineDataProperty(cx, obj, cx->names().columnNumber, columnVal)) { |
| 4300 |
return false; |
| 4301 |
} |
| 4302 |
|
| 4303 |
RootedObject notesArray(cx, CreateErrorNotesArray(cx, report)); |
| 4304 |
if (!notesArray) { |
| 4305 |
return false; |
| 4306 |
} |
| 4307 |
|
| 4308 |
RootedValue notesArrayVal(cx, ObjectValue(*notesArray)); |
| 4309 |
return DefineDataProperty(cx, obj, cx->names().notes, notesArrayVal); |
| 4310 |
} |
| 4311 |
|
| 4312 |
static bool CreateErrorReport(JSContext* cx, unsigned argc, Value* vp) { |
| 4313 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4314 |
|
| 4315 |
// We don't have a stack here, so just initialize with null. |
| 4316 |
JS::ExceptionStack exnStack(cx, args.get(0), nullptr); |
| 4317 |
JS::ErrorReportBuilder report(cx); |
| 4318 |
if (!report.init(cx, exnStack, JS::ErrorReportBuilder::WithSideEffects)) { |
| 4319 |
return false; |
| 4320 |
} |
| 4321 |
|
| 4322 |
MOZ_ASSERT(!report.report()->isWarning()); |
| 4323 |
|
| 4324 |
RootedObject obj(cx, JS_NewPlainObject(cx)); |
| 4325 |
if (!obj) { |
| 4326 |
return false; |
| 4327 |
} |
| 4328 |
|
| 4329 |
RootedString toString(cx, NewStringCopyUTF8Z(cx, report.toStringResult())); |
| 4330 |
if (!toString) { |
| 4331 |
return false; |
| 4332 |
} |
| 4333 |
|
| 4334 |
if (!JS_DefineProperty(cx, obj, "toStringResult", toString, |
| 4335 |
JSPROP_ENUMERATE)) { |
| 4336 |
return false; |
| 4337 |
} |
| 4338 |
|
| 4339 |
if (!CopyErrorReportToObject(cx, report.report(), obj)) { |
| 4340 |
return false; |
| 4341 |
} |
| 4342 |
|
| 4343 |
args.rval().setObject(*obj); |
| 4344 |
return true; |
| 4345 |
} |
| 4346 |
|
| 4347 |
#define LAZY_STANDARD_CLASSES |
| 4348 |
|
| 4349 |
/* A class for easily testing the inner/outer object callbacks. */ |
| 4350 |
struct ComplexObject { |
| 4351 |
bool isInner; |
| 4352 |
bool frozen; |
| 4353 |
JSObject* inner; |
| 4354 |
JSObject* outer; |
| 4355 |
}; |
| 4356 |
|
| 4357 |
static bool sandbox_enumerate(JSContext* cx, JS::HandleObject obj, |
| 4358 |
JS::MutableHandleIdVector properties, |
| 4359 |
bool enumerableOnly) { |
| 4360 |
RootedValue v(cx); |
| 4361 |
|
| 4362 |
if (!JS_GetProperty(cx, obj, "lazy", &v)) { |
| 4363 |
return false; |
| 4364 |
} |
| 4365 |
|
| 4366 |
if (!ToBoolean(v)) { |
| 4367 |
return true; |
| 4368 |
} |
| 4369 |
|
| 4370 |
return JS_NewEnumerateStandardClasses(cx, obj, properties, enumerableOnly); |
| 4371 |
} |
| 4372 |
|
| 4373 |
static bool sandbox_resolve(JSContext* cx, HandleObject obj, HandleId id, |
| 4374 |
bool* resolvedp) { |
| 4375 |
RootedValue v(cx); |
| 4376 |
if (!JS_GetProperty(cx, obj, "lazy", &v)) { |
| 4377 |
return false; |
| 4378 |
} |
| 4379 |
|
| 4380 |
if (ToBoolean(v)) { |
| 4381 |
return JS_ResolveStandardClass(cx, obj, id, resolvedp); |
| 4382 |
} |
| 4383 |
return true; |
| 4384 |
} |
| 4385 |
|
| 4386 |
static const JSClassOps sandbox_classOps = { |
| 4387 |
nullptr, // addProperty |
| 4388 |
nullptr, // delProperty |
| 4389 |
nullptr, // enumerate |
| 4390 |
sandbox_enumerate, // newEnumerate |
| 4391 |
sandbox_resolve, // resolve |
| 4392 |
nullptr, // mayResolve |
| 4393 |
nullptr, // finalize |
| 4394 |
nullptr, // call |
| 4395 |
nullptr, // construct |
| 4396 |
JS_GlobalObjectTraceHook, // trace |
| 4397 |
}; |
| 4398 |
|
| 4399 |
static const JSClass sandbox_class = { |
| 4400 |
"sandbox", |
| 4401 |
JSCLASS_GLOBAL_FLAGS, |
| 4402 |
&sandbox_classOps, |
| 4403 |
}; |
| 4404 |
|
| 4405 |
static void SetStandardRealmOptions(JS::RealmOptions& options) { |
| 4406 |
options.creationOptions() |
| 4407 |
.setSharedMemoryAndAtomicsEnabled(enableSharedMemory) |
| 4408 |
.setCoopAndCoepEnabled(false) |
| 4409 |
.setToSourceEnabled(enableToSource); |
| 4410 |
} |
| 4411 |
|
| 4412 |
[[nodiscard]] static bool CheckRealmOptions(JSContext* cx, |
| 4413 |
JS::RealmOptions& options, |
| 4414 |
JSPrincipals* principals) { |
| 4415 |
JS::RealmCreationOptions& creationOptions = options.creationOptions(); |
| 4416 |
if (creationOptions.compartmentSpecifier() != |
| 4417 |
JS::CompartmentSpecifier::ExistingCompartment) { |
| 4418 |
return true; |
| 4419 |
} |
| 4420 |
|
| 4421 |
JS::Compartment* comp = creationOptions.compartment(); |
| 4422 |
|
| 4423 |
// All realms in a compartment must be either system or non-system. |
| 4424 |
bool isSystem = |
| 4425 |
principals && principals == cx->runtime()->trustedPrincipals(); |
| 4426 |
if (isSystem != IsSystemCompartment(comp)) { |
| 4427 |
JS_ReportErrorASCII(cx, |
| 4428 |
"Cannot create system and non-system realms in the " |
| 4429 |
"same compartment"); |
| 4430 |
return false; |
| 4431 |
} |
| 4432 |
|
| 4433 |
// Debugger visibility is per-compartment, not per-realm, so make sure the |
| 4434 |
// requested visibility matches the existing compartment's. |
| 4435 |
if (creationOptions.invisibleToDebugger() != comp->invisibleToDebugger()) { |
| 4436 |
JS_ReportErrorASCII(cx, |
| 4437 |
"All the realms in a compartment must have " |
| 4438 |
"the same debugger visibility"); |
| 4439 |
return false; |
| 4440 |
} |
| 4441 |
|
| 4442 |
return true; |
| 4443 |
} |
| 4444 |
|
| 4445 |
static JSObject* NewSandbox(JSContext* cx, bool lazy) { |
| 4446 |
JS::RealmOptions options; |
| 4447 |
SetStandardRealmOptions(options); |
| 4448 |
|
| 4449 |
if (defaultToSameCompartment) { |
| 4450 |
options.creationOptions().setExistingCompartment(cx->global()); |
| 4451 |
} else { |
| 4452 |
options.creationOptions().setNewCompartmentAndZone(); |
| 4453 |
} |
| 4454 |
|
| 4455 |
JSPrincipals* principals = nullptr; |
| 4456 |
if (!CheckRealmOptions(cx, options, principals)) { |
| 4457 |
return nullptr; |
| 4458 |
} |
| 4459 |
|
| 4460 |
RootedObject obj(cx, |
| 4461 |
JS_NewGlobalObject(cx, &sandbox_class, principals, |
| 4462 |
JS::DontFireOnNewGlobalHook, options)); |
| 4463 |
if (!obj) { |
| 4464 |
return nullptr; |
| 4465 |
} |
| 4466 |
|
| 4467 |
{ |
| 4468 |
JSAutoRealm ar(cx, obj); |
| 4469 |
if (!lazy && !JS::InitRealmStandardClasses(cx)) { |
| 4470 |
return nullptr; |
| 4471 |
} |
| 4472 |
|
| 4473 |
RootedValue value(cx, BooleanValue(lazy)); |
| 4474 |
if (!JS_DefineProperty(cx, obj, "lazy", value, |
| 4475 |
JSPROP_PERMANENT | JSPROP_READONLY)) { |
| 4476 |
return nullptr; |
| 4477 |
} |
| 4478 |
|
| 4479 |
JS_FireOnNewGlobalObject(cx, obj); |
| 4480 |
} |
| 4481 |
|
| 4482 |
if (!cx->compartment()->wrap(cx, &obj)) { |
| 4483 |
return nullptr; |
| 4484 |
} |
| 4485 |
return obj; |
| 4486 |
} |
| 4487 |
|
| 4488 |
static bool EvalInContext(JSContext* cx, unsigned argc, Value* vp) { |
| 4489 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4490 |
if (!args.requireAtLeast(cx, "evalcx", 1)) { |
| 4491 |
return false; |
| 4492 |
} |
| 4493 |
|
| 4494 |
RootedString str(cx, ToString(cx, args[0])); |
| 4495 |
if (!str) { |
| 4496 |
return false; |
| 4497 |
} |
| 4498 |
|
| 4499 |
RootedObject sobj(cx); |
| 4500 |
if (args.hasDefined(1)) { |
| 4501 |
sobj = ToObject(cx, args[1]); |
| 4502 |
if (!sobj) { |
| 4503 |
return false; |
| 4504 |
} |
| 4505 |
} |
| 4506 |
|
| 4507 |
AutoStableStringChars strChars(cx); |
| 4508 |
if (!strChars.initTwoByte(cx, str)) { |
| 4509 |
return false; |
| 4510 |
} |
| 4511 |
|
| 4512 |
mozilla::Range<const char16_t> chars = strChars.twoByteRange(); |
| 4513 |
size_t srclen = chars.length(); |
| 4514 |
const char16_t* src = chars.begin().get(); |
| 4515 |
|
| 4516 |
bool lazy = false; |
| 4517 |
if (srclen == 4) { |
| 4518 |
if (src[0] == 'l' && src[1] == 'a' && src[2] == 'z' && src[3] == 'y') { |
| 4519 |
lazy = true; |
| 4520 |
srclen = 0; |
| 4521 |
} |
| 4522 |
} |
| 4523 |
|
| 4524 |
if (!sobj) { |
| 4525 |
sobj = NewSandbox(cx, lazy); |
| 4526 |
if (!sobj) { |
| 4527 |
return false; |
| 4528 |
} |
| 4529 |
} |
| 4530 |
|
| 4531 |
if (srclen == 0) { |
| 4532 |
args.rval().setObject(*sobj); |
| 4533 |
return true; |
| 4534 |
} |
| 4535 |
|
| 4536 |
JS::AutoFilename filename; |
| 4537 |
uint32_t lineno; |
| 4538 |
|
| 4539 |
DescribeScriptedCaller(&filename, cx, &lineno); |
| 4540 |
{ |
| 4541 |
sobj = UncheckedUnwrap(sobj, true); |
| 4542 |
|
| 4543 |
JSAutoRealm ar(cx, sobj); |
| 4544 |
|
| 4545 |
sobj = ToWindowIfWindowProxy(sobj); |
| 4546 |
|
| 4547 |
if (!JS_IsGlobalObject(sobj)) { |
| 4548 |
JS_ReportErrorASCII(cx, "Invalid scope argument to evalcx"); |
| 4549 |
return false; |
| 4550 |
} |
| 4551 |
|
| 4552 |
JS::CompileOptions opts(cx); |
| 4553 |
opts.setFileAndLine(filename.get(), lineno) |
| 4554 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 4555 |
|
| 4556 |
JS::SourceText<char16_t> srcBuf; |
| 4557 |
if (!srcBuf.init(cx, src, srclen, JS::SourceOwnership::Borrowed) || |
| 4558 |
!JS::Evaluate(cx, opts, srcBuf, args.rval())) { |
| 4559 |
return false; |
| 4560 |
} |
| 4561 |
} |
| 4562 |
|
| 4563 |
if (!cx->compartment()->wrap(cx, args.rval())) { |
| 4564 |
return false; |
| 4565 |
} |
| 4566 |
|
| 4567 |
return true; |
| 4568 |
} |
| 4569 |
|
| 4570 |
static bool EnsureGeckoProfilingStackInstalled(JSContext* cx, |
| 4571 |
ShellContext* sc) { |
| 4572 |
if (cx->geckoProfiler().infraInstalled()) { |
| 4573 |
MOZ_ASSERT(sc->geckoProfilingStack); |
| 4574 |
return true; |
| 4575 |
} |
| 4576 |
|
| 4577 |
MOZ_ASSERT(!sc->geckoProfilingStack); |
| 4578 |
sc->geckoProfilingStack = MakeUnique<ProfilingStack>(); |
| 4579 |
if (!sc->geckoProfilingStack) { |
| 4580 |
JS_ReportOutOfMemory(cx); |
| 4581 |
return false; |
| 4582 |
} |
| 4583 |
|
| 4584 |
SetContextProfilingStack(cx, sc->geckoProfilingStack.get()); |
| 4585 |
return true; |
| 4586 |
} |
| 4587 |
|
| 4588 |
struct WorkerInput { |
| 4589 |
JSRuntime* parentRuntime; |
| 4590 |
UniqueTwoByteChars chars; |
| 4591 |
size_t length; |
| 4592 |
|
| 4593 |
WorkerInput(JSRuntime* parentRuntime, UniqueTwoByteChars chars, size_t length) |
| 4594 |
: parentRuntime(parentRuntime), chars(std::move(chars)), length(length) {} |
| 4595 |
}; |
| 4596 |
|
| 4597 |
static void DestroyShellCompartmentPrivate(JS::GCContext* gcx, |
| 4598 |
JS::Compartment* compartment) { |
| 4599 |
auto priv = static_cast<ShellCompartmentPrivate*>( |
| 4600 |
JS_GetCompartmentPrivate(compartment)); |
| 4601 |
js_delete(priv); |
| 4602 |
} |
| 4603 |
|
| 4604 |
static void SetWorkerContextOptions(JSContext* cx); |
| 4605 |
static bool ShellBuildId(JS::BuildIdCharVector* buildId); |
| 4606 |
|
| 4607 |
static constexpr size_t gWorkerStackSize = 2 * 128 * sizeof(size_t) * 1024; |
| 4608 |
|
| 4609 |
static void WorkerMain(UniquePtr<WorkerInput> input) { |
| 4610 |
MOZ_ASSERT(input->parentRuntime); |
| 4611 |
|
| 4612 |
JSContext* cx = JS_NewContext(8L * 1024L * 1024L, input->parentRuntime); |
| 4613 |
if (!cx) { |
| 4614 |
return; |
| 4615 |
} |
| 4616 |
auto destroyContext = MakeScopeExit([cx] { JS_DestroyContext(cx); }); |
| 4617 |
|
| 4618 |
UniquePtr<ShellContext> sc = |
| 4619 |
MakeUnique<ShellContext>(cx, ShellContext::Worker); |
| 4620 |
if (!sc || !sc->registerWithCx(cx)) { |
| 4621 |
return; |
| 4622 |
} |
| 4623 |
|
| 4624 |
if (!JS::InitSelfHostedCode(cx)) { |
| 4625 |
return; |
| 4626 |
} |
| 4627 |
|
| 4628 |
EnvironmentPreparer environmentPreparer(cx); |
| 4629 |
|
| 4630 |
do { |
| 4631 |
JS::RealmOptions realmOptions; |
| 4632 |
SetStandardRealmOptions(realmOptions); |
| 4633 |
|
| 4634 |
RootedObject global(cx, NewGlobalObject(cx, realmOptions, nullptr, |
| 4635 |
ShellGlobalKind::WindowProxy, |
| 4636 |
/* immutablePrototype = */ true)); |
| 4637 |
if (!global) { |
| 4638 |
break; |
| 4639 |
} |
| 4640 |
|
| 4641 |
JSAutoRealm ar(cx, global); |
| 4642 |
|
| 4643 |
JS::ConstUTF8CharsZ path(processWideModuleLoadPath.get(), |
| 4644 |
strlen(processWideModuleLoadPath.get())); |
| 4645 |
RootedString moduleLoadPath(cx, JS_NewStringCopyUTF8Z(cx, path)); |
| 4646 |
if (!moduleLoadPath) { |
| 4647 |
return; |
| 4648 |
} |
| 4649 |
sc->moduleLoader = js::MakeUnique<ModuleLoader>(); |
| 4650 |
if (!sc->moduleLoader || !sc->moduleLoader->init(cx, moduleLoadPath)) { |
| 4651 |
return; |
| 4652 |
} |
| 4653 |
|
| 4654 |
JS::CompileOptions options(cx); |
| 4655 |
options.setFileAndLine("<string>", 1) |
| 4656 |
.setIsRunOnce(true) |
| 4657 |
.setEagerDelazificationStrategy(defaultDelazificationMode); |
| 4658 |
|
| 4659 |
{ |
| 4660 |
AutoReportException are(cx); |
| 4661 |
JS::SourceText<char16_t> srcBuf; |
| 4662 |
if (!srcBuf.init(cx, input->chars.get(), input->length, |
| 4663 |
JS::SourceOwnership::Borrowed)) { |
| 4664 |
break; |
| 4665 |
} |
| 4666 |
|
| 4667 |
RootedScript script(cx, JS::Compile(cx, options, srcBuf)); |
| 4668 |
if (!script) { |
| 4669 |
break; |
| 4670 |
} |
| 4671 |
RootedValue result(cx); |
| 4672 |
JS_ExecuteScript(cx, script, &result); |
| 4673 |
} |
| 4674 |
|
| 4675 |
RunShellJobs(cx); |
| 4676 |
} while (0); |
| 4677 |
|
| 4678 |
KillWatchdog(cx); |
| 4679 |
} |
| 4680 |
|
| 4681 |
// Workers can spawn other workers, so we need a lock to access workerThreads. |
| 4682 |
static Mutex* workerThreadsLock = nullptr; |
| 4683 |
MOZ_RUNINIT static Vector<UniquePtr<js::Thread>, 0, SystemAllocPolicy> |
| 4684 |
workerThreads; |
| 4685 |
|
| 4686 |
class MOZ_RAII AutoLockWorkerThreads : public LockGuard<Mutex> { |
| 4687 |
using Base = LockGuard<Mutex>; |
| 4688 |
|
| 4689 |
public: |
| 4690 |
AutoLockWorkerThreads() : Base(*workerThreadsLock) { |
| 4691 |
MOZ_ASSERT(workerThreadsLock); |
| 4692 |
} |
| 4693 |
}; |
| 4694 |
|
| 4695 |
static bool EvalInWorker(JSContext* cx, unsigned argc, Value* vp) { |
| 4696 |
if (!CanUseExtraThreads()) { |
| 4697 |
JS_ReportErrorASCII(cx, "Can't create threads with --no-threads"); |
| 4698 |
return false; |
| 4699 |
} |
| 4700 |
|
| 4701 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4702 |
if (!args.get(0).isString()) { |
| 4703 |
JS_ReportErrorASCII(cx, "Invalid arguments"); |
| 4704 |
return false; |
| 4705 |
} |
| 4706 |
|
| 4707 |
#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) |
| 4708 |
if (cx->runningOOMTest) { |
| 4709 |
JS_ReportErrorASCII( |
| 4710 |
cx, "Can't create threads while running simulated OOM test"); |
| 4711 |
return false; |
| 4712 |
} |
| 4713 |
#endif |
| 4714 |
|
| 4715 |
if (!args[0].toString()->ensureLinear(cx)) { |
| 4716 |
return false; |
| 4717 |
} |
| 4718 |
|
| 4719 |
if (!workerThreadsLock) { |
| 4720 |
workerThreadsLock = js_new<Mutex>(mutexid::ShellWorkerThreads); |
| 4721 |
if (!workerThreadsLock) { |
| 4722 |
ReportOutOfMemory(cx); |
| 4723 |
return false; |
| 4724 |
} |
| 4725 |
} |
| 4726 |
|
| 4727 |
JSLinearString* str = &args[0].toString()->asLinear(); |
| 4728 |
|
| 4729 |
UniqueTwoByteChars chars(js_pod_malloc<char16_t>(str->length())); |
| 4730 |
if (!chars) { |
| 4731 |
ReportOutOfMemory(cx); |
| 4732 |
return false; |
| 4733 |
} |
| 4734 |
|
| 4735 |
CopyChars(chars.get(), *str); |
| 4736 |
|
| 4737 |
auto input = js::MakeUnique<WorkerInput>(JS_GetParentRuntime(cx), |
| 4738 |
std::move(chars), str->length()); |
| 4739 |
if (!input) { |
| 4740 |
ReportOutOfMemory(cx); |
| 4741 |
return false; |
| 4742 |
} |
| 4743 |
|
| 4744 |
UniquePtr<Thread> thread; |
| 4745 |
{ |
| 4746 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 4747 |
thread = js::MakeUnique<Thread>( |
| 4748 |
Thread::Options().setStackSize(gWorkerStackSize + 512 * 1024)); |
| 4749 |
if (!thread || !thread->init(WorkerMain, std::move(input))) { |
| 4750 |
oomUnsafe.crash("EvalInWorker"); |
| 4751 |
} |
| 4752 |
} |
| 4753 |
|
| 4754 |
AutoLockWorkerThreads alwt; |
| 4755 |
if (!workerThreads.append(std::move(thread))) { |
| 4756 |
ReportOutOfMemory(cx); |
| 4757 |
thread->join(); |
| 4758 |
return false; |
| 4759 |
} |
| 4760 |
|
| 4761 |
args.rval().setUndefined(); |
| 4762 |
return true; |
| 4763 |
} |
| 4764 |
|
| 4765 |
static bool ShapeOf(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 4766 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4767 |
if (!args.get(0).isObject()) { |
| 4768 |
JS_ReportErrorASCII(cx, "shapeOf: object expected"); |
| 4769 |
return false; |
| 4770 |
} |
| 4771 |
JSObject* obj = &args[0].toObject(); |
| 4772 |
args.rval().set(JS_NumberValue(double(uintptr_t(obj->shape()) >> 3))); |
| 4773 |
return true; |
| 4774 |
} |
| 4775 |
|
| 4776 |
static bool Sleep_fn(JSContext* cx, unsigned argc, Value* vp) { |
| 4777 |
ShellContext* sc = GetShellContext(cx); |
| 4778 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4779 |
|
| 4780 |
TimeDuration duration = TimeDuration::FromSeconds(0.0); |
| 4781 |
if (args.length() > 0) { |
| 4782 |
double t_secs; |
| 4783 |
if (!ToNumber(cx, args[0], &t_secs)) { |
| 4784 |
return false; |
| 4785 |
} |
| 4786 |
if (std::isnan(t_secs)) { |
| 4787 |
JS_ReportErrorASCII(cx, "sleep interval is not a number"); |
| 4788 |
return false; |
| 4789 |
} |
| 4790 |
|
| 4791 |
duration = TimeDuration::FromSeconds(std::max(0.0, t_secs)); |
| 4792 |
const TimeDuration MAX_TIMEOUT_INTERVAL = |
| 4793 |
TimeDuration::FromSeconds(MAX_TIMEOUT_SECONDS); |
| 4794 |
if (duration > MAX_TIMEOUT_INTERVAL) { |
| 4795 |
JS_ReportErrorASCII(cx, "Excessive sleep interval"); |
| 4796 |
return false; |
| 4797 |
} |
| 4798 |
} |
| 4799 |
{ |
| 4800 |
LockGuard<Mutex> guard(sc->watchdogLock); |
| 4801 |
TimeStamp toWakeup = TimeStamp::Now() + duration; |
| 4802 |
for (;;) { |
| 4803 |
sc->sleepWakeup.wait_for(guard, duration); |
| 4804 |
if (sc->serviceInterrupt) { |
| 4805 |
break; |
| 4806 |
} |
| 4807 |
auto now = TimeStamp::Now(); |
| 4808 |
if (now >= toWakeup) { |
| 4809 |
break; |
| 4810 |
} |
| 4811 |
duration = toWakeup - now; |
| 4812 |
} |
| 4813 |
} |
| 4814 |
|
| 4815 |
if (sc->serviceInterrupt) { |
| 4816 |
JS::ReportUncatchableException(cx); |
| 4817 |
return false; |
| 4818 |
} |
| 4819 |
|
| 4820 |
args.rval().setUndefined(); |
| 4821 |
return true; |
| 4822 |
} |
| 4823 |
|
| 4824 |
static void KillWatchdog(JSContext* cx) { |
| 4825 |
ShellContext* sc = GetShellContext(cx); |
| 4826 |
Maybe<Thread> thread; |
| 4827 |
|
| 4828 |
{ |
| 4829 |
LockGuard<Mutex> guard(sc->watchdogLock); |
| 4830 |
std::swap(sc->watchdogThread, thread); |
| 4831 |
if (thread) { |
| 4832 |
// The watchdog thread becoming Nothing is its signal to exit. |
| 4833 |
sc->watchdogWakeup.notify_one(); |
| 4834 |
} |
| 4835 |
} |
| 4836 |
if (thread) { |
| 4837 |
thread->join(); |
| 4838 |
} |
| 4839 |
|
| 4840 |
MOZ_ASSERT(!sc->watchdogThread); |
| 4841 |
} |
| 4842 |
|
| 4843 |
static void WatchdogMain(JSContext* cx) { |
| 4844 |
ThisThread::SetName("JS Watchdog"); |
| 4845 |
|
| 4846 |
ShellContext* sc = GetShellContext(cx); |
| 4847 |
|
| 4848 |
{ |
| 4849 |
LockGuard<Mutex> guard(sc->watchdogLock); |
| 4850 |
while (sc->watchdogThread) { |
| 4851 |
auto now = TimeStamp::Now(); |
| 4852 |
if (sc->watchdogTimeout && now >= sc->watchdogTimeout.value()) { |
| 4853 |
/* |
| 4854 |
* The timeout has just expired. Request an interrupt callback |
| 4855 |
* outside the lock. |
| 4856 |
*/ |
| 4857 |
sc->watchdogTimeout = Nothing(); |
| 4858 |
{ |
| 4859 |
UnlockGuard unlock(guard); |
| 4860 |
CancelExecution(cx); |
| 4861 |
} |
| 4862 |
|
| 4863 |
/* Wake up any threads doing sleep. */ |
| 4864 |
sc->sleepWakeup.notify_all(); |
| 4865 |
} else { |
| 4866 |
if (sc->watchdogTimeout) { |
| 4867 |
/* |
| 4868 |
* Time hasn't expired yet. Simulate an interrupt callback |
| 4869 |
* which doesn't abort execution. |
| 4870 |
*/ |
| 4871 |
JS_RequestInterruptCallback(cx); |
| 4872 |
} |
| 4873 |
|
| 4874 |
TimeDuration sleepDuration = sc->watchdogTimeout |
| 4875 |
? TimeDuration::FromSeconds(0.1) |
| 4876 |
: TimeDuration::Forever(); |
| 4877 |
sc->watchdogWakeup.wait_for(guard, sleepDuration); |
| 4878 |
} |
| 4879 |
} |
| 4880 |
} |
| 4881 |
} |
| 4882 |
|
| 4883 |
static bool ScheduleWatchdog(JSContext* cx, double t) { |
| 4884 |
ShellContext* sc = GetShellContext(cx); |
| 4885 |
|
| 4886 |
if (t <= 0) { |
| 4887 |
LockGuard<Mutex> guard(sc->watchdogLock); |
| 4888 |
sc->watchdogTimeout = Nothing(); |
| 4889 |
return true; |
| 4890 |
} |
| 4891 |
|
| 4892 |
#ifdef __wasi__ |
| 4893 |
return false; |
| 4894 |
#endif |
| 4895 |
|
| 4896 |
auto interval = TimeDuration::FromSeconds(t); |
| 4897 |
auto timeout = TimeStamp::Now() + interval; |
| 4898 |
LockGuard<Mutex> guard(sc->watchdogLock); |
| 4899 |
if (!sc->watchdogThread) { |
| 4900 |
MOZ_ASSERT(!sc->watchdogTimeout); |
| 4901 |
sc->watchdogThread.emplace(); |
| 4902 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 4903 |
if (!sc->watchdogThread->init(WatchdogMain, cx)) { |
| 4904 |
oomUnsafe.crash("watchdogThread.init"); |
| 4905 |
} |
| 4906 |
} else if (!sc->watchdogTimeout || timeout < sc->watchdogTimeout.value()) { |
| 4907 |
sc->watchdogWakeup.notify_one(); |
| 4908 |
} |
| 4909 |
sc->watchdogTimeout = Some(timeout); |
| 4910 |
return true; |
| 4911 |
} |
| 4912 |
|
| 4913 |
static void KillWorkerThreads(JSContext* cx) { |
| 4914 |
MOZ_ASSERT_IF(!CanUseExtraThreads(), workerThreads.empty()); |
| 4915 |
|
| 4916 |
if (!workerThreadsLock) { |
| 4917 |
MOZ_ASSERT(workerThreads.empty()); |
| 4918 |
return; |
| 4919 |
} |
| 4920 |
|
| 4921 |
while (true) { |
| 4922 |
// We need to leave the AutoLockWorkerThreads scope before we call |
| 4923 |
// js::Thread::join, to avoid deadlocks when AutoLockWorkerThreads is |
| 4924 |
// used by the worker thread. |
| 4925 |
UniquePtr<Thread> thread; |
| 4926 |
{ |
| 4927 |
AutoLockWorkerThreads alwt; |
| 4928 |
if (workerThreads.empty()) { |
| 4929 |
break; |
| 4930 |
} |
| 4931 |
thread = std::move(workerThreads.back()); |
| 4932 |
workerThreads.popBack(); |
| 4933 |
} |
| 4934 |
thread->join(); |
| 4935 |
} |
| 4936 |
|
| 4937 |
workerThreads.clearAndFree(); |
| 4938 |
|
| 4939 |
js_delete(workerThreadsLock); |
| 4940 |
workerThreadsLock = nullptr; |
| 4941 |
} |
| 4942 |
|
| 4943 |
static void CancelExecution(JSContext* cx) { |
| 4944 |
ShellContext* sc = GetShellContext(cx); |
| 4945 |
sc->serviceInterrupt = true; |
| 4946 |
JS_RequestInterruptCallback(cx); |
| 4947 |
} |
| 4948 |
|
| 4949 |
static bool SetTimeoutValue(JSContext* cx, double t) { |
| 4950 |
if (std::isnan(t)) { |
| 4951 |
JS_ReportErrorASCII(cx, "timeout is not a number"); |
| 4952 |
return false; |
| 4953 |
} |
| 4954 |
const TimeDuration MAX_TIMEOUT_INTERVAL = |
| 4955 |
TimeDuration::FromSeconds(MAX_TIMEOUT_SECONDS); |
| 4956 |
if (TimeDuration::FromSeconds(t) > MAX_TIMEOUT_INTERVAL) { |
| 4957 |
JS_ReportErrorASCII(cx, "Excessive timeout value"); |
| 4958 |
return false; |
| 4959 |
} |
| 4960 |
GetShellContext(cx)->timeoutInterval = t; |
| 4961 |
if (!ScheduleWatchdog(cx, t)) { |
| 4962 |
JS_ReportErrorASCII(cx, "Failed to create the watchdog"); |
| 4963 |
return false; |
| 4964 |
} |
| 4965 |
return true; |
| 4966 |
} |
| 4967 |
|
| 4968 |
static bool Timeout(JSContext* cx, unsigned argc, Value* vp) { |
| 4969 |
ShellContext* sc = GetShellContext(cx); |
| 4970 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 4971 |
|
| 4972 |
if (args.length() == 0) { |
| 4973 |
args.rval().setNumber(sc->timeoutInterval); |
| 4974 |
return true; |
| 4975 |
} |
| 4976 |
|
| 4977 |
if (args.length() > 2) { |
| 4978 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 4979 |
return false; |
| 4980 |
} |
| 4981 |
|
| 4982 |
double t; |
| 4983 |
if (!ToNumber(cx, args[0], &t)) { |
| 4984 |
return false; |
| 4985 |
} |
| 4986 |
|
| 4987 |
if (args.length() > 1) { |
| 4988 |
RootedValue value(cx, args[1]); |
| 4989 |
if (!value.isObject() || !value.toObject().is<JSFunction>()) { |
| 4990 |
JS_ReportErrorASCII(cx, "Second argument must be a timeout function"); |
| 4991 |
return false; |
| 4992 |
} |
| 4993 |
sc->interruptFunc = value; |
| 4994 |
sc->haveInterruptFunc = true; |
| 4995 |
} |
| 4996 |
|
| 4997 |
args.rval().setUndefined(); |
| 4998 |
return SetTimeoutValue(cx, t); |
| 4999 |
} |
| 5000 |
|
| 5001 |
static bool InterruptIf(JSContext* cx, unsigned argc, Value* vp) { |
| 5002 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5003 |
|
| 5004 |
if (args.length() != 1) { |
| 5005 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 5006 |
return false; |
| 5007 |
} |
| 5008 |
|
| 5009 |
if (ToBoolean(args[0])) { |
| 5010 |
GetShellContext(cx)->serviceInterrupt = true; |
| 5011 |
JS_RequestInterruptCallback(cx); |
| 5012 |
} |
| 5013 |
|
| 5014 |
args.rval().setUndefined(); |
| 5015 |
return true; |
| 5016 |
} |
| 5017 |
|
| 5018 |
static bool InvokeInterruptCallbackWrapper(JSContext* cx, unsigned argc, |
| 5019 |
Value* vp) { |
| 5020 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5021 |
if (args.length() != 1) { |
| 5022 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 5023 |
return false; |
| 5024 |
} |
| 5025 |
|
| 5026 |
GetShellContext(cx)->serviceInterrupt = true; |
| 5027 |
JS_RequestInterruptCallback(cx); |
| 5028 |
bool interruptRv = CheckForInterrupt(cx); |
| 5029 |
|
| 5030 |
// The interrupt handler could have set a pending exception. Since we call |
| 5031 |
// back into JS, don't have it see the pending exception. If we have an |
| 5032 |
// uncatchable exception that's not propagating a debug mode forced |
| 5033 |
// return, return. |
| 5034 |
if (!interruptRv && !cx->isExceptionPending() && |
| 5035 |
!cx->isPropagatingForcedReturn()) { |
| 5036 |
return false; |
| 5037 |
} |
| 5038 |
|
| 5039 |
JS::AutoSaveExceptionState savedExc(cx); |
| 5040 |
|
| 5041 |
FixedInvokeArgs<1> iargs(cx); |
| 5042 |
|
| 5043 |
iargs[0].setBoolean(interruptRv); |
| 5044 |
|
| 5045 |
RootedValue rv(cx); |
| 5046 |
if (!js::Call(cx, args[0], UndefinedHandleValue, iargs, &rv)) { |
| 5047 |
return false; |
| 5048 |
} |
| 5049 |
|
| 5050 |
args.rval().setUndefined(); |
| 5051 |
return interruptRv; |
| 5052 |
} |
| 5053 |
|
| 5054 |
static bool SetInterruptCallback(JSContext* cx, unsigned argc, Value* vp) { |
| 5055 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5056 |
|
| 5057 |
if (args.length() != 1) { |
| 5058 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 5059 |
return false; |
| 5060 |
} |
| 5061 |
|
| 5062 |
RootedValue value(cx, args[0]); |
| 5063 |
if (!value.isObject() || !value.toObject().is<JSFunction>()) { |
| 5064 |
JS_ReportErrorASCII(cx, "Argument must be a function"); |
| 5065 |
return false; |
| 5066 |
} |
| 5067 |
GetShellContext(cx)->interruptFunc = value; |
| 5068 |
GetShellContext(cx)->haveInterruptFunc = true; |
| 5069 |
|
| 5070 |
args.rval().setUndefined(); |
| 5071 |
return true; |
| 5072 |
} |
| 5073 |
|
| 5074 |
#ifdef DEBUG |
| 5075 |
// var s0 = "A".repeat(10*1024); |
| 5076 |
// interruptRegexp(/a(bc|bd)/, s0); |
| 5077 |
// first arg is regexp |
| 5078 |
// second arg is string |
| 5079 |
static bool InterruptRegexp(JSContext* cx, unsigned argc, Value* vp) { |
| 5080 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5081 |
ShellContext* sc = GetShellContext(cx); |
| 5082 |
RootedObject callee(cx, &args.callee()); |
| 5083 |
|
| 5084 |
if (args.length() != 2) { |
| 5085 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments."); |
| 5086 |
return false; |
| 5087 |
} |
| 5088 |
if (!(args[0].isObject() && args[0].toObject().is<RegExpObject>())) { |
| 5089 |
ReportUsageErrorASCII(cx, callee, |
| 5090 |
"First argument must be a regular expression."); |
| 5091 |
return false; |
| 5092 |
} |
| 5093 |
if (!args[1].isString()) { |
| 5094 |
ReportUsageErrorASCII(cx, callee, "Second argument must be a String."); |
| 5095 |
return false; |
| 5096 |
} |
| 5097 |
// Set interrupt flags |
| 5098 |
sc->serviceInterrupt = true; |
| 5099 |
js::irregexp::IsolateSetShouldSimulateInterrupt(cx->isolate); |
| 5100 |
|
| 5101 |
RootedObject regexp(cx, &args[0].toObject()); |
| 5102 |
RootedString string(cx, args[1].toString()); |
| 5103 |
int32_t lastIndex = 0; |
| 5104 |
|
| 5105 |
return js::RegExpMatcherRaw(cx, regexp, string, lastIndex, nullptr, |
| 5106 |
args.rval()); |
| 5107 |
} |
| 5108 |
#endif |
| 5109 |
|
| 5110 |
static bool CheckRegExpSyntax(JSContext* cx, unsigned argc, Value* vp) { |
| 5111 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5112 |
RootedObject callee(cx, &args.callee()); |
| 5113 |
|
| 5114 |
if (args.length() != 1) { |
| 5115 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments."); |
| 5116 |
return false; |
| 5117 |
} |
| 5118 |
if (!args[0].isString()) { |
| 5119 |
ReportUsageErrorASCII(cx, callee, "First argument must be a string."); |
| 5120 |
return false; |
| 5121 |
} |
| 5122 |
|
| 5123 |
RootedString string(cx, args[0].toString()); |
| 5124 |
AutoStableStringChars stableChars(cx); |
| 5125 |
if (!stableChars.initTwoByte(cx, string)) { |
| 5126 |
return false; |
| 5127 |
} |
| 5128 |
|
| 5129 |
const char16_t* chars = stableChars.twoByteRange().begin().get(); |
| 5130 |
size_t length = string->length(); |
| 5131 |
|
| 5132 |
Rooted<JS::Value> error(cx); |
| 5133 |
if (!JS::CheckRegExpSyntax(cx, chars, length, JS::RegExpFlag::NoFlags, |
| 5134 |
&error)) { |
| 5135 |
return false; |
| 5136 |
} |
| 5137 |
|
| 5138 |
args.rval().set(error); |
| 5139 |
return true; |
| 5140 |
} |
| 5141 |
|
| 5142 |
static bool IsPrefAvailable(const char* pref) { |
| 5143 |
if (!fuzzingSafe) { |
| 5144 |
// All prefs in fuzzing unsafe mode are enabled. |
| 5145 |
return true; |
| 5146 |
} |
| 5147 |
#define WASM_FEATURE(NAME, LOWER_NAME, COMPILE_PRED, COMPILER_PRED, FLAG_PRED, \ |
| 5148 |
FLAG_FORCE_ON, FLAG_FUZZ_ON, PREF) \ |
| 5149 |
if constexpr (!FLAG_FUZZ_ON) { \ |
| 5150 |
if (strcmp("wasm_" #PREF, pref) == 0) { \ |
| 5151 |
return false; \ |
| 5152 |
} \ |
| 5153 |
} |
| 5154 |
JS_FOR_WASM_FEATURES(WASM_FEATURE) |
| 5155 |
#undef WASM_FEATURE |
| 5156 |
return true; |
| 5157 |
} |
| 5158 |
|
| 5159 |
template <typename T> |
| 5160 |
static bool ParsePrefValue(const char* name, const char* val, T* result) { |
| 5161 |
if constexpr (std::is_same_v<T, bool>) { |
| 5162 |
if (strcmp(val, "true") == 0) { |
| 5163 |
*result = true; |
| 5164 |
return true; |
| 5165 |
} |
| 5166 |
if (strcmp(val, "false") == 0) { |
| 5167 |
*result = false; |
| 5168 |
return true; |
| 5169 |
} |
| 5170 |
fprintf(stderr, "Invalid value for boolean pref %s: %s\n", name, val); |
| 5171 |
return false; |
| 5172 |
} else { |
| 5173 |
static_assert(std::is_same_v<T, int32_t> || std::is_same_v<T, uint32_t>); |
| 5174 |
char* end; |
| 5175 |
long v = strtol(val, &end, 10); |
| 5176 |
if (end != val + strlen(val) || static_cast<long>(static_cast<T>(v)) != v) { |
| 5177 |
fprintf(stderr, "Invalid value for integer pref %s: %s\n", name, val); |
| 5178 |
return false; |
| 5179 |
} |
| 5180 |
*result = static_cast<T>(v); |
| 5181 |
return true; |
| 5182 |
} |
| 5183 |
} |
| 5184 |
|
| 5185 |
static bool SetPrefToTrueForBool(const char* name) { |
| 5186 |
// Search for a matching pref and try to set it to a default value for the |
| 5187 |
// type. |
| 5188 |
#define CHECK_PREF(NAME, CPP_NAME, TYPE, SETTER, IS_STARTUP_PREF) \ |
| 5189 |
if (strcmp(name, NAME) == 0) { \ |
| 5190 |
if constexpr (std::is_same_v<TYPE, bool>) { \ |
| 5191 |
JS::Prefs::SETTER(true); \ |
| 5192 |
return true; \ |
| 5193 |
} else { \ |
| 5194 |
fprintf(stderr, "Pref %s must have a value specified.\n", name); \ |
| 5195 |
return false; \ |
| 5196 |
} \ |
| 5197 |
} |
| 5198 |
FOR_EACH_JS_PREF(CHECK_PREF) |
| 5199 |
#undef CHECK_PREF |
| 5200 |
|
| 5201 |
// Nothing matched. If --fuzzing-safe is used, return true after printing a |
| 5202 |
// message, to continue execution without breaking fuzzing when a pref is |
| 5203 |
// removed. |
| 5204 |
if (fuzzingSafe) { |
| 5205 |
fprintf(stderr, "Warning: Ignoring unknown pref name: %s\n", name); |
| 5206 |
return true; |
| 5207 |
} |
| 5208 |
fprintf(stderr, "Invalid pref name: %s\n", name); |
| 5209 |
return false; |
| 5210 |
} |
| 5211 |
|
| 5212 |
template <typename T> |
| 5213 |
static bool ConvertPrefValue(JSContext* cx, HandleValue val, T* result) { |
| 5214 |
if constexpr (std::is_same_v<T, bool>) { |
| 5215 |
*result = ToBoolean(val); |
| 5216 |
return true; |
| 5217 |
} else if constexpr (std::is_same_v<T, int32_t>) { |
| 5218 |
return ToInt32(cx, val, result); |
| 5219 |
} else { |
| 5220 |
static_assert(std::is_same_v<T, uint32_t>); |
| 5221 |
return ToUint32(cx, val, result); |
| 5222 |
} |
| 5223 |
} |
| 5224 |
|
| 5225 |
static bool SetPrefValue(JSContext* cx, unsigned argc, Value* vp) { |
| 5226 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5227 |
if (!args.requireAtLeast(cx, "setPrefValue", 2)) { |
| 5228 |
return false; |
| 5229 |
} |
| 5230 |
|
| 5231 |
if (!args[0].isString()) { |
| 5232 |
JS_ReportErrorASCII(cx, "expected string argument"); |
| 5233 |
return false; |
| 5234 |
} |
| 5235 |
|
| 5236 |
Rooted<JSLinearString*> name(cx, args[0].toString()->ensureLinear(cx)); |
| 5237 |
if (!name) { |
| 5238 |
return false; |
| 5239 |
} |
| 5240 |
|
| 5241 |
// Search for a matching pref and try to set it to the provided value. |
| 5242 |
#define CHECK_PREF(NAME, CPP_NAME, TYPE, SETTER, IS_STARTUP_PREF) \ |
| 5243 |
if (IsPrefAvailable(NAME) && StringEqualsAscii(name, NAME)) { \ |
| 5244 |
if (IS_STARTUP_PREF) { \ |
| 5245 |
JS_ReportErrorASCII(cx, "%s is a startup pref and can't be set", NAME); \ |
| 5246 |
return false; \ |
| 5247 |
} \ |
| 5248 |
TYPE v; \ |
| 5249 |
if (!ConvertPrefValue<TYPE>(cx, args[1], &v)) { \ |
| 5250 |
return false; \ |
| 5251 |
} \ |
| 5252 |
JS::Prefs::SETTER(v); \ |
| 5253 |
args.rval().setUndefined(); \ |
| 5254 |
return true; \ |
| 5255 |
} |
| 5256 |
FOR_EACH_JS_PREF(CHECK_PREF) |
| 5257 |
#undef CHECK_PREF |
| 5258 |
|
| 5259 |
// Fuzzing ignores missing prefs so it doesn't break if we remove a pref |
| 5260 |
if (fuzzingSafe) { |
| 5261 |
args.rval().setUndefined(); |
| 5262 |
return true; |
| 5263 |
} |
| 5264 |
JS_ReportErrorASCII(cx, "invalid pref name"); |
| 5265 |
return false; |
| 5266 |
} |
| 5267 |
|
| 5268 |
static bool SetPrefToValue(const char* name, size_t nameLen, |
| 5269 |
const char* value) { |
| 5270 |
// Search for a matching pref and try to set it to the provided value. |
| 5271 |
#define CHECK_PREF(NAME, CPP_NAME, TYPE, SETTER, IS_STARTUP_PREF) \ |
| 5272 |
if (nameLen == strlen(NAME) && memcmp(name, NAME, strlen(NAME)) == 0) { \ |
| 5273 |
TYPE v; \ |
| 5274 |
if (!ParsePrefValue<TYPE>(NAME, value, &v)) { \ |
| 5275 |
return false; \ |
| 5276 |
} \ |
| 5277 |
JS::Prefs::SETTER(v); \ |
| 5278 |
return true; \ |
| 5279 |
} |
| 5280 |
FOR_EACH_JS_PREF(CHECK_PREF) |
| 5281 |
#undef CHECK_PREF |
| 5282 |
|
| 5283 |
// Nothing matched. If --fuzzing-safe is used, return true after printing a |
| 5284 |
// message, to continue execution without breaking fuzzing when a pref is |
| 5285 |
// removed. |
| 5286 |
if (fuzzingSafe) { |
| 5287 |
fprintf(stderr, "Warning: Ignoring unknown pref name: %s\n", name); |
| 5288 |
return true; |
| 5289 |
} |
| 5290 |
fprintf(stderr, "Invalid pref name: %s\n", name); |
| 5291 |
return false; |
| 5292 |
} |
| 5293 |
|
| 5294 |
static bool SetPref(const char* pref) { |
| 5295 |
const char* assign = strchr(pref, '='); |
| 5296 |
if (!assign) { |
| 5297 |
if (IsPrefAvailable(pref) && !SetPrefToTrueForBool(pref)) { |
| 5298 |
return false; |
| 5299 |
} |
| 5300 |
return true; |
| 5301 |
} |
| 5302 |
|
| 5303 |
size_t nameLen = assign - pref; |
| 5304 |
const char* valStart = assign + 1; // Skip '='. |
| 5305 |
|
| 5306 |
if (IsPrefAvailable(pref) && !SetPrefToValue(pref, nameLen, valStart)) { |
| 5307 |
return false; |
| 5308 |
} |
| 5309 |
return true; |
| 5310 |
} |
| 5311 |
|
| 5312 |
static void ListPrefs() { |
| 5313 |
auto printPref = [](const char* name, auto defaultVal) { |
| 5314 |
if (!IsPrefAvailable(name)) { |
| 5315 |
return; |
| 5316 |
} |
| 5317 |
using T = decltype(defaultVal); |
| 5318 |
if constexpr (std::is_same_v<T, bool>) { |
| 5319 |
fprintf(stderr, "%s=%s\n", name, defaultVal ? "true" : "false"); |
| 5320 |
} else if constexpr (std::is_same_v<T, int32_t>) { |
| 5321 |
fprintf(stderr, "%s=%d\n", name, defaultVal); |
| 5322 |
} else { |
| 5323 |
static_assert(std::is_same_v<T, uint32_t>); |
| 5324 |
fprintf(stderr, "%s=%u\n", name, defaultVal); |
| 5325 |
} |
| 5326 |
}; |
| 5327 |
|
| 5328 |
#define PRINT_PREF(NAME, CPP_NAME, TYPE, SETTER, IS_STARTUP_PREF) \ |
| 5329 |
printPref(NAME, JS::Prefs::CPP_NAME()); |
| 5330 |
FOR_EACH_JS_PREF(PRINT_PREF) |
| 5331 |
#undef PRINT_PREF |
| 5332 |
} |
| 5333 |
|
| 5334 |
static bool SetJitCompilerOption(JSContext* cx, unsigned argc, Value* vp) { |
| 5335 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5336 |
RootedObject callee(cx, &args.callee()); |
| 5337 |
|
| 5338 |
if (args.length() != 2) { |
| 5339 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments."); |
| 5340 |
return false; |
| 5341 |
} |
| 5342 |
|
| 5343 |
if (!args[0].isString()) { |
| 5344 |
ReportUsageErrorASCII(cx, callee, "First argument must be a String."); |
| 5345 |
return false; |
| 5346 |
} |
| 5347 |
|
| 5348 |
if (!args[1].isInt32()) { |
| 5349 |
ReportUsageErrorASCII(cx, callee, "Second argument must be an Int32."); |
| 5350 |
return false; |
| 5351 |
} |
| 5352 |
|
| 5353 |
// Disallow setting JIT options when there are worker threads, to avoid |
| 5354 |
// races. |
| 5355 |
if (workerThreadsLock) { |
| 5356 |
ReportUsageErrorASCII( |
| 5357 |
cx, callee, "Can't set JIT options when there are worker threads."); |
| 5358 |
return false; |
| 5359 |
} |
| 5360 |
|
| 5361 |
JSLinearString* strArg = JS_EnsureLinearString(cx, args[0].toString()); |
| 5362 |
if (!strArg) { |
| 5363 |
return false; |
| 5364 |
} |
| 5365 |
|
| 5366 |
#define JIT_COMPILER_MATCH(key, string) \ |
| 5367 |
else if (JS_LinearStringEqualsLiteral(strArg, string)) opt = \ |
| 5368 |
JSJITCOMPILER_##key; |
| 5369 |
|
| 5370 |
JSJitCompilerOption opt = JSJITCOMPILER_NOT_AN_OPTION; |
| 5371 |
if (false) { |
| 5372 |
} |
| 5373 |
JIT_COMPILER_OPTIONS(JIT_COMPILER_MATCH); |
| 5374 |
#undef JIT_COMPILER_MATCH |
| 5375 |
|
| 5376 |
if (opt == JSJITCOMPILER_NOT_AN_OPTION) { |
| 5377 |
ReportUsageErrorASCII( |
| 5378 |
cx, callee, |
| 5379 |
"First argument does not name a valid option (see jsapi.h)."); |
| 5380 |
return false; |
| 5381 |
} |
| 5382 |
|
| 5383 |
int32_t number = args[1].toInt32(); |
| 5384 |
if (number < 0) { |
| 5385 |
number = -1; |
| 5386 |
} |
| 5387 |
|
| 5388 |
// Disallow enabling or disabling the Baseline Interpreter at runtime. |
| 5389 |
// Enabling is a problem because the Baseline Interpreter code is only |
| 5390 |
// present if the interpreter was enabled when the JitRuntime was created. |
| 5391 |
// To support disabling we would have to discard all JitScripts. Furthermore, |
| 5392 |
// we really want JitOptions to be immutable after startup so it's better to |
| 5393 |
// use shell flags. |
| 5394 |
if (opt == JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE && |
| 5395 |
bool(number) != jit::IsBaselineInterpreterEnabled()) { |
| 5396 |
JS_ReportErrorASCII(cx, |
| 5397 |
"Enabling or disabling the Baseline Interpreter at " |
| 5398 |
"runtime is not supported."); |
| 5399 |
return false; |
| 5400 |
} |
| 5401 |
|
| 5402 |
// Throw if disabling the JITs and there's JIT code on the stack, to avoid |
| 5403 |
// assertion failures. |
| 5404 |
if ((opt == JSJITCOMPILER_BASELINE_ENABLE || |
| 5405 |
opt == JSJITCOMPILER_ION_ENABLE) && |
| 5406 |
number == 0) { |
| 5407 |
js::jit::JitActivationIterator iter(cx); |
| 5408 |
if (!iter.done()) { |
| 5409 |
JS_ReportErrorASCII(cx, |
| 5410 |
"Can't turn off JITs with JIT code on the stack."); |
| 5411 |
return false; |
| 5412 |
} |
| 5413 |
} |
| 5414 |
|
| 5415 |
// Changing code memory protection settings at runtime is not supported. Don't |
| 5416 |
// throw if not changing the setting because some jit-tests depend on that. |
| 5417 |
if (opt == JSJITCOMPILER_WRITE_PROTECT_CODE) { |
| 5418 |
uint32_t writeProtect; |
| 5419 |
MOZ_ALWAYS_TRUE(JS_GetGlobalJitCompilerOption( |
| 5420 |
cx, JSJITCOMPILER_WRITE_PROTECT_CODE, &writeProtect)); |
| 5421 |
if (bool(number) != writeProtect) { |
| 5422 |
JS_ReportErrorASCII(cx, "Can't change code write protection at runtime"); |
| 5423 |
return false; |
| 5424 |
} |
| 5425 |
return true; |
| 5426 |
} |
| 5427 |
|
| 5428 |
// Throw if trying to disable all the Wasm compilers. The logic here is that |
| 5429 |
// if we're trying to disable a compiler that is currently enabled and that is |
| 5430 |
// the last compiler enabled then we must throw. |
| 5431 |
// |
| 5432 |
// Note that this check does not prevent an error from being thrown later. |
| 5433 |
// Actual compiler availability is dynamic and depends on other conditions, |
| 5434 |
// such as other options set and whether a debugger is present. |
| 5435 |
if ((opt == JSJITCOMPILER_WASM_JIT_BASELINE || |
| 5436 |
opt == JSJITCOMPILER_WASM_JIT_OPTIMIZING) && |
| 5437 |
number == 0) { |
| 5438 |
uint32_t baseline, optimizing; |
| 5439 |
MOZ_ALWAYS_TRUE(JS_GetGlobalJitCompilerOption( |
| 5440 |
cx, JSJITCOMPILER_WASM_JIT_BASELINE, &baseline)); |
| 5441 |
MOZ_ALWAYS_TRUE(JS_GetGlobalJitCompilerOption( |
| 5442 |
cx, JSJITCOMPILER_WASM_JIT_OPTIMIZING, &optimizing)); |
| 5443 |
if (baseline + optimizing == 1) { |
| 5444 |
if ((opt == JSJITCOMPILER_WASM_JIT_BASELINE && baseline) || |
| 5445 |
(opt == JSJITCOMPILER_WASM_JIT_OPTIMIZING && optimizing)) { |
| 5446 |
JS_ReportErrorASCII( |
| 5447 |
cx, |
| 5448 |
"Disabling all the Wasm compilers at runtime is not supported."); |
| 5449 |
return false; |
| 5450 |
} |
| 5451 |
} |
| 5452 |
} |
| 5453 |
|
| 5454 |
// JIT compiler options are process-wide, so we have to stop off-thread |
| 5455 |
// compilations for all runtimes to avoid races. |
| 5456 |
WaitForAllHelperThreads(); |
| 5457 |
|
| 5458 |
// Only release JIT code for the current runtime because there's no good |
| 5459 |
// way to discard code for other runtimes. |
| 5460 |
ReleaseAllJITCode(cx->gcContext()); |
| 5461 |
|
| 5462 |
JS_SetGlobalJitCompilerOption(cx, opt, uint32_t(number)); |
| 5463 |
|
| 5464 |
args.rval().setUndefined(); |
| 5465 |
return true; |
| 5466 |
} |
| 5467 |
|
| 5468 |
static bool EnableLastWarning(JSContext* cx, unsigned argc, Value* vp) { |
| 5469 |
ShellContext* sc = GetShellContext(cx); |
| 5470 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5471 |
|
| 5472 |
sc->lastWarningEnabled = true; |
| 5473 |
sc->lastWarning.setNull(); |
| 5474 |
|
| 5475 |
args.rval().setUndefined(); |
| 5476 |
return true; |
| 5477 |
} |
| 5478 |
|
| 5479 |
static bool DisableLastWarning(JSContext* cx, unsigned argc, Value* vp) { |
| 5480 |
ShellContext* sc = GetShellContext(cx); |
| 5481 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5482 |
|
| 5483 |
sc->lastWarningEnabled = false; |
| 5484 |
sc->lastWarning.setNull(); |
| 5485 |
|
| 5486 |
args.rval().setUndefined(); |
| 5487 |
return true; |
| 5488 |
} |
| 5489 |
|
| 5490 |
static bool GetLastWarning(JSContext* cx, unsigned argc, Value* vp) { |
| 5491 |
ShellContext* sc = GetShellContext(cx); |
| 5492 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5493 |
|
| 5494 |
if (!sc->lastWarningEnabled) { |
| 5495 |
JS_ReportErrorASCII(cx, "Call enableLastWarning first."); |
| 5496 |
return false; |
| 5497 |
} |
| 5498 |
|
| 5499 |
if (!JS_WrapValue(cx, &sc->lastWarning)) { |
| 5500 |
return false; |
| 5501 |
} |
| 5502 |
|
| 5503 |
args.rval().set(sc->lastWarning); |
| 5504 |
return true; |
| 5505 |
} |
| 5506 |
|
| 5507 |
static bool ClearLastWarning(JSContext* cx, unsigned argc, Value* vp) { |
| 5508 |
ShellContext* sc = GetShellContext(cx); |
| 5509 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5510 |
|
| 5511 |
if (!sc->lastWarningEnabled) { |
| 5512 |
JS_ReportErrorASCII(cx, "Call enableLastWarning first."); |
| 5513 |
return false; |
| 5514 |
} |
| 5515 |
|
| 5516 |
sc->lastWarning.setNull(); |
| 5517 |
|
| 5518 |
args.rval().setUndefined(); |
| 5519 |
return true; |
| 5520 |
} |
| 5521 |
|
| 5522 |
#if defined(DEBUG) || defined(JS_JITSPEW) |
| 5523 |
static bool StackDump(JSContext* cx, unsigned argc, Value* vp) { |
| 5524 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5525 |
|
| 5526 |
if (!gOutFile->isOpen()) { |
| 5527 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 5528 |
return false; |
| 5529 |
} |
| 5530 |
|
| 5531 |
bool showArgs = ToBoolean(args.get(0)); |
| 5532 |
bool showLocals = ToBoolean(args.get(1)); |
| 5533 |
bool showThisProps = ToBoolean(args.get(2)); |
| 5534 |
|
| 5535 |
JS::UniqueChars buf = |
| 5536 |
JS::FormatStackDump(cx, showArgs, showLocals, showThisProps); |
| 5537 |
if (!buf) { |
| 5538 |
fputs("Failed to format JavaScript stack for dump\n", gOutFile->fp); |
| 5539 |
JS_ClearPendingException(cx); |
| 5540 |
} else { |
| 5541 |
fputs(buf.get(), gOutFile->fp); |
| 5542 |
} |
| 5543 |
|
| 5544 |
args.rval().setUndefined(); |
| 5545 |
return true; |
| 5546 |
} |
| 5547 |
#endif |
| 5548 |
|
| 5549 |
MOZ_ASAN_IGNORE static bool StackPointerInfo(JSContext* cx, unsigned argc, |
| 5550 |
Value* vp) { |
| 5551 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5552 |
|
| 5553 |
// Copy the truncated stack pointer to the result. This value is not used |
| 5554 |
// as a pointer but as a way to measure frame-size from JS. |
| 5555 |
// The ASAN must be disabled for this function -- it may allocate `args` |
| 5556 |
// not on the stack. |
| 5557 |
args.rval().setInt32(int32_t(reinterpret_cast<size_t>(&args) & 0xfffffff)); |
| 5558 |
return true; |
| 5559 |
} |
| 5560 |
|
| 5561 |
static bool Elapsed(JSContext* cx, unsigned argc, Value* vp) { |
| 5562 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5563 |
if (args.length() == 0) { |
| 5564 |
double d = PRMJ_Now() - GetShellContext(cx)->startTime; |
| 5565 |
args.rval().setDouble(d); |
| 5566 |
return true; |
| 5567 |
} |
| 5568 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 5569 |
return false; |
| 5570 |
} |
| 5571 |
|
| 5572 |
static ShellCompartmentPrivate* EnsureShellCompartmentPrivate(JSContext* cx) { |
| 5573 |
Compartment* comp = cx->compartment(); |
| 5574 |
auto priv = |
| 5575 |
static_cast<ShellCompartmentPrivate*>(JS_GetCompartmentPrivate(comp)); |
| 5576 |
if (!priv) { |
| 5577 |
priv = cx->new_<ShellCompartmentPrivate>(); |
| 5578 |
JS_SetCompartmentPrivate(cx->compartment(), priv); |
| 5579 |
} |
| 5580 |
return priv; |
| 5581 |
} |
| 5582 |
|
| 5583 |
static bool ParseModule(JSContext* cx, unsigned argc, Value* vp) { |
| 5584 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5585 |
if (!args.requireAtLeast(cx, "parseModule", 1)) { |
| 5586 |
return false; |
| 5587 |
} |
| 5588 |
|
| 5589 |
if (!args[0].isString()) { |
| 5590 |
const char* typeName = InformalValueTypeName(args[0]); |
| 5591 |
JS_ReportErrorASCII(cx, "expected string to compile, got %s", typeName); |
| 5592 |
return false; |
| 5593 |
} |
| 5594 |
|
| 5595 |
JSString* scriptContents = args[0].toString(); |
| 5596 |
|
| 5597 |
UniqueChars filename; |
| 5598 |
CompileOptions options(cx); |
| 5599 |
bool jsonModule = false; |
| 5600 |
if (args.length() > 1) { |
| 5601 |
if (!args[1].isString()) { |
| 5602 |
const char* typeName = InformalValueTypeName(args[1]); |
| 5603 |
JS_ReportErrorASCII(cx, "expected filename string, got %s", typeName); |
| 5604 |
return false; |
| 5605 |
} |
| 5606 |
|
| 5607 |
RootedString str(cx, args[1].toString()); |
| 5608 |
filename = JS_EncodeStringToUTF8(cx, str); |
| 5609 |
if (!filename) { |
| 5610 |
return false; |
| 5611 |
} |
| 5612 |
|
| 5613 |
options.setFileAndLine(filename.get(), 1); |
| 5614 |
|
| 5615 |
// The 2nd argument is the module type string. "js" or "json" is expected. |
| 5616 |
if (args.length() == 3) { |
| 5617 |
if (!args[2].isString()) { |
| 5618 |
const char* typeName = InformalValueTypeName(args[2]); |
| 5619 |
JS_ReportErrorASCII(cx, "expected moduleType string, got %s", typeName); |
| 5620 |
return false; |
| 5621 |
} |
| 5622 |
|
| 5623 |
RootedString str(cx, args[2].toString()); |
| 5624 |
JSLinearString* linearStr = JS_EnsureLinearString(cx, str); |
| 5625 |
if (!linearStr) { |
| 5626 |
return false; |
| 5627 |
} |
| 5628 |
if (JS_LinearStringEqualsLiteral(linearStr, "json")) { |
| 5629 |
jsonModule = true; |
| 5630 |
} else if (!JS_LinearStringEqualsLiteral(linearStr, "js")) { |
| 5631 |
JS_ReportErrorASCII(cx, "moduleType string ('js' or 'json') expected"); |
| 5632 |
return false; |
| 5633 |
} |
| 5634 |
} |
| 5635 |
} else { |
| 5636 |
options.setFileAndLine("<string>", 1); |
| 5637 |
} |
| 5638 |
|
| 5639 |
AutoStableStringChars linearChars(cx); |
| 5640 |
if (!linearChars.initTwoByte(cx, scriptContents)) { |
| 5641 |
return false; |
| 5642 |
} |
| 5643 |
|
| 5644 |
JS::SourceText<char16_t> srcBuf; |
| 5645 |
if (!srcBuf.initMaybeBorrowed(cx, linearChars)) { |
| 5646 |
return false; |
| 5647 |
} |
| 5648 |
|
| 5649 |
RootedObject module(cx); |
| 5650 |
if (jsonModule) { |
| 5651 |
module = JS::CompileJsonModule(cx, options, srcBuf); |
| 5652 |
} else { |
| 5653 |
options.setModule(); |
| 5654 |
module = JS::CompileModule(cx, options, srcBuf); |
| 5655 |
} |
| 5656 |
if (!module) { |
| 5657 |
return false; |
| 5658 |
} |
| 5659 |
|
| 5660 |
Rooted<ShellModuleObjectWrapper*> wrapper( |
| 5661 |
cx, ShellModuleObjectWrapper::create(cx, module.as<ModuleObject>())); |
| 5662 |
if (!wrapper) { |
| 5663 |
return false; |
| 5664 |
} |
| 5665 |
args.rval().setObject(*wrapper); |
| 5666 |
return true; |
| 5667 |
} |
| 5668 |
|
| 5669 |
// A JSObject that holds XDRBuffer. |
| 5670 |
class XDRBufferObject : public NativeObject { |
| 5671 |
static const size_t VECTOR_SLOT = 0; |
| 5672 |
static const unsigned RESERVED_SLOTS = 1; |
| 5673 |
|
| 5674 |
public: |
| 5675 |
static const JSClassOps classOps_; |
| 5676 |
static const JSClass class_; |
| 5677 |
|
| 5678 |
[[nodiscard]] inline static XDRBufferObject* create( |
| 5679 |
JSContext* cx, JS::TranscodeBuffer&& buf); |
| 5680 |
|
| 5681 |
JS::TranscodeBuffer* data() const { |
| 5682 |
Value value = getReservedSlot(VECTOR_SLOT); |
| 5683 |
auto buf = static_cast<JS::TranscodeBuffer*>(value.toPrivate()); |
| 5684 |
MOZ_ASSERT(buf); |
| 5685 |
return buf; |
| 5686 |
} |
| 5687 |
|
| 5688 |
bool hasData() const { |
| 5689 |
// Data may not be present if we hit OOM in initialization. |
| 5690 |
return !getReservedSlot(VECTOR_SLOT).isUndefined(); |
| 5691 |
} |
| 5692 |
|
| 5693 |
static void finalize(JS::GCContext* gcx, JSObject* obj); |
| 5694 |
}; |
| 5695 |
|
| 5696 |
/*static */ const JSClassOps XDRBufferObject::classOps_ = { |
| 5697 |
nullptr, // addProperty |
| 5698 |
nullptr, // delProperty |
| 5699 |
nullptr, // enumerate |
| 5700 |
nullptr, // newEnumerate |
| 5701 |
nullptr, // resolve |
| 5702 |
nullptr, // mayResolve |
| 5703 |
XDRBufferObject::finalize, // finalize |
| 5704 |
nullptr, // call |
| 5705 |
nullptr, // construct |
| 5706 |
nullptr, // trace |
| 5707 |
}; |
| 5708 |
|
| 5709 |
/*static */ const JSClass XDRBufferObject::class_ = { |
| 5710 |
"XDRBufferObject", |
| 5711 |
JSCLASS_HAS_RESERVED_SLOTS(XDRBufferObject::RESERVED_SLOTS) | |
| 5712 |
JSCLASS_BACKGROUND_FINALIZE, |
| 5713 |
&XDRBufferObject::classOps_, |
| 5714 |
}; |
| 5715 |
|
| 5716 |
XDRBufferObject* XDRBufferObject::create(JSContext* cx, |
| 5717 |
JS::TranscodeBuffer&& buf) { |
| 5718 |
XDRBufferObject* bufObj = |
| 5719 |
NewObjectWithGivenProto<XDRBufferObject>(cx, nullptr); |
| 5720 |
if (!bufObj) { |
| 5721 |
return nullptr; |
| 5722 |
} |
| 5723 |
|
| 5724 |
auto heapBuf = cx->make_unique<JS::TranscodeBuffer>(std::move(buf)); |
| 5725 |
if (!heapBuf) { |
| 5726 |
return nullptr; |
| 5727 |
} |
| 5728 |
|
| 5729 |
size_t len = heapBuf->length(); |
| 5730 |
InitReservedSlot(bufObj, VECTOR_SLOT, heapBuf.release(), len, |
| 5731 |
MemoryUse::XDRBufferElements); |
| 5732 |
|
| 5733 |
return bufObj; |
| 5734 |
} |
| 5735 |
|
| 5736 |
void XDRBufferObject::finalize(JS::GCContext* gcx, JSObject* obj) { |
| 5737 |
XDRBufferObject* buf = &obj->as<XDRBufferObject>(); |
| 5738 |
if (buf->hasData()) { |
| 5739 |
gcx->delete_(buf, buf->data(), buf->data()->length(), |
| 5740 |
MemoryUse::XDRBufferElements); |
| 5741 |
} |
| 5742 |
} |
| 5743 |
|
| 5744 |
static bool InstantiateModuleStencil(JSContext* cx, uint32_t argc, Value* vp) { |
| 5745 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5746 |
|
| 5747 |
if (!args.requireAtLeast(cx, "instantiateModuleStencil", 1)) { |
| 5748 |
return false; |
| 5749 |
} |
| 5750 |
|
| 5751 |
/* Prepare the input byte array. */ |
| 5752 |
if (!args[0].isObject()) { |
| 5753 |
JS_ReportErrorASCII(cx, |
| 5754 |
"instantiateModuleStencil: Stencil object expected"); |
| 5755 |
return false; |
| 5756 |
} |
| 5757 |
Rooted<js::StencilObject*> stencilObj( |
| 5758 |
cx, args[0].toObject().maybeUnwrapIf<js::StencilObject>()); |
| 5759 |
if (!stencilObj) { |
| 5760 |
JS_ReportErrorASCII(cx, |
| 5761 |
"instantiateModuleStencil: Stencil object expected"); |
| 5762 |
return false; |
| 5763 |
} |
| 5764 |
|
| 5765 |
if (!stencilObj->stencil()->getInitial()->isModule()) { |
| 5766 |
JS_ReportErrorASCII(cx, |
| 5767 |
"instantiateModuleStencil: Module stencil expected"); |
| 5768 |
return false; |
| 5769 |
} |
| 5770 |
|
| 5771 |
CompileOptions options(cx); |
| 5772 |
UniqueChars fileNameBytes; |
| 5773 |
if (args.length() == 2) { |
| 5774 |
if (!args[1].isObject()) { |
| 5775 |
JS_ReportErrorASCII( |
| 5776 |
cx, "instantiateModuleStencil: The 2nd argument must be an object"); |
| 5777 |
return false; |
| 5778 |
} |
| 5779 |
|
| 5780 |
RootedObject opts(cx, &args[1].toObject()); |
| 5781 |
if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) { |
| 5782 |
return false; |
| 5783 |
} |
| 5784 |
} |
| 5785 |
|
| 5786 |
if (!js::ValidateLazinessOfStencilAndGlobal(cx, stencilObj->stencil())) { |
| 5787 |
return false; |
| 5788 |
} |
| 5789 |
|
| 5790 |
JS::InstantiateOptions instantiateOptions(options); |
| 5791 |
Rooted<JSObject*> modObject( |
| 5792 |
cx, JS::InstantiateModuleStencil(cx, instantiateOptions, |
| 5793 |
stencilObj->stencil(), nullptr)); |
| 5794 |
if (!modObject) { |
| 5795 |
return false; |
| 5796 |
} |
| 5797 |
|
| 5798 |
Rooted<ModuleObject*> module(cx, &modObject->as<ModuleObject>()); |
| 5799 |
Rooted<ShellModuleObjectWrapper*> wrapper( |
| 5800 |
cx, ShellModuleObjectWrapper::create(cx, module)); |
| 5801 |
if (!wrapper) { |
| 5802 |
return false; |
| 5803 |
} |
| 5804 |
args.rval().setObject(*wrapper); |
| 5805 |
return true; |
| 5806 |
} |
| 5807 |
|
| 5808 |
static bool InstantiateModuleStencilXDR(JSContext* cx, uint32_t argc, |
| 5809 |
Value* vp) { |
| 5810 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5811 |
|
| 5812 |
if (!args.requireAtLeast(cx, "instantiateModuleStencilXDR", 1)) { |
| 5813 |
return false; |
| 5814 |
} |
| 5815 |
|
| 5816 |
/* Prepare the input byte array. */ |
| 5817 |
if (!args[0].isObject()) { |
| 5818 |
JS_ReportErrorASCII( |
| 5819 |
cx, "instantiateModuleStencilXDR: Stencil XDR object expected"); |
| 5820 |
return false; |
| 5821 |
} |
| 5822 |
Rooted<StencilXDRBufferObject*> xdrObj( |
| 5823 |
cx, args[0].toObject().maybeUnwrapIf<StencilXDRBufferObject>()); |
| 5824 |
if (!xdrObj) { |
| 5825 |
JS_ReportErrorASCII( |
| 5826 |
cx, "instantiateModuleStencilXDR: Stencil XDR object expected"); |
| 5827 |
return false; |
| 5828 |
} |
| 5829 |
MOZ_ASSERT(xdrObj->hasBuffer()); |
| 5830 |
|
| 5831 |
CompileOptions options(cx); |
| 5832 |
UniqueChars fileNameBytes; |
| 5833 |
if (args.length() == 2) { |
| 5834 |
if (!args[1].isObject()) { |
| 5835 |
JS_ReportErrorASCII( |
| 5836 |
cx, |
| 5837 |
"instantiateModuleStencilXDR: The 2nd argument must be an object"); |
| 5838 |
return false; |
| 5839 |
} |
| 5840 |
|
| 5841 |
RootedObject opts(cx, &args[1].toObject()); |
| 5842 |
if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) { |
| 5843 |
return false; |
| 5844 |
} |
| 5845 |
} |
| 5846 |
|
| 5847 |
JS::TranscodeRange xdrRange(xdrObj->buffer(), xdrObj->bufferLength()); |
| 5848 |
JS::DecodeOptions decodeOptions(options); |
| 5849 |
RefPtr<JS::Stencil> stencil; |
| 5850 |
auto result = |
| 5851 |
JS::DecodeStencil(cx, decodeOptions, xdrRange, getter_AddRefs(stencil)); |
| 5852 |
if (result == JS::TranscodeResult::Throw) { |
| 5853 |
return false; |
| 5854 |
} |
| 5855 |
if (JS::IsTranscodeFailureResult(result)) { |
| 5856 |
JS_ReportErrorASCII(cx, "Decoding failure"); |
| 5857 |
return false; |
| 5858 |
} |
| 5859 |
|
| 5860 |
if (!stencil->getInitial()->isModule()) { |
| 5861 |
JS_ReportErrorASCII(cx, |
| 5862 |
"instantiateModuleStencilXDR: Module stencil expected"); |
| 5863 |
return false; |
| 5864 |
} |
| 5865 |
|
| 5866 |
if (!js::ValidateLazinessOfStencilAndGlobal(cx, stencil.get())) { |
| 5867 |
return false; |
| 5868 |
} |
| 5869 |
|
| 5870 |
JS::InstantiateOptions instantiateOptions(options); |
| 5871 |
Rooted<JSObject*> modObject( |
| 5872 |
cx, |
| 5873 |
JS::InstantiateModuleStencil(cx, instantiateOptions, stencil, nullptr)); |
| 5874 |
if (!modObject) { |
| 5875 |
return false; |
| 5876 |
} |
| 5877 |
|
| 5878 |
Rooted<ModuleObject*> module(cx, &modObject->as<ModuleObject>()); |
| 5879 |
Rooted<ShellModuleObjectWrapper*> wrapper( |
| 5880 |
cx, ShellModuleObjectWrapper::create(cx, module)); |
| 5881 |
if (!wrapper) { |
| 5882 |
return false; |
| 5883 |
} |
| 5884 |
args.rval().setObject(*wrapper); |
| 5885 |
return true; |
| 5886 |
} |
| 5887 |
|
| 5888 |
static bool RegisterModule(JSContext* cx, unsigned argc, Value* vp) { |
| 5889 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5890 |
if (!args.requireAtLeast(cx, "registerModule", 2)) { |
| 5891 |
return false; |
| 5892 |
} |
| 5893 |
|
| 5894 |
if (!args[0].isString()) { |
| 5895 |
const char* typeName = InformalValueTypeName(args[0]); |
| 5896 |
JS_ReportErrorASCII(cx, "Expected string, got %s", typeName); |
| 5897 |
return false; |
| 5898 |
} |
| 5899 |
|
| 5900 |
if (!args[1].isObject() || |
| 5901 |
!args[1].toObject().is<ShellModuleObjectWrapper>()) { |
| 5902 |
const char* typeName = InformalValueTypeName(args[1]); |
| 5903 |
JS_ReportErrorASCII(cx, "Expected module, got %s", typeName); |
| 5904 |
return false; |
| 5905 |
} |
| 5906 |
|
| 5907 |
ShellContext* sc = GetShellContext(cx); |
| 5908 |
Rooted<ModuleObject*> module( |
| 5909 |
cx, args[1].toObject().as<ShellModuleObjectWrapper>().get()); |
| 5910 |
if (module->realm() != cx->realm()) { |
| 5911 |
JS_ReportErrorASCII(cx, "Module is in a different realm"); |
| 5912 |
return false; |
| 5913 |
} |
| 5914 |
|
| 5915 |
Rooted<JSAtom*> specifier(cx, AtomizeString(cx, args[0].toString())); |
| 5916 |
if (!specifier) { |
| 5917 |
return false; |
| 5918 |
} |
| 5919 |
|
| 5920 |
JS::ModuleType moduleType = JS::ModuleType::JavaScript; |
| 5921 |
if (module->hasSyntheticModuleFields()) { |
| 5922 |
moduleType = JS::ModuleType::JSON; |
| 5923 |
} |
| 5924 |
|
| 5925 |
RootedObject moduleRequest( |
| 5926 |
cx, ModuleRequestObject::create(cx, specifier, moduleType)); |
| 5927 |
if (!moduleRequest) { |
| 5928 |
return false; |
| 5929 |
} |
| 5930 |
|
| 5931 |
if (!sc->moduleLoader->registerTestModule(cx, moduleRequest, module)) { |
| 5932 |
return false; |
| 5933 |
} |
| 5934 |
|
| 5935 |
Rooted<ShellModuleObjectWrapper*> wrapper( |
| 5936 |
cx, ShellModuleObjectWrapper::create(cx, module)); |
| 5937 |
if (!wrapper) { |
| 5938 |
return false; |
| 5939 |
} |
| 5940 |
args.rval().setObject(*wrapper); |
| 5941 |
return true; |
| 5942 |
} |
| 5943 |
|
| 5944 |
static bool ClearModules(JSContext* cx, unsigned argc, Value* vp) { |
| 5945 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5946 |
ShellContext* sc = GetShellContext(cx); |
| 5947 |
sc->moduleLoader->clearModules(cx); |
| 5948 |
args.rval().setUndefined(); |
| 5949 |
return true; |
| 5950 |
} |
| 5951 |
|
| 5952 |
static bool ModuleLink(JSContext* cx, unsigned argc, Value* vp) { |
| 5953 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5954 |
|
| 5955 |
if (args.length() != 1 || !args[0].isObject()) { |
| 5956 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARGS, |
| 5957 |
"moduleLink"); |
| 5958 |
return false; |
| 5959 |
} |
| 5960 |
|
| 5961 |
RootedObject object(cx, UncheckedUnwrap(&args[0].toObject())); |
| 5962 |
if (!object->is<ShellModuleObjectWrapper>()) { |
| 5963 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARGS, |
| 5964 |
"moduleLink"); |
| 5965 |
return false; |
| 5966 |
} |
| 5967 |
|
| 5968 |
AutoRealm ar(cx, object); |
| 5969 |
|
| 5970 |
Rooted<ModuleObject*> module(cx, |
| 5971 |
object->as<ShellModuleObjectWrapper>().get()); |
| 5972 |
if (!JS::ModuleLink(cx, module)) { |
| 5973 |
return false; |
| 5974 |
} |
| 5975 |
|
| 5976 |
args.rval().setUndefined(); |
| 5977 |
return true; |
| 5978 |
} |
| 5979 |
|
| 5980 |
static bool ModuleEvaluate(JSContext* cx, unsigned argc, Value* vp) { |
| 5981 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 5982 |
|
| 5983 |
if (args.length() != 1 || !args[0].isObject()) { |
| 5984 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARGS, |
| 5985 |
"moduleEvaluate"); |
| 5986 |
return false; |
| 5987 |
} |
| 5988 |
|
| 5989 |
RootedObject object(cx, UncheckedUnwrap(&args[0].toObject())); |
| 5990 |
if (!object->is<ShellModuleObjectWrapper>()) { |
| 5991 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_INVALID_ARGS, |
| 5992 |
"moduleEvaluate"); |
| 5993 |
return false; |
| 5994 |
} |
| 5995 |
|
| 5996 |
{ |
| 5997 |
AutoRealm ar(cx, object); |
| 5998 |
|
| 5999 |
Rooted<ModuleObject*> module(cx, |
| 6000 |
object->as<ShellModuleObjectWrapper>().get()); |
| 6001 |
if (!JS::ModuleEvaluate(cx, module, args.rval())) { |
| 6002 |
return false; |
| 6003 |
} |
| 6004 |
} |
| 6005 |
|
| 6006 |
return JS_WrapValue(cx, args.rval()); |
| 6007 |
} |
| 6008 |
|
| 6009 |
static ModuleEnvironmentObject* GetModuleInitialEnvironment( |
| 6010 |
JSContext* cx, Handle<ModuleObject*> module) { |
| 6011 |
// Use the initial environment so that tests can check bindings exists |
| 6012 |
// before they have been instantiated. |
| 6013 |
Rooted<ModuleEnvironmentObject*> env(cx, &module->initialEnvironment()); |
| 6014 |
MOZ_ASSERT(env); |
| 6015 |
return env; |
| 6016 |
} |
| 6017 |
|
| 6018 |
static bool GetModuleEnvironmentNames(JSContext* cx, unsigned argc, Value* vp) { |
| 6019 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6020 |
if (args.length() != 1) { |
| 6021 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 6022 |
return false; |
| 6023 |
} |
| 6024 |
|
| 6025 |
if (!args[0].isObject() || |
| 6026 |
!args[0].toObject().is<ShellModuleObjectWrapper>()) { |
| 6027 |
JS_ReportErrorASCII(cx, |
| 6028 |
"First argument should be a ShellModuleObjectWrapper"); |
| 6029 |
return false; |
| 6030 |
} |
| 6031 |
|
| 6032 |
Rooted<ModuleObject*> module( |
| 6033 |
cx, args[0].toObject().as<ShellModuleObjectWrapper>().get()); |
| 6034 |
if (module->hasSyntheticModuleFields()) { |
| 6035 |
JS_ReportErrorASCII(cx, |
| 6036 |
"Operation is not supported on JSON module objects."); |
| 6037 |
return false; |
| 6038 |
} |
| 6039 |
|
| 6040 |
if (module->hadEvaluationError()) { |
| 6041 |
JS_ReportErrorASCII(cx, "Module environment unavailable"); |
| 6042 |
return false; |
| 6043 |
} |
| 6044 |
|
| 6045 |
Rooted<ModuleEnvironmentObject*> env(cx, |
| 6046 |
GetModuleInitialEnvironment(cx, module)); |
| 6047 |
Rooted<IdVector> ids(cx, IdVector(cx)); |
| 6048 |
if (!JS_Enumerate(cx, env, &ids)) { |
| 6049 |
return false; |
| 6050 |
} |
| 6051 |
|
| 6052 |
// The "*namespace*" binding is a detail of current implementation so hide |
| 6053 |
// it to give stable results in tests. |
| 6054 |
ids.eraseIfEqual(NameToId(cx->names().star_namespace_star_)); |
| 6055 |
|
| 6056 |
uint32_t length = ids.length(); |
| 6057 |
Rooted<ArrayObject*> array(cx, NewDenseFullyAllocatedArray(cx, length)); |
| 6058 |
if (!array) { |
| 6059 |
return false; |
| 6060 |
} |
| 6061 |
|
| 6062 |
array->setDenseInitializedLength(length); |
| 6063 |
for (uint32_t i = 0; i < length; i++) { |
| 6064 |
array->initDenseElement(i, StringValue(ids[i].toString())); |
| 6065 |
} |
| 6066 |
|
| 6067 |
args.rval().setObject(*array); |
| 6068 |
return true; |
| 6069 |
} |
| 6070 |
|
| 6071 |
static bool GetModuleEnvironmentValue(JSContext* cx, unsigned argc, Value* vp) { |
| 6072 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6073 |
if (args.length() != 2) { |
| 6074 |
JS_ReportErrorASCII(cx, "Wrong number of arguments"); |
| 6075 |
return false; |
| 6076 |
} |
| 6077 |
|
| 6078 |
if (!args[0].isObject() || |
| 6079 |
!args[0].toObject().is<ShellModuleObjectWrapper>()) { |
| 6080 |
JS_ReportErrorASCII(cx, |
| 6081 |
"First argument should be a ShellModuleObjectWrapper"); |
| 6082 |
return false; |
| 6083 |
} |
| 6084 |
|
| 6085 |
if (!args[1].isString()) { |
| 6086 |
JS_ReportErrorASCII(cx, "Second argument should be a string"); |
| 6087 |
return false; |
| 6088 |
} |
| 6089 |
|
| 6090 |
Rooted<ModuleObject*> module( |
| 6091 |
cx, args[0].toObject().as<ShellModuleObjectWrapper>().get()); |
| 6092 |
if (module->hasSyntheticModuleFields()) { |
| 6093 |
JS_ReportErrorASCII(cx, |
| 6094 |
"Operation is not supported on JSON module objects."); |
| 6095 |
return false; |
| 6096 |
} |
| 6097 |
|
| 6098 |
if (module->hadEvaluationError()) { |
| 6099 |
JS_ReportErrorASCII(cx, "Module environment unavailable"); |
| 6100 |
return false; |
| 6101 |
} |
| 6102 |
|
| 6103 |
Rooted<ModuleEnvironmentObject*> env(cx, |
| 6104 |
GetModuleInitialEnvironment(cx, module)); |
| 6105 |
RootedString name(cx, args[1].toString()); |
| 6106 |
RootedId id(cx); |
| 6107 |
if (!JS_StringToId(cx, name, &id)) { |
| 6108 |
return false; |
| 6109 |
} |
| 6110 |
|
| 6111 |
if (!GetProperty(cx, env, env, id, args.rval())) { |
| 6112 |
return false; |
| 6113 |
} |
| 6114 |
|
| 6115 |
if (args.rval().isMagic(JS_UNINITIALIZED_LEXICAL)) { |
| 6116 |
ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id); |
| 6117 |
return false; |
| 6118 |
} |
| 6119 |
|
| 6120 |
return true; |
| 6121 |
} |
| 6122 |
|
| 6123 |
enum class DumpType { |
| 6124 |
ParseNode, |
| 6125 |
Stencil, |
| 6126 |
}; |
| 6127 |
|
| 6128 |
template <typename Unit> |
| 6129 |
static bool DumpAST(JSContext* cx, const JS::ReadOnlyCompileOptions& options, |
| 6130 |
const Unit* units, size_t length, |
| 6131 |
js::frontend::CompilationState& compilationState, |
| 6132 |
js::frontend::ParseGoal goal) { |
| 6133 |
using namespace js::frontend; |
| 6134 |
|
| 6135 |
AutoReportFrontendContext fc(cx); |
| 6136 |
Parser<FullParseHandler, Unit> parser(&fc, options, units, length, |
| 6137 |
compilationState, |
| 6138 |
/* syntaxParser = */ nullptr); |
| 6139 |
if (!parser.checkOptions()) { |
| 6140 |
return false; |
| 6141 |
} |
| 6142 |
|
| 6143 |
// Emplace the top-level stencil. |
| 6144 |
MOZ_ASSERT(compilationState.scriptData.length() == |
| 6145 |
CompilationStencil::TopLevelIndex); |
| 6146 |
if (!compilationState.appendScriptStencilAndData(&fc)) { |
| 6147 |
return false; |
| 6148 |
} |
| 6149 |
|
| 6150 |
js::frontend::ParseNode* pn; |
| 6151 |
if (goal == frontend::ParseGoal::Script) { |
| 6152 |
pn = parser.parse().unwrapOr(nullptr); |
| 6153 |
} else { |
| 6154 |
ModuleBuilder builder(&fc, &parser); |
| 6155 |
|
| 6156 |
SourceExtent extent = SourceExtent::makeGlobalExtent(length); |
| 6157 |
ModuleSharedContext modulesc(&fc, options, builder, extent); |
| 6158 |
pn = parser.moduleBody(&modulesc).unwrapOr(nullptr); |
| 6159 |
} |
| 6160 |
|
| 6161 |
if (!pn) { |
| 6162 |
return false; |
| 6163 |
} |
| 6164 |
|
| 6165 |
#if defined(DEBUG) |
| 6166 |
js::Fprinter out(stderr); |
| 6167 |
DumpParseTree(&parser, pn, out); |
| 6168 |
#endif |
| 6169 |
|
| 6170 |
return true; |
| 6171 |
} |
| 6172 |
|
| 6173 |
template <typename Unit> |
| 6174 |
[[nodiscard]] static bool DumpStencil(JSContext* cx, |
| 6175 |
const JS::ReadOnlyCompileOptions& options, |
| 6176 |
const Unit* units, size_t length, |
| 6177 |
js::frontend::ParseGoal goal) { |
| 6178 |
JS::SourceText<Unit> srcBuf; |
| 6179 |
if (!srcBuf.init(cx, units, length, JS::SourceOwnership::Borrowed)) { |
| 6180 |
return false; |
| 6181 |
} |
| 6182 |
|
| 6183 |
RefPtr<JS::Stencil> stencil; |
| 6184 |
if (goal == frontend::ParseGoal::Script) { |
| 6185 |
stencil = JS::CompileGlobalScriptToStencil(cx, options, srcBuf); |
| 6186 |
} else { |
| 6187 |
stencil = JS::CompileModuleScriptToStencil(cx, options, srcBuf); |
| 6188 |
} |
| 6189 |
|
| 6190 |
if (!stencil) { |
| 6191 |
return false; |
| 6192 |
} |
| 6193 |
|
| 6194 |
#if defined(DEBUG) || defined(JS_JITSPEW) |
| 6195 |
stencil->dump(); |
| 6196 |
#endif |
| 6197 |
|
| 6198 |
return true; |
| 6199 |
} |
| 6200 |
|
| 6201 |
static bool FrontendTest(JSContext* cx, unsigned argc, Value* vp, |
| 6202 |
const char* funcName, DumpType dumpType) { |
| 6203 |
using namespace js::frontend; |
| 6204 |
|
| 6205 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6206 |
|
| 6207 |
if (!args.requireAtLeast(cx, funcName, 1)) { |
| 6208 |
return false; |
| 6209 |
} |
| 6210 |
if (!args[0].isString()) { |
| 6211 |
const char* typeName = InformalValueTypeName(args[0]); |
| 6212 |
JS_ReportErrorASCII(cx, "expected string to parse, got %s", typeName); |
| 6213 |
return false; |
| 6214 |
} |
| 6215 |
|
| 6216 |
frontend::ParseGoal goal = frontend::ParseGoal::Script; |
| 6217 |
|
| 6218 |
CompileOptions options(cx); |
| 6219 |
options.setIntroductionType("js shell parse") |
| 6220 |
.setFileAndLine("<string>", 1) |
| 6221 |
.setIsRunOnce(true) |
| 6222 |
.setNoScriptRval(true); |
| 6223 |
|
| 6224 |
if (args.length() >= 2) { |
| 6225 |
if (!args[1].isObject()) { |
| 6226 |
JS_ReportErrorASCII(cx, "The 2nd argument must be an object"); |
| 6227 |
return false; |
| 6228 |
} |
| 6229 |
|
| 6230 |
RootedObject objOptions(cx, &args[1].toObject()); |
| 6231 |
|
| 6232 |
RootedValue optionModule(cx); |
| 6233 |
if (!JS_GetProperty(cx, objOptions, "module", &optionModule)) { |
| 6234 |
return false; |
| 6235 |
} |
| 6236 |
|
| 6237 |
if (optionModule.isBoolean()) { |
| 6238 |
if (optionModule.toBoolean()) { |
| 6239 |
goal = frontend::ParseGoal::Module; |
| 6240 |
} |
| 6241 |
} else if (!optionModule.isUndefined()) { |
| 6242 |
const char* typeName = InformalValueTypeName(optionModule); |
| 6243 |
JS_ReportErrorASCII(cx, "option `module` should be a boolean, got %s", |
| 6244 |
typeName); |
| 6245 |
return false; |
| 6246 |
} |
| 6247 |
if (!js::ParseCompileOptions(cx, options, objOptions, nullptr)) { |
| 6248 |
return false; |
| 6249 |
} |
| 6250 |
|
| 6251 |
if (goal == frontend::ParseGoal::Module && options.lineno == 0) { |
| 6252 |
JS_ReportErrorASCII(cx, "Module cannot be compiled with lineNumber == 0"); |
| 6253 |
return false; |
| 6254 |
} |
| 6255 |
} |
| 6256 |
|
| 6257 |
JSString* scriptContents = args[0].toString(); |
| 6258 |
Rooted<JSLinearString*> linearString(cx, scriptContents->ensureLinear(cx)); |
| 6259 |
if (!linearString) { |
| 6260 |
return false; |
| 6261 |
} |
| 6262 |
|
| 6263 |
bool isAscii = false; |
| 6264 |
if (linearString->hasLatin1Chars()) { |
| 6265 |
JS::AutoCheckCannotGC nogc; |
| 6266 |
isAscii = JS::StringIsASCII(mozilla::Span( |
| 6267 |
reinterpret_cast<const char*>(linearString->latin1Chars(nogc)), |
| 6268 |
linearString->length())); |
| 6269 |
} |
| 6270 |
|
| 6271 |
AutoStableStringChars stableChars(cx); |
| 6272 |
if (isAscii) { |
| 6273 |
if (!stableChars.init(cx, scriptContents)) { |
| 6274 |
return false; |
| 6275 |
} |
| 6276 |
MOZ_ASSERT(stableChars.isLatin1()); |
| 6277 |
} else { |
| 6278 |
if (!stableChars.initTwoByte(cx, scriptContents)) { |
| 6279 |
return false; |
| 6280 |
} |
| 6281 |
} |
| 6282 |
|
| 6283 |
size_t length = scriptContents->length(); |
| 6284 |
|
| 6285 |
if (goal == frontend::ParseGoal::Module) { |
| 6286 |
// See frontend::CompileModule. |
| 6287 |
options.setForceStrictMode(); |
| 6288 |
options.allowHTMLComments = false; |
| 6289 |
} |
| 6290 |
|
| 6291 |
if (dumpType == DumpType::Stencil) { |
| 6292 |
if (isAscii) { |
| 6293 |
const Latin1Char* latin1 = stableChars.latin1Range().begin().get(); |
| 6294 |
auto utf8 = reinterpret_cast<const mozilla::Utf8Unit*>(latin1); |
| 6295 |
if (!DumpStencil<mozilla::Utf8Unit>(cx, options, utf8, length, goal)) { |
| 6296 |
return false; |
| 6297 |
} |
| 6298 |
} else { |
| 6299 |
MOZ_ASSERT(stableChars.isTwoByte()); |
| 6300 |
const char16_t* chars = stableChars.twoByteRange().begin().get(); |
| 6301 |
if (!DumpStencil<char16_t>(cx, options, chars, length, goal)) { |
| 6302 |
return false; |
| 6303 |
} |
| 6304 |
} |
| 6305 |
|
| 6306 |
args.rval().setUndefined(); |
| 6307 |
return true; |
| 6308 |
} |
| 6309 |
|
| 6310 |
AutoReportFrontendContext fc(cx); |
| 6311 |
Rooted<frontend::CompilationInput> input(cx, |
| 6312 |
frontend::CompilationInput(options)); |
| 6313 |
if (goal == frontend::ParseGoal::Script) { |
| 6314 |
if (!input.get().initForGlobal(&fc)) { |
| 6315 |
return false; |
| 6316 |
} |
| 6317 |
} else { |
| 6318 |
if (!input.get().initForModule(&fc)) { |
| 6319 |
return false; |
| 6320 |
} |
| 6321 |
} |
| 6322 |
|
| 6323 |
LifoAllocScope allocScope(&cx->tempLifoAlloc()); |
| 6324 |
frontend::NoScopeBindingCache scopeCache; |
| 6325 |
frontend::CompilationState compilationState(&fc, allocScope, input.get()); |
| 6326 |
if (!compilationState.init(&fc, &scopeCache)) { |
| 6327 |
return false; |
| 6328 |
} |
| 6329 |
|
| 6330 |
if (isAscii) { |
| 6331 |
const Latin1Char* latin1 = stableChars.latin1Range().begin().get(); |
| 6332 |
auto utf8 = reinterpret_cast<const mozilla::Utf8Unit*>(latin1); |
| 6333 |
if (!DumpAST<mozilla::Utf8Unit>(cx, options, utf8, length, compilationState, |
| 6334 |
goal)) { |
| 6335 |
return false; |
| 6336 |
} |
| 6337 |
} else { |
| 6338 |
MOZ_ASSERT(stableChars.isTwoByte()); |
| 6339 |
const char16_t* chars = stableChars.twoByteRange().begin().get(); |
| 6340 |
if (!DumpAST<char16_t>(cx, options, chars, length, compilationState, |
| 6341 |
goal)) { |
| 6342 |
return false; |
| 6343 |
} |
| 6344 |
} |
| 6345 |
args.rval().setUndefined(); |
| 6346 |
return true; |
| 6347 |
} |
| 6348 |
|
| 6349 |
static bool DumpStencil(JSContext* cx, unsigned argc, Value* vp) { |
| 6350 |
return FrontendTest(cx, argc, vp, "dumpStencil", DumpType::Stencil); |
| 6351 |
} |
| 6352 |
|
| 6353 |
static bool Parse(JSContext* cx, unsigned argc, Value* vp) { |
| 6354 |
// Parse returns local scope information with variables ordered |
| 6355 |
// differently, depending on the underlying JIT implementation. |
| 6356 |
if (js::SupportDifferentialTesting()) { |
| 6357 |
JS_ReportErrorASCII(cx, |
| 6358 |
"Function not available in differential testing mode."); |
| 6359 |
return false; |
| 6360 |
} |
| 6361 |
|
| 6362 |
return FrontendTest(cx, argc, vp, "parse", DumpType::ParseNode); |
| 6363 |
} |
| 6364 |
|
| 6365 |
static bool SyntaxParse(JSContext* cx, unsigned argc, Value* vp) { |
| 6366 |
using namespace js::frontend; |
| 6367 |
|
| 6368 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6369 |
|
| 6370 |
if (!args.requireAtLeast(cx, "syntaxParse", 1)) { |
| 6371 |
return false; |
| 6372 |
} |
| 6373 |
if (!args[0].isString()) { |
| 6374 |
const char* typeName = InformalValueTypeName(args[0]); |
| 6375 |
JS_ReportErrorASCII(cx, "expected string to parse, got %s", typeName); |
| 6376 |
return false; |
| 6377 |
} |
| 6378 |
|
| 6379 |
JSString* scriptContents = args[0].toString(); |
| 6380 |
|
| 6381 |
CompileOptions options(cx); |
| 6382 |
options.setIntroductionType("js shell syntaxParse") |
| 6383 |
.setFileAndLine("<string>", 1); |
| 6384 |
|
| 6385 |
AutoStableStringChars stableChars(cx); |
| 6386 |
if (!stableChars.initTwoByte(cx, scriptContents)) { |
| 6387 |
return false; |
| 6388 |
} |
| 6389 |
|
| 6390 |
const char16_t* chars = stableChars.twoByteRange().begin().get(); |
| 6391 |
size_t length = scriptContents->length(); |
| 6392 |
|
| 6393 |
AutoReportFrontendContext fc(cx); |
| 6394 |
Rooted<frontend::CompilationInput> input(cx, |
| 6395 |
frontend::CompilationInput(options)); |
| 6396 |
if (!input.get().initForGlobal(&fc)) { |
| 6397 |
return false; |
| 6398 |
} |
| 6399 |
|
| 6400 |
LifoAllocScope allocScope(&cx->tempLifoAlloc()); |
| 6401 |
frontend::NoScopeBindingCache scopeCache; |
| 6402 |
frontend::CompilationState compilationState(&fc, allocScope, input.get()); |
| 6403 |
if (!compilationState.init(&fc, &scopeCache)) { |
| 6404 |
return false; |
| 6405 |
} |
| 6406 |
|
| 6407 |
Parser<frontend::SyntaxParseHandler, char16_t> parser( |
| 6408 |
&fc, options, chars, length, compilationState, |
| 6409 |
/* syntaxParser = */ nullptr); |
| 6410 |
if (!parser.checkOptions()) { |
| 6411 |
return false; |
| 6412 |
} |
| 6413 |
|
| 6414 |
bool succeeded = parser.parse().isOk(); |
| 6415 |
if (fc.hadErrors()) { |
| 6416 |
return false; |
| 6417 |
} |
| 6418 |
|
| 6419 |
if (!succeeded && !parser.hadAbortedSyntaxParse()) { |
| 6420 |
// If no exception is posted, either there was an OOM or a language |
| 6421 |
// feature unhandled by the syntax parser was encountered. |
| 6422 |
MOZ_ASSERT(fc.hadOutOfMemory()); |
| 6423 |
return false; |
| 6424 |
} |
| 6425 |
|
| 6426 |
args.rval().setBoolean(succeeded); |
| 6427 |
return true; |
| 6428 |
} |
| 6429 |
|
| 6430 |
static bool OffThreadCompileToStencil(JSContext* cx, unsigned argc, Value* vp) { |
| 6431 |
if (!CanUseExtraThreads()) { |
| 6432 |
JS_ReportErrorASCII( |
| 6433 |
cx, "Can't use offThreadCompileToStencil with --no-threads"); |
| 6434 |
return false; |
| 6435 |
} |
| 6436 |
|
| 6437 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6438 |
|
| 6439 |
if (!args.requireAtLeast(cx, "offThreadCompileToStencil", 1)) { |
| 6440 |
return false; |
| 6441 |
} |
| 6442 |
if (!args[0].isString()) { |
| 6443 |
const char* typeName = InformalValueTypeName(args[0]); |
| 6444 |
JS_ReportErrorASCII(cx, "expected string to parse, got %s", typeName); |
| 6445 |
return false; |
| 6446 |
} |
| 6447 |
|
| 6448 |
UniqueChars fileNameBytes; |
| 6449 |
CompileOptions options(cx); |
| 6450 |
options.setIntroductionType("js shell offThreadCompileToStencil") |
| 6451 |
.setFileAndLine("<string>", 1); |
| 6452 |
|
| 6453 |
if (args.length() >= 2) { |
| 6454 |
if (!args[1].isObject()) { |
| 6455 |
JS_ReportErrorASCII( |
| 6456 |
cx, "offThreadCompileToStencil: The 2nd argument must be an object"); |
| 6457 |
return false; |
| 6458 |
} |
| 6459 |
|
| 6460 |
// Offthread compilation requires that the debug metadata be set when the |
| 6461 |
// script is collected from offthread, rather than when compiled. |
| 6462 |
RootedObject opts(cx, &args[1].toObject()); |
| 6463 |
if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) { |
| 6464 |
return false; |
| 6465 |
} |
| 6466 |
} |
| 6467 |
|
| 6468 |
// This option setting must override whatever the caller requested. |
| 6469 |
options.setIsRunOnce(true); |
| 6470 |
|
| 6471 |
JSString* scriptContents = args[0].toString(); |
| 6472 |
AutoStableStringChars stableChars(cx); |
| 6473 |
if (!stableChars.initTwoByte(cx, scriptContents)) { |
| 6474 |
return false; |
| 6475 |
} |
| 6476 |
|
| 6477 |
size_t length = scriptContents->length(); |
| 6478 |
const char16_t* chars = stableChars.twoByteChars(); |
| 6479 |
|
| 6480 |
// Make sure we own the string's chars, so that they are not freed before |
| 6481 |
// the compilation is finished. |
| 6482 |
UniqueTwoByteChars ownedChars; |
| 6483 |
if (stableChars.maybeGiveOwnershipToCaller()) { |
| 6484 |
ownedChars.reset(const_cast<char16_t*>(chars)); |
| 6485 |
} else { |
| 6486 |
ownedChars.reset(cx->pod_malloc<char16_t>(length)); |
| 6487 |
if (!ownedChars) { |
| 6488 |
return false; |
| 6489 |
} |
| 6490 |
|
| 6491 |
mozilla::PodCopy(ownedChars.get(), chars, length); |
| 6492 |
} |
| 6493 |
|
| 6494 |
if (!js::CanUseExtraThreads()) { |
| 6495 |
JS_ReportErrorASCII(cx, "cannot compile code on helper thread"); |
| 6496 |
return false; |
| 6497 |
} |
| 6498 |
|
| 6499 |
JS::SourceText<char16_t> srcBuf; |
| 6500 |
if (!srcBuf.init(cx, std::move(ownedChars), length)) { |
| 6501 |
return false; |
| 6502 |
} |
| 6503 |
|
| 6504 |
OffThreadJob* job = NewOffThreadJob(cx, OffThreadJob::Kind::CompileScript, |
| 6505 |
options, std::move(srcBuf)); |
| 6506 |
if (!job) { |
| 6507 |
return false; |
| 6508 |
} |
| 6509 |
|
| 6510 |
if (!job->dispatch()) { |
| 6511 |
ReportOutOfMemory(cx); |
| 6512 |
DeleteOffThreadJob(cx, job); |
| 6513 |
return false; |
| 6514 |
} |
| 6515 |
|
| 6516 |
args.rval().setInt32(job->id); |
| 6517 |
return true; |
| 6518 |
} |
| 6519 |
|
| 6520 |
static bool FinishOffThreadStencil(JSContext* cx, unsigned argc, Value* vp) { |
| 6521 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6522 |
|
| 6523 |
OffThreadJob* job = LookupOffThreadJobForArgs(cx, args, 0); |
| 6524 |
if (!job) { |
| 6525 |
return false; |
| 6526 |
} |
| 6527 |
|
| 6528 |
job->waitUntilDone(); |
| 6529 |
|
| 6530 |
RefPtr<JS::Stencil> stencil = job->stealStencil(cx); |
| 6531 |
DeleteOffThreadJob(cx, job); |
| 6532 |
if (!stencil) { |
| 6533 |
return false; |
| 6534 |
} |
| 6535 |
RootedObject stencilObj(cx, |
| 6536 |
js::StencilObject::create(cx, std::move(stencil))); |
| 6537 |
if (!stencilObj) { |
| 6538 |
return false; |
| 6539 |
} |
| 6540 |
|
| 6541 |
args.rval().setObject(*stencilObj); |
| 6542 |
return true; |
| 6543 |
} |
| 6544 |
|
| 6545 |
static bool OffThreadCompileModuleToStencil(JSContext* cx, unsigned argc, |
| 6546 |
Value* vp) { |
| 6547 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6548 |
|
| 6549 |
if (!args.requireAtLeast(cx, "offThreadCompileModuleToStencil", 1)) { |
| 6550 |
return false; |
| 6551 |
} |
| 6552 |
if (!args[0].isString()) { |
| 6553 |
const char* typeName = InformalValueTypeName(args[0]); |
| 6554 |
JS_ReportErrorASCII(cx, "expected string to parse, got %s", typeName); |
| 6555 |
return false; |
| 6556 |
} |
| 6557 |
|
| 6558 |
UniqueChars fileNameBytes; |
| 6559 |
CompileOptions options(cx); |
| 6560 |
options.setIntroductionType("js shell offThreadCompileModuleToStencil") |
| 6561 |
.setFileAndLine("<string>", 1); |
| 6562 |
|
| 6563 |
if (args.length() >= 2) { |
| 6564 |
if (!args[1].isObject()) { |
| 6565 |
JS_ReportErrorASCII(cx, |
| 6566 |
"offThreadCompileModuleToStencil: The 2nd argument " |
| 6567 |
"must be an object"); |
| 6568 |
return false; |
| 6569 |
} |
| 6570 |
|
| 6571 |
// Offthread compilation requires that the debug metadata be set when the |
| 6572 |
// script is collected from offthread, rather than when compiled. |
| 6573 |
RootedObject opts(cx, &args[1].toObject()); |
| 6574 |
if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) { |
| 6575 |
return false; |
| 6576 |
} |
| 6577 |
|
| 6578 |
if (!ValidateModuleCompileOptions(cx, options)) { |
| 6579 |
return false; |
| 6580 |
} |
| 6581 |
} |
| 6582 |
|
| 6583 |
options.setIsRunOnce(true).setSourceIsLazy(false); |
| 6584 |
|
| 6585 |
JSString* scriptContents = args[0].toString(); |
| 6586 |
AutoStableStringChars stableChars(cx); |
| 6587 |
if (!stableChars.initTwoByte(cx, scriptContents)) { |
| 6588 |
return false; |
| 6589 |
} |
| 6590 |
|
| 6591 |
size_t length = scriptContents->length(); |
| 6592 |
const char16_t* chars = stableChars.twoByteChars(); |
| 6593 |
|
| 6594 |
// Make sure we own the string's chars, so that they are not freed before |
| 6595 |
// the compilation is finished. |
| 6596 |
UniqueTwoByteChars ownedChars; |
| 6597 |
if (stableChars.maybeGiveOwnershipToCaller()) { |
| 6598 |
ownedChars.reset(const_cast<char16_t*>(chars)); |
| 6599 |
} else { |
| 6600 |
ownedChars.reset(cx->pod_malloc<char16_t>(length)); |
| 6601 |
if (!ownedChars) { |
| 6602 |
return false; |
| 6603 |
} |
| 6604 |
|
| 6605 |
mozilla::PodCopy(ownedChars.get(), chars, length); |
| 6606 |
} |
| 6607 |
|
| 6608 |
if (!js::CanUseExtraThreads()) { |
| 6609 |
JS_ReportErrorASCII(cx, "cannot compile code on worker thread"); |
| 6610 |
return false; |
| 6611 |
} |
| 6612 |
|
| 6613 |
JS::SourceText<char16_t> srcBuf; |
| 6614 |
if (!srcBuf.init(cx, std::move(ownedChars), length)) { |
| 6615 |
return false; |
| 6616 |
} |
| 6617 |
|
| 6618 |
OffThreadJob* job = NewOffThreadJob(cx, OffThreadJob::Kind::CompileModule, |
| 6619 |
options, std::move(srcBuf)); |
| 6620 |
if (!job) { |
| 6621 |
return false; |
| 6622 |
} |
| 6623 |
|
| 6624 |
if (!job->dispatch()) { |
| 6625 |
ReportOutOfMemory(cx); |
| 6626 |
DeleteOffThreadJob(cx, job); |
| 6627 |
return false; |
| 6628 |
} |
| 6629 |
|
| 6630 |
args.rval().setInt32(job->id); |
| 6631 |
return true; |
| 6632 |
} |
| 6633 |
|
| 6634 |
static bool OffThreadDecodeStencil(JSContext* cx, unsigned argc, Value* vp) { |
| 6635 |
if (!CanUseExtraThreads()) { |
| 6636 |
JS_ReportErrorASCII(cx, |
| 6637 |
"Can't use offThreadDecodeStencil with --no-threads"); |
| 6638 |
return false; |
| 6639 |
} |
| 6640 |
|
| 6641 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 6642 |
|
| 6643 |
if (!args.requireAtLeast(cx, "offThreadDecodeStencil", 1)) { |
| 6644 |
return false; |
| 6645 |
} |
| 6646 |
if (!args[0].isObject() || !CacheEntry_isCacheEntry(&args[0].toObject())) { |
| 6647 |
const char* typeName = InformalValueTypeName(args[0]); |
| 6648 |
JS_ReportErrorASCII(cx, "expected cache entry, got %s", typeName); |
| 6649 |
return false; |
| 6650 |
} |
| 6651 |
RootedObject cacheEntry(cx, &args[0].toObject()); |
| 6652 |
|
| 6653 |
UniqueChars fileNameBytes; |
| 6654 |
CompileOptions options(cx); |
| 6655 |
options.setIntroductionType("js shell offThreadDecodeStencil") |
| 6656 |
.setFileAndLine("<string>", 1); |
| 6657 |
|
| 6658 |
if (args.length() >= 2) { |
| 6659 |
if (!args[1].isObject()) { |
| 6660 |
JS_ReportErrorASCII( |
| 6661 |
cx, "offThreadDecodeStencil: The 2nd argument must be an object"); |
| 6662 |
return false; |
| 6663 |
} |
| 6664 |
|
| 6665 |
RootedObject opts(cx, &args[1].toObject()); |
| 6666 |
if (!js::ParseCompileOptions(cx, options, opts, &fileNameBytes)) { |
| 6667 |
return false; |
| 6668 |
} |
| 6669 |
} |
| 6670 |
|
| 6671 |
// This option setting must override whatever the caller requested, and |
| 6672 |
// this should match `Evaluate` that encodes the script. |
| 6673 |
options.setIsRunOnce(false); |
| 6674 |
|
| 6675 |
JS::TranscodeBuffer loadBuffer; |
| 6676 |
size_t loadLength = 0; |
| 6677 |
uint8_t* loadData = nullptr; |
| 6678 |
loadData = CacheEntry_getBytecode(cx, cacheEntry, &loadLength); |
| 6679 |
if (!loadData) { |
| 6680 |
return false; |
| 6681 |
} |
| 6682 |
if (!loadBuffer.append(loadData, loadLength)) { |
| 6683 |
JS_ReportOutOfMemory(cx); |
| 6684 |
return false; |
| 6685 |
} |
| 6686 |
|
| 6687 |
if (!js::CanUseExtraThreads()) { |
| 6688 |
JS_ReportErrorASCII(cx, "cannot compile code on worker thread"); |
| 6689 |
return false; |
| 6690 |
} |
| 6691 |
|
| 6692 |
OffThreadJob* job = NewOffThreadJob(cx, OffThreadJob::Kind::Decode, options, |
| 6693 |
std::move(loadBuffer)); |
| 6694 |
if (!job) { |
| 6695 |
return false; |
| 6696 |
} |
| 6697 |
|
| 6698 |
if (!job->dispatch()) { |
| 6699 |
ReportOutOfMemory(cx); |
| 6700 |
DeleteOffThreadJob(cx, job); |
| 6701 |
return false; |
| 6702 |
} |
| 6703 |
|
| 6704 |
args.rval().setInt32(job->id); |
| 6705 |
return true; |
| 6706 |
} |
| 6707 |
|
| 6708 |
class AutoCStringVector { |
| 6709 |
Vector<char*> argv_; |
| 6710 |
|
| 6711 |
public: |
| 6712 |
explicit AutoCStringVector(JSContext* cx) : argv_(cx) {} |
| 6713 |
~AutoCStringVector() { |
| 6714 |
for (size_t i = 0; i < argv_.length(); i++) { |
| 6715 |
js_free(argv_[i]); |
| 6716 |
} |
| 6717 |
} |
| 6718 |
bool append(UniqueChars&& arg) { |
| 6719 |
if (!argv_.append(arg.get())) { |
| 6720 |
return false; |
| 6721 |
} |
| 6722 |
|
| 6723 |
// Now owned by this vector. |
| 6724 |
(void)arg.release(); |
| 6725 |
return true; |
| 6726 |
} |
| 6727 |
char* const* get() const { return argv_.begin(); } |
| 6728 |
size_t length() const { return argv_.length(); } |
| 6729 |
char* operator[](size_t i) const { return argv_[i]; } |
| 6730 |
void replace(size_t i, UniqueChars arg) { |
| 6731 |
js_free(argv_[i]); |
| 6732 |
argv_[i] = arg.release(); |
| 6733 |
} |
| 6734 |
}; |
| 6735 |
|
| 6736 |
#if defined(XP_WIN) |
| 6737 |
static bool EscapeForShell(JSContext* cx, AutoCStringVector& argv) { |
| 6738 |
// Windows will break arguments in argv by various spaces, so we wrap each |
| 6739 |
// argument in quotes and escape quotes within. Even with quotes, \ will be |
| 6740 |
// treated like an escape character, so inflate each \ to \\. |
| 6741 |
|
| 6742 |
for (size_t i = 0; i < argv.length(); i++) { |
| 6743 |
if (!argv[i]) { |
| 6744 |
continue; |
| 6745 |
} |
| 6746 |
|
| 6747 |
size_t newLen = 3; // quotes before and after and null-terminator |
| 6748 |
for (char* p = argv[i]; *p; p++) { |
| 6749 |
newLen++; |
| 6750 |
if (*p == '\"' || *p == '\\') { |
| 6751 |
newLen++; |
| 6752 |
} |
| 6753 |
} |
| 6754 |
|
| 6755 |
auto escaped = cx->make_pod_array<char>(newLen); |
| 6756 |
if (!escaped) { |
| 6757 |
return false; |
| 6758 |
} |
| 6759 |
|
| 6760 |
char* src = argv[i]; |
| 6761 |
char* dst = escaped.get(); |
| 6762 |
*dst++ = '\"'; |
| 6763 |
while (*src) { |
| 6764 |
if (*src == '\"' || *src == '\\') { |
| 6765 |
*dst++ = '\\'; |
| 6766 |
} |
| 6767 |
*dst++ = *src++; |
| 6768 |
} |
| 6769 |
*dst++ = '\"'; |
| 6770 |
*dst++ = '\0'; |
| 6771 |
MOZ_ASSERT(escaped.get() + newLen == dst); |
| 6772 |
|
| 6773 |
argv.replace(i, std::move(escaped)); |
| 6774 |
} |
| 6775 |
return true; |
| 6776 |
} |
| 6777 |
#endif |
| 6778 |
|
| 6779 |
#ifndef __wasi__ |
| 6780 |
static bool ReadAll(int fd, wasm::Bytes* bytes) { |
| 6781 |
size_t lastLength = bytes->length(); |
| 6782 |
while (true) { |
| 6783 |
static const int ChunkSize = 64 * 1024; |
| 6784 |
if (!bytes->growBy(ChunkSize)) { |
| 6785 |
return false; |
| 6786 |
} |
| 6787 |
|
| 6788 |
intptr_t readCount; |
| 6789 |
while (true) { |
| 6790 |
readCount = read(fd, bytes->begin() + lastLength, ChunkSize); |
| 6791 |
if (readCount >= 0) { |
| 6792 |
break; |
| 6793 |
} |
| 6794 |
if (errno != EINTR) { |
| 6795 |
return false; |
| 6796 |
} |
| 6797 |
} |
| 6798 |
|
| 6799 |
if (readCount < ChunkSize) { |
| 6800 |
bytes->shrinkTo(lastLength + readCount); |
| 6801 |
if (readCount == 0) { |
| 6802 |
return true; |
| 6803 |
} |
| 6804 |
} |
| 6805 |
|
| 6806 |
lastLength = bytes->length(); |
| 6807 |
} |
| 6808 |
} |
| 6809 |
|
| 6810 |
static bool WriteAll(int fd, const uint8_t* bytes, size_t length) { |
| 6811 |
while (length > 0) { |
| 6812 |
int written = write(fd, bytes, length); |
| 6813 |
if (written < 0) { |
| 6814 |
if (errno == EINTR) { |
| 6815 |
continue; |
| 6816 |
} |
| 6817 |
return false; |
| 6818 |
} |
| 6819 |
MOZ_ASSERT(unsigned(written) <= length); |
| 6820 |
length -= written; |
| 6821 |
bytes += written; |
| 6822 |
} |
| 6823 |
|
| 6824 |
return true; |
| 6825 |
} |
| 6826 |
|
| 6827 |
class AutoPipe { |
| 6828 |
int fds_[2]; |
| 6829 |
|
| 6830 |
public: |
| 6831 |
AutoPipe() { |
| 6832 |
fds_[0] = -1; |
| 6833 |
fds_[1] = -1; |
| 6834 |
} |
| 6835 |
|
| 6836 |
~AutoPipe() { |
| 6837 |
if (fds_[0] != -1) { |
| 6838 |
close(fds_[0]); |
| 6839 |
} |
| 6840 |
if (fds_[1] != -1) { |
| 6841 |
close(fds_[1]); |
| 6842 |
} |
| 6843 |
} |
| 6844 |
|
| 6845 |
bool init() { |
| 6846 |
# ifdef XP_WIN |
| 6847 |
return !_pipe(fds_, 4096, O_BINARY); |
| 6848 |
# else |
| 6849 |
return !pipe(fds_); |
| 6850 |
# endif |
| 6851 |
} |
| 6852 |
|
| 6853 |
int reader() const { |
| 6854 |
MOZ_ASSERT(fds_[0] != -1); |
| 6855 |
return fds_[0]; |
| 6856 |
} |
| 6857 |
|
| 6858 |
int writer() const { |
| 6859 |
MOZ_ASSERT(fds_[1] != -1); |
| 6860 |
return fds_[1]; |
| 6861 |
} |
| 6862 |
|
| 6863 |
void closeReader() { |
| 6864 |
MOZ_ASSERT(fds_[0] != -1); |
| 6865 |
close(fds_[0]); |
| 6866 |
fds_[0] = -1; |
| 6867 |
} |
| 6868 |
|
| 6869 |
void closeWriter() { |
| 6870 |
MOZ_ASSERT(fds_[1] != -1); |
| 6871 |
close(fds_[1]); |
| 6872 |
fds_[1] = -1; |
| 6873 |
} |
| 6874 |
}; |
| 6875 |
#endif // __wasi__ |
| 6876 |
|
| 6877 |
int shell::sArgc; |
| 6878 |
char** shell::sArgv; |
| 6879 |
|
| 6880 |
#ifndef __wasi__ |
| 6881 |
static const char sWasmCompileAndSerializeFlag[] = |
| 6882 |
"--wasm-compile-and-serialize"; |
| 6883 |
MOZ_RUNINIT static Vector<const char*, 5, js::SystemAllocPolicy> |
| 6884 |
sCompilerProcessFlags; |
| 6885 |
|
| 6886 |
static bool CompileAndSerializeInSeparateProcess(JSContext* cx, |
| 6887 |
const uint8_t* bytecode, |
| 6888 |
size_t bytecodeLength, |
| 6889 |
wasm::Bytes* serialized) { |
| 6890 |
AutoPipe stdIn, stdOut; |
| 6891 |
if (!stdIn.init() || !stdOut.init()) { |
| 6892 |
return false; |
| 6893 |
} |
| 6894 |
|
| 6895 |
AutoCStringVector argv(cx); |
| 6896 |
|
| 6897 |
UniqueChars argv0 = DuplicateString(cx, sArgv[0]); |
| 6898 |
if (!argv0 || !argv.append(std::move(argv0))) { |
| 6899 |
return false; |
| 6900 |
} |
| 6901 |
|
| 6902 |
// Put compiler flags first since they must precede the non-option |
| 6903 |
// file-descriptor args (passed on Windows, below). |
| 6904 |
for (unsigned i = 0; i < sCompilerProcessFlags.length(); i++) { |
| 6905 |
UniqueChars flags = DuplicateString(cx, sCompilerProcessFlags[i]); |
| 6906 |
if (!flags || !argv.append(std::move(flags))) { |
| 6907 |
return false; |
| 6908 |
} |
| 6909 |
} |
| 6910 |
|
| 6911 |
UniqueChars arg; |
| 6912 |
|
| 6913 |
arg = DuplicateString(sWasmCompileAndSerializeFlag); |
| 6914 |
if (!arg || !argv.append(std::move(arg))) { |
| 6915 |
return false; |
| 6916 |
} |
| 6917 |
|
| 6918 |
# ifdef XP_WIN |
| 6919 |
// The spawned process will have all the stdIn/stdOut file handles open, but |
| 6920 |
// without the power of fork, we need some other way to communicate the |
| 6921 |
// integer fd values so we encode them in argv and WasmCompileAndSerialize() |
| 6922 |
// has a matching #ifdef XP_WIN to parse them out. Communicate both ends of |
| 6923 |
// both pipes so the child process can closed the unused ends. |
| 6924 |
|
| 6925 |
arg = JS_smprintf("%d", stdIn.reader()); |
| 6926 |
if (!arg || !argv.append(std::move(arg))) { |
| 6927 |
return false; |
| 6928 |
} |
| 6929 |
|
| 6930 |
arg = JS_smprintf("%d", stdIn.writer()); |
| 6931 |
if (!arg || !argv.append(std::move(arg))) { |
| 6932 |
return false; |
| 6933 |
} |
| 6934 |
|
| 6935 |
arg = JS_smprintf("%d", stdOut.reader()); |
| 6936 |
if (!arg || !argv.append(std::move(arg))) { |
| 6937 |
return false; |
| 6938 |
} |
| 6939 |
|
| 6940 |
arg = JS_smprintf("%d", stdOut.writer()); |
| 6941 |
if (!arg || !argv.append(std::move(arg))) { |
| 6942 |
return false; |
| 6943 |
} |
| 6944 |
# endif |
| 6945 |
|
| 6946 |
// Required by both _spawnv and exec. |
| 6947 |
if (!argv.append(nullptr)) { |
| 6948 |
return false; |
| 6949 |
} |
| 6950 |
|
| 6951 |
# ifdef XP_WIN |
| 6952 |
if (!EscapeForShell(cx, argv)) { |
| 6953 |
return false; |
| 6954 |
} |
| 6955 |
|
| 6956 |
int childPid = _spawnv(P_NOWAIT, sArgv[0], argv.get()); |
| 6957 |
if (childPid == -1) { |
| 6958 |
return false; |
| 6959 |
} |
| 6960 |
# else |
| 6961 |
pid_t childPid = fork(); |
| 6962 |
switch (childPid) { |
| 6963 |
case -1: |
| 6964 |
return false; |
| 6965 |
case 0: |
| 6966 |
// In the child process. Redirect stdin/stdout to the respective ends of |
| 6967 |
// the pipes. Closing stdIn.writer() is necessary for stdin to hit EOF. |
| 6968 |
// This case statement must not return before exec() takes over. Rather, |
| 6969 |
// exit(-1) is used to return failure to the parent process. |
| 6970 |
if (dup2(stdIn.reader(), STDIN_FILENO) == -1) { |
| 6971 |
exit(-1); |
| 6972 |
} |
| 6973 |
if (dup2(stdOut.writer(), STDOUT_FILENO) == -1) { |
| 6974 |
exit(-1); |
| 6975 |
} |
| 6976 |
close(stdIn.reader()); |
| 6977 |
close(stdIn.writer()); |
| 6978 |
close(stdOut.reader()); |
| 6979 |
close(stdOut.writer()); |
| 6980 |
execv(sArgv[0], argv.get()); |
| 6981 |
exit(-1); |
| 6982 |
} |
| 6983 |
# endif |
| 6984 |
|
| 6985 |
// In the parent process. Closing stdOut.writer() is necessary for |
| 6986 |
// stdOut.reader() below to hit EOF. |
| 6987 |
stdIn.closeReader(); |
| 6988 |
stdOut.closeWriter(); |
| 6989 |
|
| 6990 |
if (!WriteAll(stdIn.writer(), bytecode, bytecodeLength)) { |
| 6991 |
return false; |
| 6992 |
} |
| 6993 |
|
| 6994 |
stdIn.closeWriter(); |
| 6995 |
|
| 6996 |
if (!ReadAll(stdOut.reader(), serialized)) { |
| 6997 |
return false; |
| 6998 |
} |
| 6999 |
|
| 7000 |
stdOut.closeReader(); |
| 7001 |
|
| 7002 |
int status; |
| 7003 |
# ifdef XP_WIN |
| 7004 |
if (_cwait(&status, childPid, WAIT_CHILD) == -1) { |
| 7005 |
return false; |
| 7006 |
} |
| 7007 |
# else |
| 7008 |
while (true) { |
| 7009 |
if (waitpid(childPid, &status, 0) >= 0) { |
| 7010 |
break; |
| 7011 |
} |
| 7012 |
if (errno != EINTR) { |
| 7013 |
return false; |
| 7014 |
} |
| 7015 |
} |
| 7016 |
# endif |
| 7017 |
|
| 7018 |
return status == 0; |
| 7019 |
} |
| 7020 |
|
| 7021 |
static bool WasmCompileAndSerialize(JSContext* cx) { |
| 7022 |
MOZ_ASSERT(wasm::CodeCachingAvailable(cx)); |
| 7023 |
|
| 7024 |
# ifdef XP_WIN |
| 7025 |
// See CompileAndSerializeInSeparateProcess for why we've had to smuggle |
| 7026 |
// these fd values through argv. Closing the writing ends is necessary for |
| 7027 |
// the reading ends to hit EOF. |
| 7028 |
int flagIndex = 0; |
| 7029 |
for (; flagIndex < sArgc; flagIndex++) { |
| 7030 |
if (!strcmp(sArgv[flagIndex], sWasmCompileAndSerializeFlag)) { |
| 7031 |
break; |
| 7032 |
} |
| 7033 |
} |
| 7034 |
MOZ_RELEASE_ASSERT(flagIndex < sArgc); |
| 7035 |
|
| 7036 |
int fdsIndex = flagIndex + 1; |
| 7037 |
MOZ_RELEASE_ASSERT(fdsIndex + 4 == sArgc); |
| 7038 |
|
| 7039 |
int stdInReader = atoi(sArgv[fdsIndex + 0]); |
| 7040 |
int stdInWriter = atoi(sArgv[fdsIndex + 1]); |
| 7041 |
int stdOutReader = atoi(sArgv[fdsIndex + 2]); |
| 7042 |
int stdOutWriter = atoi(sArgv[fdsIndex + 3]); |
| 7043 |
|
| 7044 |
int stdIn = stdInReader; |
| 7045 |
close(stdInWriter); |
| 7046 |
close(stdOutReader); |
| 7047 |
int stdOut = stdOutWriter; |
| 7048 |
# else |
| 7049 |
int stdIn = STDIN_FILENO; |
| 7050 |
int stdOut = STDOUT_FILENO; |
| 7051 |
# endif |
| 7052 |
|
| 7053 |
wasm::MutableBytes bytecode = js_new<wasm::ShareableBytes>(); |
| 7054 |
if (!ReadAll(stdIn, &bytecode->vector)) { |
| 7055 |
return false; |
| 7056 |
} |
| 7057 |
|
| 7058 |
wasm::BytecodeSource bytecodeSource(bytecode->begin(), bytecode->length()); |
| 7059 |
wasm::Bytes serialized; |
| 7060 |
if (!wasm::CompileAndSerialize(cx, bytecodeSource, &serialized)) { |
| 7061 |
return false; |
| 7062 |
} |
| 7063 |
|
| 7064 |
if (!WriteAll(stdOut, serialized.begin(), serialized.length())) { |
| 7065 |
return false; |
| 7066 |
} |
| 7067 |
|
| 7068 |
return true; |
| 7069 |
} |
| 7070 |
|
| 7071 |
static bool WasmCompileInSeparateProcess(JSContext* cx, unsigned argc, |
| 7072 |
Value* vp) { |
| 7073 |
if (!wasm::CodeCachingAvailable(cx)) { |
| 7074 |
JS_ReportErrorASCII(cx, "WebAssembly caching not supported"); |
| 7075 |
return false; |
| 7076 |
} |
| 7077 |
|
| 7078 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7079 |
if (!args.requireAtLeast(cx, "wasmCompileInSeparateProcess", 1)) { |
| 7080 |
return false; |
| 7081 |
} |
| 7082 |
|
| 7083 |
SharedMem<uint8_t*> bytecode; |
| 7084 |
size_t numBytes; |
| 7085 |
if (!args[0].isObject() || |
| 7086 |
!IsBufferSource(cx, &args[0].toObject(), /*allowShared*/ false, |
| 7087 |
/*allowResizable*/ false, &bytecode, &numBytes)) { |
| 7088 |
RootedObject callee(cx, &args.callee()); |
| 7089 |
ReportUsageErrorASCII(cx, callee, "Argument must be a buffer source"); |
| 7090 |
return false; |
| 7091 |
} |
| 7092 |
|
| 7093 |
wasm::Bytes serialized; |
| 7094 |
if (!CompileAndSerializeInSeparateProcess(cx, bytecode.unwrap(), numBytes, |
| 7095 |
&serialized)) { |
| 7096 |
if (!cx->isExceptionPending()) { |
| 7097 |
JS_ReportErrorASCII(cx, "creating and executing child process"); |
| 7098 |
} |
| 7099 |
return false; |
| 7100 |
} |
| 7101 |
|
| 7102 |
RootedObject module(cx); |
| 7103 |
if (!wasm::DeserializeModule(cx, serialized, &module)) { |
| 7104 |
return false; |
| 7105 |
} |
| 7106 |
|
| 7107 |
args.rval().setObject(*module); |
| 7108 |
return true; |
| 7109 |
} |
| 7110 |
#endif // __wasi__ |
| 7111 |
|
| 7112 |
static bool DecompileFunction(JSContext* cx, unsigned argc, Value* vp) { |
| 7113 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7114 |
if (args.length() < 1 || !args[0].isObject() || |
| 7115 |
!args[0].toObject().is<JSFunction>()) { |
| 7116 |
args.rval().setUndefined(); |
| 7117 |
return true; |
| 7118 |
} |
| 7119 |
RootedFunction fun(cx, &args[0].toObject().as<JSFunction>()); |
| 7120 |
JSString* result = JS_DecompileFunction(cx, fun); |
| 7121 |
if (!result) { |
| 7122 |
return false; |
| 7123 |
} |
| 7124 |
args.rval().setString(result); |
| 7125 |
return true; |
| 7126 |
} |
| 7127 |
|
| 7128 |
static bool DecompileThisScript(JSContext* cx, unsigned argc, Value* vp) { |
| 7129 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7130 |
|
| 7131 |
NonBuiltinScriptFrameIter iter(cx); |
| 7132 |
if (iter.done()) { |
| 7133 |
args.rval().setString(cx->runtime()->emptyString); |
| 7134 |
return true; |
| 7135 |
} |
| 7136 |
|
| 7137 |
{ |
| 7138 |
JSAutoRealm ar(cx, iter.script()); |
| 7139 |
|
| 7140 |
RootedScript script(cx, iter.script()); |
| 7141 |
JSString* result = JS_DecompileScript(cx, script); |
| 7142 |
if (!result) { |
| 7143 |
return false; |
| 7144 |
} |
| 7145 |
|
| 7146 |
args.rval().setString(result); |
| 7147 |
} |
| 7148 |
|
| 7149 |
return JS_WrapValue(cx, args.rval()); |
| 7150 |
} |
| 7151 |
|
| 7152 |
static bool ValueToSource(JSContext* cx, unsigned argc, Value* vp) { |
| 7153 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7154 |
|
| 7155 |
JSString* str = ValueToSource(cx, args.get(0)); |
| 7156 |
if (!str) { |
| 7157 |
return false; |
| 7158 |
} |
| 7159 |
|
| 7160 |
args.rval().setString(str); |
| 7161 |
return true; |
| 7162 |
} |
| 7163 |
|
| 7164 |
static bool ThisFilename(JSContext* cx, unsigned argc, Value* vp) { |
| 7165 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7166 |
|
| 7167 |
JS::AutoFilename filename; |
| 7168 |
if (!DescribeScriptedCaller(&filename, cx) || !filename.get()) { |
| 7169 |
args.rval().setString(cx->runtime()->emptyString); |
| 7170 |
return true; |
| 7171 |
} |
| 7172 |
|
| 7173 |
JSString* str = NewStringCopyUTF8(cx, filename.get()); |
| 7174 |
if (!str) { |
| 7175 |
return false; |
| 7176 |
} |
| 7177 |
|
| 7178 |
args.rval().setString(str); |
| 7179 |
return true; |
| 7180 |
} |
| 7181 |
|
| 7182 |
static bool WrapWithProto(JSContext* cx, unsigned argc, Value* vp) { |
| 7183 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7184 |
Value obj = args.get(0); |
| 7185 |
Value proto = args.get(1); |
| 7186 |
if (!obj.isObject() || !proto.isObjectOrNull()) { |
| 7187 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 7188 |
JSSMSG_INVALID_ARGS, "wrapWithProto"); |
| 7189 |
return false; |
| 7190 |
} |
| 7191 |
|
| 7192 |
// Disallow constructing (deeply) nested wrapper chains, to avoid running |
| 7193 |
// out of stack space in isCallable/isConstructor. See bug 1126105. |
| 7194 |
if (IsWrapper(&obj.toObject())) { |
| 7195 |
JS_ReportErrorASCII(cx, "wrapWithProto cannot wrap a wrapper"); |
| 7196 |
return false; |
| 7197 |
} |
| 7198 |
|
| 7199 |
WrapperOptions options(cx); |
| 7200 |
options.setProto(proto.toObjectOrNull()); |
| 7201 |
JSObject* wrapped = Wrapper::New(cx, &obj.toObject(), |
| 7202 |
&Wrapper::singletonWithPrototype, options); |
| 7203 |
if (!wrapped) { |
| 7204 |
return false; |
| 7205 |
} |
| 7206 |
|
| 7207 |
args.rval().setObject(*wrapped); |
| 7208 |
return true; |
| 7209 |
} |
| 7210 |
|
| 7211 |
static bool NewGlobal(JSContext* cx, unsigned argc, Value* vp) { |
| 7212 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7213 |
RootedObject callee(cx, &args.callee()); |
| 7214 |
|
| 7215 |
JS::RealmOptions options; |
| 7216 |
JS::RealmCreationOptions& creationOptions = options.creationOptions(); |
| 7217 |
JS::RealmBehaviors& behaviors = options.behaviors(); |
| 7218 |
ShellGlobalKind kind = ShellGlobalKind::WindowProxy; |
| 7219 |
bool immutablePrototype = true; |
| 7220 |
|
| 7221 |
SetStandardRealmOptions(options); |
| 7222 |
|
| 7223 |
// Default to creating the global in the current compartment unless |
| 7224 |
// --more-compartments is used. |
| 7225 |
if (defaultToSameCompartment) { |
| 7226 |
creationOptions.setExistingCompartment(cx->global()); |
| 7227 |
} else { |
| 7228 |
creationOptions.setNewCompartmentAndZone(); |
| 7229 |
} |
| 7230 |
|
| 7231 |
// Ensure the target compartment/zone is kept alive when sameCompartmentAs or |
| 7232 |
// sameZoneAs is used. |
| 7233 |
Rooted<JSObject*> compartmentRoot(cx); |
| 7234 |
|
| 7235 |
JS::AutoHoldPrincipals principals(cx); |
| 7236 |
|
| 7237 |
if (args.length() == 1 && args[0].isObject()) { |
| 7238 |
RootedObject opts(cx, &args[0].toObject()); |
| 7239 |
RootedValue v(cx); |
| 7240 |
|
| 7241 |
if (!JS_GetProperty(cx, opts, "invisibleToDebugger", &v)) { |
| 7242 |
return false; |
| 7243 |
} |
| 7244 |
if (v.isBoolean()) { |
| 7245 |
creationOptions.setInvisibleToDebugger(v.toBoolean()); |
| 7246 |
} |
| 7247 |
|
| 7248 |
if (!JS_GetProperty(cx, opts, "sameZoneAs", &v)) { |
| 7249 |
return false; |
| 7250 |
} |
| 7251 |
if (v.isObject()) { |
| 7252 |
compartmentRoot = UncheckedUnwrap(&v.toObject()); |
| 7253 |
creationOptions.setNewCompartmentInExistingZone(compartmentRoot); |
| 7254 |
} |
| 7255 |
|
| 7256 |
if (!JS_GetProperty(cx, opts, "sameCompartmentAs", &v)) { |
| 7257 |
return false; |
| 7258 |
} |
| 7259 |
if (v.isObject()) { |
| 7260 |
compartmentRoot = UncheckedUnwrap(&v.toObject()); |
| 7261 |
creationOptions.setExistingCompartment(compartmentRoot); |
| 7262 |
} |
| 7263 |
|
| 7264 |
if (!JS_GetProperty(cx, opts, "newCompartment", &v)) { |
| 7265 |
return false; |
| 7266 |
} |
| 7267 |
if (v.isBoolean()) { |
| 7268 |
if (v.toBoolean()) { |
| 7269 |
creationOptions.setNewCompartmentAndZone(); |
| 7270 |
} else { |
| 7271 |
creationOptions.setExistingCompartment(cx->global()); |
| 7272 |
} |
| 7273 |
} |
| 7274 |
|
| 7275 |
if (!JS_GetProperty(cx, opts, "discardSource", &v)) { |
| 7276 |
return false; |
| 7277 |
} |
| 7278 |
if (v.isBoolean()) { |
| 7279 |
behaviors.setDiscardSource(v.toBoolean()); |
| 7280 |
} |
| 7281 |
|
| 7282 |
if (!JS_GetProperty(cx, opts, "useWindowProxy", &v)) { |
| 7283 |
return false; |
| 7284 |
} |
| 7285 |
if (v.isBoolean()) { |
| 7286 |
kind = v.toBoolean() ? ShellGlobalKind::WindowProxy |
| 7287 |
: ShellGlobalKind::GlobalObject; |
| 7288 |
} |
| 7289 |
|
| 7290 |
if (!JS_GetProperty(cx, opts, "immutablePrototype", &v)) { |
| 7291 |
return false; |
| 7292 |
} |
| 7293 |
if (v.isBoolean()) { |
| 7294 |
immutablePrototype = v.toBoolean(); |
| 7295 |
} |
| 7296 |
|
| 7297 |
if (!JS_GetProperty(cx, opts, "systemPrincipal", &v)) { |
| 7298 |
return false; |
| 7299 |
} |
| 7300 |
if (v.isBoolean()) { |
| 7301 |
principals.reset(&ShellPrincipals::fullyTrusted); |
| 7302 |
} |
| 7303 |
|
| 7304 |
if (!JS_GetProperty(cx, opts, "principal", &v)) { |
| 7305 |
return false; |
| 7306 |
} |
| 7307 |
if (!v.isUndefined()) { |
| 7308 |
uint32_t bits; |
| 7309 |
if (!ToUint32(cx, v, &bits)) { |
| 7310 |
return false; |
| 7311 |
} |
| 7312 |
JSPrincipals* newPrincipals = cx->new_<ShellPrincipals>(bits); |
| 7313 |
if (!newPrincipals) { |
| 7314 |
return false; |
| 7315 |
} |
| 7316 |
principals.reset(newPrincipals); |
| 7317 |
} |
| 7318 |
|
| 7319 |
if (!JS_GetProperty(cx, opts, "enableCoopAndCoep", &v)) { |
| 7320 |
return false; |
| 7321 |
} |
| 7322 |
if (v.isBoolean()) { |
| 7323 |
creationOptions.setCoopAndCoepEnabled(v.toBoolean()); |
| 7324 |
} |
| 7325 |
|
| 7326 |
if (!JS_GetProperty(cx, opts, "freezeBuiltins", &v)) { |
| 7327 |
return false; |
| 7328 |
} |
| 7329 |
if (v.isBoolean()) { |
| 7330 |
creationOptions.setFreezeBuiltins(v.toBoolean()); |
| 7331 |
} |
| 7332 |
|
| 7333 |
// On the web, the SharedArrayBuffer constructor is not installed as a |
| 7334 |
// global property in pages that aren't isolated in a separate process (and |
| 7335 |
// thus can't allow the structured cloning of shared memory). Specify false |
| 7336 |
// for this option to reproduce this behavior. |
| 7337 |
if (!JS_GetProperty(cx, opts, "defineSharedArrayBufferConstructor", &v)) { |
| 7338 |
return false; |
| 7339 |
} |
| 7340 |
if (v.isBoolean()) { |
| 7341 |
creationOptions.setDefineSharedArrayBufferConstructor(v.toBoolean()); |
| 7342 |
} |
| 7343 |
|
| 7344 |
if (!JS_GetProperty(cx, opts, "forceUTC", &v)) { |
| 7345 |
return false; |
| 7346 |
} |
| 7347 |
if (v.isBoolean()) { |
| 7348 |
creationOptions.setForceUTC(v.toBoolean()); |
| 7349 |
} |
| 7350 |
|
| 7351 |
if (!JS_GetProperty(cx, opts, "alwaysUseFdlibm", &v)) { |
| 7352 |
return false; |
| 7353 |
} |
| 7354 |
if (v.isBoolean()) { |
| 7355 |
creationOptions.setAlwaysUseFdlibm(v.toBoolean()); |
| 7356 |
} |
| 7357 |
|
| 7358 |
if (!JS_GetProperty(cx, opts, "locale", &v)) { |
| 7359 |
return false; |
| 7360 |
} |
| 7361 |
if (v.isString()) { |
| 7362 |
RootedString str(cx, v.toString()); |
| 7363 |
UniqueChars locale = StringToLocale(cx, callee, str); |
| 7364 |
if (!locale) { |
| 7365 |
return false; |
| 7366 |
} |
| 7367 |
creationOptions.setLocaleCopyZ(locale.get()); |
| 7368 |
} |
| 7369 |
} |
| 7370 |
|
| 7371 |
if (!CheckRealmOptions(cx, options, principals.get())) { |
| 7372 |
return false; |
| 7373 |
} |
| 7374 |
|
| 7375 |
RootedObject global(cx, NewGlobalObject(cx, options, principals.get(), kind, |
| 7376 |
immutablePrototype)); |
| 7377 |
if (!global) { |
| 7378 |
return false; |
| 7379 |
} |
| 7380 |
|
| 7381 |
RootedObject wrapped(cx, ToWindowProxyIfWindow(global)); |
| 7382 |
if (!JS_WrapObject(cx, &wrapped)) { |
| 7383 |
return false; |
| 7384 |
} |
| 7385 |
|
| 7386 |
args.rval().setObject(*wrapped); |
| 7387 |
return true; |
| 7388 |
} |
| 7389 |
|
| 7390 |
static bool NukeAllCCWs(JSContext* cx, unsigned argc, Value* vp) { |
| 7391 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7392 |
|
| 7393 |
if (args.length() != 0) { |
| 7394 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 7395 |
JSSMSG_INVALID_ARGS, "nukeAllCCWs"); |
| 7396 |
return false; |
| 7397 |
} |
| 7398 |
|
| 7399 |
NukeCrossCompartmentWrappers(cx, AllCompartments(), cx->realm(), |
| 7400 |
NukeWindowReferences, NukeAllReferences); |
| 7401 |
args.rval().setUndefined(); |
| 7402 |
return true; |
| 7403 |
} |
| 7404 |
|
| 7405 |
static bool RecomputeWrappers(JSContext* cx, unsigned argc, Value* vp) { |
| 7406 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7407 |
|
| 7408 |
if (args.length() > 2) { |
| 7409 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 7410 |
JSSMSG_INVALID_ARGS, "recomputeWrappers"); |
| 7411 |
return false; |
| 7412 |
} |
| 7413 |
|
| 7414 |
JS::Compartment* sourceComp = nullptr; |
| 7415 |
if (args.get(0).isObject()) { |
| 7416 |
sourceComp = JS::GetCompartment(UncheckedUnwrap(&args[0].toObject())); |
| 7417 |
} |
| 7418 |
|
| 7419 |
JS::Compartment* targetComp = nullptr; |
| 7420 |
if (args.get(1).isObject()) { |
| 7421 |
targetComp = JS::GetCompartment(UncheckedUnwrap(&args[1].toObject())); |
| 7422 |
} |
| 7423 |
|
| 7424 |
struct SingleOrAllCompartments final : public CompartmentFilter { |
| 7425 |
JS::Compartment* comp; |
| 7426 |
explicit SingleOrAllCompartments(JS::Compartment* c) : comp(c) {} |
| 7427 |
virtual bool match(JS::Compartment* c) const override { |
| 7428 |
return !comp || comp == c; |
| 7429 |
} |
| 7430 |
}; |
| 7431 |
|
| 7432 |
if (!js::RecomputeWrappers(cx, SingleOrAllCompartments(sourceComp), |
| 7433 |
SingleOrAllCompartments(targetComp))) { |
| 7434 |
return false; |
| 7435 |
} |
| 7436 |
|
| 7437 |
args.rval().setUndefined(); |
| 7438 |
return true; |
| 7439 |
} |
| 7440 |
|
| 7441 |
static bool DumpObjectWrappers(JSContext* cx, unsigned argc, Value* vp) { |
| 7442 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7443 |
|
| 7444 |
bool printedHeader = false; |
| 7445 |
for (ZonesIter zone(cx->runtime(), WithAtoms); !zone.done(); zone.next()) { |
| 7446 |
bool printedZoneInfo = false; |
| 7447 |
for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) { |
| 7448 |
bool printedCompartmentInfo = false; |
| 7449 |
for (Compartment::ObjectWrapperEnum e(comp); !e.empty(); e.popFront()) { |
| 7450 |
JSObject* wrapper = e.front().value().unbarrieredGet(); |
| 7451 |
JSObject* wrapped = e.front().key(); |
| 7452 |
if (!printedHeader) { |
| 7453 |
fprintf(stderr, "Cross-compartment object wrappers:\n"); |
| 7454 |
printedHeader = true; |
| 7455 |
} |
| 7456 |
if (!printedZoneInfo) { |
| 7457 |
fprintf(stderr, " Zone %p:\n", zone.get()); |
| 7458 |
printedZoneInfo = true; |
| 7459 |
} |
| 7460 |
if (!printedCompartmentInfo) { |
| 7461 |
fprintf(stderr, " Compartment %p:\n", comp.get()); |
| 7462 |
printedCompartmentInfo = true; |
| 7463 |
} |
| 7464 |
fprintf(stderr, |
| 7465 |
" Object wrapper %p -> %p in zone %p compartment %p\n", |
| 7466 |
wrapper, wrapped, wrapped->zone(), wrapped->compartment()); |
| 7467 |
} |
| 7468 |
} |
| 7469 |
} |
| 7470 |
|
| 7471 |
if (!printedHeader) { |
| 7472 |
fprintf(stderr, "No cross-compartment object wrappers.\n"); |
| 7473 |
} |
| 7474 |
|
| 7475 |
args.rval().setUndefined(); |
| 7476 |
return true; |
| 7477 |
} |
| 7478 |
|
| 7479 |
static bool GetMaxArgs(JSContext* cx, unsigned argc, Value* vp) { |
| 7480 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7481 |
args.rval().setInt32(ARGS_LENGTH_MAX); |
| 7482 |
return true; |
| 7483 |
} |
| 7484 |
|
| 7485 |
static bool IsHTMLDDA_Call(JSContext* cx, unsigned argc, Value* vp) { |
| 7486 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7487 |
|
| 7488 |
// These are the required conditions under which this object may be called |
| 7489 |
// by test262 tests, and the required behavior under those conditions. |
| 7490 |
if (args.length() == 0 || |
| 7491 |
(args[0].isString() && args[0].toString()->length() == 0)) { |
| 7492 |
args.rval().setNull(); |
| 7493 |
return true; |
| 7494 |
} |
| 7495 |
|
| 7496 |
JS_ReportErrorASCII( |
| 7497 |
cx, "IsHTMLDDA object is being called in an impermissible manner"); |
| 7498 |
return false; |
| 7499 |
} |
| 7500 |
|
| 7501 |
static bool CreateIsHTMLDDA(JSContext* cx, unsigned argc, Value* vp) { |
| 7502 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7503 |
|
| 7504 |
static const JSClassOps classOps = { |
| 7505 |
nullptr, // addProperty |
| 7506 |
nullptr, // delProperty |
| 7507 |
nullptr, // enumerate |
| 7508 |
nullptr, // newEnumerate |
| 7509 |
nullptr, // resolve |
| 7510 |
nullptr, // mayResolve |
| 7511 |
nullptr, // finalize |
| 7512 |
IsHTMLDDA_Call, // call |
| 7513 |
nullptr, // construct |
| 7514 |
nullptr, // trace |
| 7515 |
}; |
| 7516 |
|
| 7517 |
static const JSClass cls = { |
| 7518 |
"IsHTMLDDA", |
| 7519 |
JSCLASS_EMULATES_UNDEFINED, |
| 7520 |
&classOps, |
| 7521 |
}; |
| 7522 |
|
| 7523 |
JSObject* obj = JS_NewObject(cx, &cls); |
| 7524 |
if (!obj) { |
| 7525 |
return false; |
| 7526 |
} |
| 7527 |
args.rval().setObject(*obj); |
| 7528 |
return true; |
| 7529 |
} |
| 7530 |
|
| 7531 |
static bool GetSelfHostedValue(JSContext* cx, unsigned argc, Value* vp) { |
| 7532 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7533 |
|
| 7534 |
if (args.length() != 1 || !args[0].isString()) { |
| 7535 |
JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr, |
| 7536 |
JSSMSG_INVALID_ARGS, "getSelfHostedValue"); |
| 7537 |
return false; |
| 7538 |
} |
| 7539 |
Rooted<JSAtom*> srcAtom(cx, ToAtom<CanGC>(cx, args[0])); |
| 7540 |
if (!srcAtom) { |
| 7541 |
return false; |
| 7542 |
} |
| 7543 |
Rooted<PropertyName*> srcName(cx, srcAtom->asPropertyName()); |
| 7544 |
return GlobalObject::getIntrinsicValue(cx, cx->global(), srcName, |
| 7545 |
args.rval()); |
| 7546 |
} |
| 7547 |
|
| 7548 |
class ShellSourceHook : public SourceHook { |
| 7549 |
// The function we should call to lazily retrieve source code. |
| 7550 |
PersistentRootedFunction fun; |
| 7551 |
|
| 7552 |
public: |
| 7553 |
ShellSourceHook(JSContext* cx, JSFunction& fun) : fun(cx, &fun) {} |
| 7554 |
|
| 7555 |
bool load(JSContext* cx, const char* filename, char16_t** twoByteSource, |
| 7556 |
char** utf8Source, size_t* length) override { |
| 7557 |
MOZ_ASSERT((twoByteSource != nullptr) != (utf8Source != nullptr), |
| 7558 |
"must be called requesting only one of UTF-8 or UTF-16 source"); |
| 7559 |
|
| 7560 |
RootedString str(cx); |
| 7561 |
if (filename) { |
| 7562 |
str = NewStringCopyUTF8(cx, filename); |
| 7563 |
if (!str) { |
| 7564 |
return false; |
| 7565 |
} |
| 7566 |
} else { |
| 7567 |
str = JS_GetEmptyString(cx); |
| 7568 |
} |
| 7569 |
RootedValue filenameValue(cx, StringValue(str)); |
| 7570 |
|
| 7571 |
RootedValue result(cx); |
| 7572 |
if (!Call(cx, UndefinedHandleValue, fun, HandleValueArray(filenameValue), |
| 7573 |
&result)) { |
| 7574 |
return false; |
| 7575 |
} |
| 7576 |
|
| 7577 |
str = JS::ToString(cx, result); |
| 7578 |
if (!str) { |
| 7579 |
return false; |
| 7580 |
} |
| 7581 |
|
| 7582 |
Rooted<JSLinearString*> linear(cx, str->ensureLinear(cx)); |
| 7583 |
if (!linear) { |
| 7584 |
return false; |
| 7585 |
} |
| 7586 |
|
| 7587 |
if (twoByteSource) { |
| 7588 |
*length = JS_GetStringLength(linear); |
| 7589 |
|
| 7590 |
*twoByteSource = cx->pod_malloc<char16_t>(*length); |
| 7591 |
if (!*twoByteSource) { |
| 7592 |
return false; |
| 7593 |
} |
| 7594 |
|
| 7595 |
CopyChars(*twoByteSource, *linear); |
| 7596 |
} else { |
| 7597 |
MOZ_ASSERT(utf8Source != nullptr); |
| 7598 |
|
| 7599 |
*length = JS::GetDeflatedUTF8StringLength(linear); |
| 7600 |
|
| 7601 |
*utf8Source = cx->pod_malloc<char>(*length); |
| 7602 |
if (!*utf8Source) { |
| 7603 |
return false; |
| 7604 |
} |
| 7605 |
|
| 7606 |
mozilla::DebugOnly<size_t> dstLen = JS::DeflateStringToUTF8Buffer( |
| 7607 |
linear, mozilla::Span(*utf8Source, *length)); |
| 7608 |
MOZ_ASSERT(dstLen == *length); |
| 7609 |
} |
| 7610 |
|
| 7611 |
return true; |
| 7612 |
} |
| 7613 |
}; |
| 7614 |
|
| 7615 |
static bool WithSourceHook(JSContext* cx, unsigned argc, Value* vp) { |
| 7616 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7617 |
RootedObject callee(cx, &args.callee()); |
| 7618 |
|
| 7619 |
if (args.length() != 2) { |
| 7620 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments."); |
| 7621 |
return false; |
| 7622 |
} |
| 7623 |
|
| 7624 |
if (!args[0].isObject() || !args[0].toObject().is<JSFunction>() || |
| 7625 |
!args[1].isObject() || !args[1].toObject().is<JSFunction>()) { |
| 7626 |
ReportUsageErrorASCII(cx, callee, |
| 7627 |
"First and second arguments must be functions."); |
| 7628 |
return false; |
| 7629 |
} |
| 7630 |
|
| 7631 |
mozilla::UniquePtr<ShellSourceHook> hook = |
| 7632 |
mozilla::MakeUnique<ShellSourceHook>(cx, |
| 7633 |
args[0].toObject().as<JSFunction>()); |
| 7634 |
if (!hook) { |
| 7635 |
return false; |
| 7636 |
} |
| 7637 |
|
| 7638 |
mozilla::UniquePtr<SourceHook> savedHook = js::ForgetSourceHook(cx); |
| 7639 |
js::SetSourceHook(cx, std::move(hook)); |
| 7640 |
|
| 7641 |
RootedObject fun(cx, &args[1].toObject()); |
| 7642 |
bool result = Call(cx, UndefinedHandleValue, fun, |
| 7643 |
JS::HandleValueArray::empty(), args.rval()); |
| 7644 |
js::SetSourceHook(cx, std::move(savedHook)); |
| 7645 |
return result; |
| 7646 |
} |
| 7647 |
|
| 7648 |
static void PrintProfilerEvents_Callback(mozilla::MarkerCategory, |
| 7649 |
const char* msg, const char* details) { |
| 7650 |
fprintf(stderr, "PROFILER EVENT: %s %s\n", msg, details); |
| 7651 |
} |
| 7652 |
|
| 7653 |
static void PrintProfilerIntervals_Callback(mozilla::MarkerCategory, |
| 7654 |
const char* msg, |
| 7655 |
mozilla::TimeStamp start, |
| 7656 |
const char* details) { |
| 7657 |
fprintf(stderr, "PROFILER INTERVAL (%.2fms): %s %s\n", |
| 7658 |
(TimeStamp::Now() - start).ToMilliseconds(), msg, details); |
| 7659 |
} |
| 7660 |
|
| 7661 |
static bool PrintProfilerEvents(JSContext* cx, unsigned argc, Value* vp) { |
| 7662 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7663 |
if (cx->runtime()->geckoProfiler().enabled()) { |
| 7664 |
js::RegisterContextProfilingEventMarker(cx, &PrintProfilerEvents_Callback, |
| 7665 |
&PrintProfilerIntervals_Callback); |
| 7666 |
} |
| 7667 |
args.rval().setUndefined(); |
| 7668 |
return true; |
| 7669 |
} |
| 7670 |
|
| 7671 |
#ifdef SINGLESTEP_PROFILING |
| 7672 |
static void SingleStepCallback(void* arg, jit::Simulator* sim, void* pc) { |
| 7673 |
JSContext* cx = reinterpret_cast<JSContext*>(arg); |
| 7674 |
|
| 7675 |
// If profiling is not enabled, don't do anything. |
| 7676 |
if (!cx->runtime()->geckoProfiler().enabled()) { |
| 7677 |
return; |
| 7678 |
} |
| 7679 |
|
| 7680 |
JS::ProfilingFrameIterator::RegisterState state; |
| 7681 |
state.pc = pc; |
| 7682 |
# if defined(JS_SIMULATOR_ARM) |
| 7683 |
state.sp = (void*)sim->get_register(jit::Simulator::sp); |
| 7684 |
state.lr = (void*)sim->get_register(jit::Simulator::lr); |
| 7685 |
state.fp = (void*)sim->get_register(jit::Simulator::fp); |
| 7686 |
state.tempFP = (void*)sim->get_register(jit::Simulator::r7); |
| 7687 |
# elif defined(JS_SIMULATOR_ARM64) |
| 7688 |
state.sp = (void*)sim->get_sp(); |
| 7689 |
state.lr = (void*)sim->get_lr(); |
| 7690 |
state.fp = (void*)sim->get_fp(); |
| 7691 |
state.tempFP = (void*)sim->xreg(11); |
| 7692 |
# elif defined(JS_SIMULATOR_MIPS64) |
| 7693 |
state.sp = (void*)sim->getRegister(jit::Simulator::sp); |
| 7694 |
state.lr = (void*)sim->getRegister(jit::Simulator::ra); |
| 7695 |
state.fp = (void*)sim->getRegister(jit::Simulator::fp); |
| 7696 |
# elif defined(JS_SIMULATOR_LOONG64) |
| 7697 |
state.sp = (void*)sim->getRegister(jit::Simulator::sp); |
| 7698 |
state.lr = (void*)sim->getRegister(jit::Simulator::ra); |
| 7699 |
state.fp = (void*)sim->getRegister(jit::Simulator::fp); |
| 7700 |
# else |
| 7701 |
# error "NYI: Single-step profiling support" |
| 7702 |
# endif |
| 7703 |
|
| 7704 |
mozilla::DebugOnly<void*> lastStackAddress = nullptr; |
| 7705 |
StackChars stack; |
| 7706 |
uint32_t frameNo = 0; |
| 7707 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 7708 |
for (JS::ProfilingFrameIterator i(cx, state); !i.done(); ++i) { |
| 7709 |
MOZ_ASSERT(i.stackAddress() != nullptr); |
| 7710 |
# ifndef ENABLE_WASM_JSPI |
| 7711 |
// The stack addresses are monotonically increasing, except when |
| 7712 |
// suspendable stacks are present (e.g. when JS PI is enabled). |
| 7713 |
MOZ_ASSERT(lastStackAddress <= i.stackAddress()); |
| 7714 |
# endif |
| 7715 |
lastStackAddress = i.stackAddress(); |
| 7716 |
JS::ProfilingFrameIterator::Frame frames[16]; |
| 7717 |
uint32_t nframes = i.extractStack(frames, 0, 16); |
| 7718 |
for (uint32_t i = 0; i < nframes; i++) { |
| 7719 |
# ifndef ENABLE_WASM_JSPI |
| 7720 |
// Assert endStackAddress never exceeds sp (bug 1782188). |
| 7721 |
MOZ_ASSERT(frames[i].endStackAddress >= state.sp); |
| 7722 |
# endif |
| 7723 |
if (frameNo > 0) { |
| 7724 |
if (!stack.append(",", 1)) { |
| 7725 |
oomUnsafe.crash("stack.append"); |
| 7726 |
} |
| 7727 |
} |
| 7728 |
if (!stack.append(frames[i].label, strlen(frames[i].label))) { |
| 7729 |
oomUnsafe.crash("stack.append"); |
| 7730 |
} |
| 7731 |
frameNo++; |
| 7732 |
} |
| 7733 |
} |
| 7734 |
|
| 7735 |
ShellContext* sc = GetShellContext(cx); |
| 7736 |
|
| 7737 |
// Only append the stack if it differs from the last stack. |
| 7738 |
if (sc->stacks.empty() || sc->stacks.back().length() != stack.length() || |
| 7739 |
!ArrayEqual(sc->stacks.back().begin(), stack.begin(), stack.length())) { |
| 7740 |
if (!sc->stacks.append(std::move(stack))) { |
| 7741 |
oomUnsafe.crash("stacks.append"); |
| 7742 |
} |
| 7743 |
} |
| 7744 |
} |
| 7745 |
#endif |
| 7746 |
|
| 7747 |
static bool EnableSingleStepProfiling(JSContext* cx, unsigned argc, Value* vp) { |
| 7748 |
#ifdef SINGLESTEP_PROFILING |
| 7749 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7750 |
|
| 7751 |
jit::Simulator* sim = cx->simulator(); |
| 7752 |
sim->enable_single_stepping(SingleStepCallback, cx); |
| 7753 |
|
| 7754 |
args.rval().setUndefined(); |
| 7755 |
return true; |
| 7756 |
#else |
| 7757 |
JS_ReportErrorASCII(cx, "single-step profiling not enabled on this platform"); |
| 7758 |
return false; |
| 7759 |
#endif |
| 7760 |
} |
| 7761 |
|
| 7762 |
static bool DisableSingleStepProfiling(JSContext* cx, unsigned argc, |
| 7763 |
Value* vp) { |
| 7764 |
#ifdef SINGLESTEP_PROFILING |
| 7765 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7766 |
|
| 7767 |
jit::Simulator* sim = cx->simulator(); |
| 7768 |
sim->disable_single_stepping(); |
| 7769 |
|
| 7770 |
ShellContext* sc = GetShellContext(cx); |
| 7771 |
|
| 7772 |
RootedValueVector elems(cx); |
| 7773 |
for (size_t i = 0; i < sc->stacks.length(); i++) { |
| 7774 |
JSString* stack = |
| 7775 |
JS_NewUCStringCopyN(cx, sc->stacks[i].begin(), sc->stacks[i].length()); |
| 7776 |
if (!stack) { |
| 7777 |
return false; |
| 7778 |
} |
| 7779 |
if (!elems.append(StringValue(stack))) { |
| 7780 |
return false; |
| 7781 |
} |
| 7782 |
} |
| 7783 |
|
| 7784 |
JSObject* array = JS::NewArrayObject(cx, elems); |
| 7785 |
if (!array) { |
| 7786 |
return false; |
| 7787 |
} |
| 7788 |
|
| 7789 |
sc->stacks.clear(); |
| 7790 |
args.rval().setObject(*array); |
| 7791 |
return true; |
| 7792 |
#else |
| 7793 |
JS_ReportErrorASCII(cx, "single-step profiling not enabled on this platform"); |
| 7794 |
return false; |
| 7795 |
#endif |
| 7796 |
} |
| 7797 |
|
| 7798 |
static bool IsLatin1(JSContext* cx, unsigned argc, Value* vp) { |
| 7799 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7800 |
bool isLatin1 = |
| 7801 |
args.get(0).isString() && args[0].toString()->hasLatin1Chars(); |
| 7802 |
args.rval().setBoolean(isLatin1); |
| 7803 |
return true; |
| 7804 |
} |
| 7805 |
|
| 7806 |
static bool EnableGeckoProfiling(JSContext* cx, unsigned argc, Value* vp) { |
| 7807 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7808 |
|
| 7809 |
if (!EnsureGeckoProfilingStackInstalled(cx, GetShellContext(cx))) { |
| 7810 |
return false; |
| 7811 |
} |
| 7812 |
|
| 7813 |
cx->runtime()->geckoProfiler().enableSlowAssertions(false); |
| 7814 |
cx->runtime()->geckoProfiler().enable(true); |
| 7815 |
|
| 7816 |
args.rval().setUndefined(); |
| 7817 |
return true; |
| 7818 |
} |
| 7819 |
|
| 7820 |
static bool EnableGeckoProfilingWithSlowAssertions(JSContext* cx, unsigned argc, |
| 7821 |
Value* vp) { |
| 7822 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7823 |
args.rval().setUndefined(); |
| 7824 |
|
| 7825 |
if (cx->runtime()->geckoProfiler().enabled()) { |
| 7826 |
// If profiling already enabled with slow assertions disabled, |
| 7827 |
// this is a no-op. |
| 7828 |
if (cx->runtime()->geckoProfiler().slowAssertionsEnabled()) { |
| 7829 |
return true; |
| 7830 |
} |
| 7831 |
|
| 7832 |
// Slow assertions are off. Disable profiling before re-enabling |
| 7833 |
// with slow assertions on. |
| 7834 |
cx->runtime()->geckoProfiler().enable(false); |
| 7835 |
} |
| 7836 |
|
| 7837 |
if (!EnsureGeckoProfilingStackInstalled(cx, GetShellContext(cx))) { |
| 7838 |
return false; |
| 7839 |
} |
| 7840 |
|
| 7841 |
cx->runtime()->geckoProfiler().enableSlowAssertions(true); |
| 7842 |
cx->runtime()->geckoProfiler().enable(true); |
| 7843 |
|
| 7844 |
return true; |
| 7845 |
} |
| 7846 |
|
| 7847 |
static bool DisableGeckoProfiling(JSContext* cx, unsigned argc, Value* vp) { |
| 7848 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7849 |
args.rval().setUndefined(); |
| 7850 |
|
| 7851 |
if (!cx->runtime()->geckoProfiler().enabled()) { |
| 7852 |
return true; |
| 7853 |
} |
| 7854 |
|
| 7855 |
cx->runtime()->geckoProfiler().enable(false); |
| 7856 |
return true; |
| 7857 |
} |
| 7858 |
|
| 7859 |
// Global mailbox that is used to communicate a shareable object value from one |
| 7860 |
// worker to another. |
| 7861 |
// |
| 7862 |
// These object types are shareable: |
| 7863 |
// |
| 7864 |
// - SharedArrayBuffer |
| 7865 |
// - WasmMemoryObject (when constructed with shared:true) |
| 7866 |
// - WasmModuleObject |
| 7867 |
// |
| 7868 |
// For the SharedArrayBuffer and WasmMemoryObject we transmit the underlying |
| 7869 |
// SharedArrayRawBuffer ("SARB"). For the WasmModuleObject we transmit the |
| 7870 |
// underlying JS::WasmModule. The transmitted types are refcounted. When they |
| 7871 |
// are in the mailbox their reference counts are at least 1, accounting for the |
| 7872 |
// reference from the mailbox. |
| 7873 |
// |
| 7874 |
// The lock guards the mailbox variable and prevents a race where two workers |
| 7875 |
// try to set the mailbox at the same time to replace an object that is only |
| 7876 |
// referenced from the mailbox: the workers will both decrement the reference |
| 7877 |
// count on the old object, and one of those decrements will be on a garbage |
| 7878 |
// object. We could implement this with atomics and a CAS loop but it's not |
| 7879 |
// worth the bother. |
| 7880 |
// |
| 7881 |
// Note that if a thread reads the mailbox repeatedly it will get distinct |
| 7882 |
// objects on each read. The alternatives are to cache created objects locally, |
| 7883 |
// but this retains storage we don't need to retain, or to somehow clear the |
| 7884 |
// mailbox locally, but this creates a coordination headache. Buyer beware. |
| 7885 |
|
| 7886 |
enum class MailboxTag { |
| 7887 |
Empty, |
| 7888 |
SharedArrayBuffer, |
| 7889 |
WasmMemory, |
| 7890 |
WasmModule, |
| 7891 |
Number, |
| 7892 |
}; |
| 7893 |
|
| 7894 |
struct SharedObjectMailbox { |
| 7895 |
union Value { |
| 7896 |
struct { |
| 7897 |
SharedArrayRawBuffer* buffer; |
| 7898 |
size_t length; |
| 7899 |
bool isHugeMemory; // For a WasmMemory tag, otherwise false |
| 7900 |
bool isGrowable; // For GrowableSharedArrayBuffer, otherwise false |
| 7901 |
} sarb; |
| 7902 |
JS::WasmModule* module; |
| 7903 |
double number; |
| 7904 |
|
| 7905 |
Value() : number(0.0) {} |
| 7906 |
}; |
| 7907 |
|
| 7908 |
MailboxTag tag = MailboxTag::Empty; |
| 7909 |
Value val; |
| 7910 |
}; |
| 7911 |
|
| 7912 |
using SOMailbox = ExclusiveData<SharedObjectMailbox>; |
| 7913 |
|
| 7914 |
// Never null after successful initialization. |
| 7915 |
static SOMailbox* sharedObjectMailbox; |
| 7916 |
|
| 7917 |
static bool InitSharedObjectMailbox() { |
| 7918 |
sharedObjectMailbox = js_new<SOMailbox>(mutexid::ShellObjectMailbox); |
| 7919 |
return sharedObjectMailbox != nullptr; |
| 7920 |
} |
| 7921 |
|
| 7922 |
static void DestructSharedObjectMailbox() { |
| 7923 |
// All workers need to have terminated at this point. |
| 7924 |
|
| 7925 |
{ |
| 7926 |
auto mbx = sharedObjectMailbox->lock(); |
| 7927 |
switch (mbx->tag) { |
| 7928 |
case MailboxTag::Empty: |
| 7929 |
case MailboxTag::Number: |
| 7930 |
break; |
| 7931 |
case MailboxTag::SharedArrayBuffer: |
| 7932 |
case MailboxTag::WasmMemory: |
| 7933 |
mbx->val.sarb.buffer->dropReference(); |
| 7934 |
break; |
| 7935 |
case MailboxTag::WasmModule: |
| 7936 |
mbx->val.module->Release(); |
| 7937 |
break; |
| 7938 |
default: |
| 7939 |
MOZ_CRASH(); |
| 7940 |
} |
| 7941 |
} |
| 7942 |
|
| 7943 |
js_delete(sharedObjectMailbox); |
| 7944 |
sharedObjectMailbox = nullptr; |
| 7945 |
} |
| 7946 |
|
| 7947 |
static bool GetSharedObject(JSContext* cx, unsigned argc, Value* vp) { |
| 7948 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 7949 |
RootedObject newObj(cx); |
| 7950 |
|
| 7951 |
{ |
| 7952 |
auto mbx = sharedObjectMailbox->lock(); |
| 7953 |
switch (mbx->tag) { |
| 7954 |
case MailboxTag::Empty: { |
| 7955 |
break; |
| 7956 |
} |
| 7957 |
case MailboxTag::Number: { |
| 7958 |
args.rval().setNumber(mbx->val.number); |
| 7959 |
return true; |
| 7960 |
} |
| 7961 |
case MailboxTag::SharedArrayBuffer: |
| 7962 |
case MailboxTag::WasmMemory: { |
| 7963 |
// Flag was set in the sender; ensure it is set in the receiver. |
| 7964 |
MOZ_ASSERT( |
| 7965 |
cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled()); |
| 7966 |
|
| 7967 |
// The protocol for creating a SAB requires the refcount to be |
| 7968 |
// incremented prior to the SAB creation. |
| 7969 |
|
| 7970 |
SharedArrayRawBuffer* buf = mbx->val.sarb.buffer; |
| 7971 |
size_t length = mbx->val.sarb.length; |
| 7972 |
if (!buf->addReference()) { |
| 7973 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, |
| 7974 |
JSMSG_SC_SAB_REFCNT_OFLO); |
| 7975 |
return false; |
| 7976 |
} |
| 7977 |
|
| 7978 |
// If the allocation fails we must decrement the refcount before |
| 7979 |
// returning. |
| 7980 |
|
| 7981 |
Rooted<ArrayBufferObjectMaybeShared*> maybesab(cx); |
| 7982 |
if (!mbx->val.sarb.isGrowable) { |
| 7983 |
maybesab = SharedArrayBufferObject::New(cx, buf, length); |
| 7984 |
} else { |
| 7985 |
maybesab = SharedArrayBufferObject::NewGrowable(cx, buf, length); |
| 7986 |
} |
| 7987 |
if (!maybesab) { |
| 7988 |
buf->dropReference(); |
| 7989 |
return false; |
| 7990 |
} |
| 7991 |
|
| 7992 |
// At this point the SAB was created successfully and it owns the |
| 7993 |
// refcount-increase on the buffer that we performed above. So even |
| 7994 |
// if we fail to allocate along any path below we must not decrement |
| 7995 |
// the refcount; the garbage collector must be allowed to handle |
| 7996 |
// that via finalization of the orphaned SAB object. |
| 7997 |
|
| 7998 |
if (mbx->tag == MailboxTag::SharedArrayBuffer) { |
| 7999 |
newObj = maybesab; |
| 8000 |
} else { |
| 8001 |
if (!GlobalObject::ensureConstructor(cx, cx->global(), |
| 8002 |
JSProto_WebAssembly)) { |
| 8003 |
return false; |
| 8004 |
} |
| 8005 |
RootedObject proto(cx, |
| 8006 |
&cx->global()->getPrototype(JSProto_WasmMemory)); |
| 8007 |
newObj = WasmMemoryObject::create(cx, maybesab, |
| 8008 |
mbx->val.sarb.isHugeMemory, proto); |
| 8009 |
MOZ_ASSERT_IF(newObj, newObj->as<WasmMemoryObject>().isShared()); |
| 8010 |
if (!newObj) { |
| 8011 |
return false; |
| 8012 |
} |
| 8013 |
} |
| 8014 |
|
| 8015 |
break; |
| 8016 |
} |
| 8017 |
case MailboxTag::WasmModule: { |
| 8018 |
if (!GlobalObject::ensureConstructor(cx, cx->global(), |
| 8019 |
JSProto_WebAssembly)) { |
| 8020 |
return false; |
| 8021 |
} |
| 8022 |
|
| 8023 |
// WasmModuleObject::create() increments the refcount on the module |
| 8024 |
// and signals an error and returns null if that fails. |
| 8025 |
newObj = mbx->val.module->createObject(cx); |
| 8026 |
if (!newObj) { |
| 8027 |
return false; |
| 8028 |
} |
| 8029 |
break; |
| 8030 |
} |
| 8031 |
default: { |
| 8032 |
MOZ_CRASH(); |
| 8033 |
} |
| 8034 |
} |
| 8035 |
} |
| 8036 |
|
| 8037 |
args.rval().setObjectOrNull(newObj); |
| 8038 |
return true; |
| 8039 |
} |
| 8040 |
|
| 8041 |
static bool SetSharedObject(JSContext* cx, unsigned argc, Value* vp) { |
| 8042 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8043 |
|
| 8044 |
MailboxTag tag = MailboxTag::Empty; |
| 8045 |
SharedObjectMailbox::Value value; |
| 8046 |
|
| 8047 |
// Increase refcounts when we obtain the value to avoid operating on dead |
| 8048 |
// storage during self-assignment. |
| 8049 |
|
| 8050 |
if (args.get(0).isObject()) { |
| 8051 |
RootedObject obj(cx, &args[0].toObject()); |
| 8052 |
if (obj->is<SharedArrayBufferObject>()) { |
| 8053 |
Rooted<SharedArrayBufferObject*> sab(cx, |
| 8054 |
&obj->as<SharedArrayBufferObject>()); |
| 8055 |
tag = MailboxTag::SharedArrayBuffer; |
| 8056 |
value.sarb.buffer = sab->rawBufferObject(); |
| 8057 |
value.sarb.length = sab->byteLengthOrMaxByteLength(); |
| 8058 |
value.sarb.isHugeMemory = false; |
| 8059 |
value.sarb.isGrowable = sab->isGrowable(); |
| 8060 |
if (!value.sarb.buffer->addReference()) { |
| 8061 |
JS_ReportErrorASCII(cx, |
| 8062 |
"Reference count overflow on SharedArrayBuffer"); |
| 8063 |
return false; |
| 8064 |
} |
| 8065 |
} else if (obj->is<WasmMemoryObject>()) { |
| 8066 |
// Here we must transmit sab.byteLength() as the length; the SARB has its |
| 8067 |
// own notion of the length which may be greater, and that's fine. |
| 8068 |
if (obj->as<WasmMemoryObject>().isShared()) { |
| 8069 |
Rooted<SharedArrayBufferObject*> sab( |
| 8070 |
cx, &obj->as<WasmMemoryObject>() |
| 8071 |
.buffer() |
| 8072 |
.as<SharedArrayBufferObject>()); |
| 8073 |
MOZ_ASSERT(!sab->isGrowable(), "unexpected growable shared buffer"); |
| 8074 |
tag = MailboxTag::WasmMemory; |
| 8075 |
value.sarb.buffer = sab->rawBufferObject(); |
| 8076 |
value.sarb.length = sab->byteLength(); |
| 8077 |
value.sarb.isHugeMemory = obj->as<WasmMemoryObject>().isHuge(); |
| 8078 |
value.sarb.isGrowable = false; |
| 8079 |
if (!value.sarb.buffer->addReference()) { |
| 8080 |
JS_ReportErrorASCII(cx, |
| 8081 |
"Reference count overflow on SharedArrayBuffer"); |
| 8082 |
return false; |
| 8083 |
} |
| 8084 |
} else { |
| 8085 |
JS_ReportErrorASCII(cx, "Invalid argument to SetSharedObject"); |
| 8086 |
return false; |
| 8087 |
} |
| 8088 |
} else if (JS::IsWasmModuleObject(obj)) { |
| 8089 |
tag = MailboxTag::WasmModule; |
| 8090 |
value.module = JS::GetWasmModule(obj).forget().take(); |
| 8091 |
} else { |
| 8092 |
JS_ReportErrorASCII(cx, "Invalid argument to SetSharedObject"); |
| 8093 |
return false; |
| 8094 |
} |
| 8095 |
} else if (args.get(0).isNumber()) { |
| 8096 |
tag = MailboxTag::Number; |
| 8097 |
value.number = args.get(0).toNumber(); |
| 8098 |
// Nothing |
| 8099 |
} else if (args.get(0).isNullOrUndefined()) { |
| 8100 |
// Nothing |
| 8101 |
} else { |
| 8102 |
JS_ReportErrorASCII(cx, "Invalid argument to SetSharedObject"); |
| 8103 |
return false; |
| 8104 |
} |
| 8105 |
|
| 8106 |
{ |
| 8107 |
auto mbx = sharedObjectMailbox->lock(); |
| 8108 |
|
| 8109 |
switch (mbx->tag) { |
| 8110 |
case MailboxTag::Empty: |
| 8111 |
case MailboxTag::Number: |
| 8112 |
break; |
| 8113 |
case MailboxTag::SharedArrayBuffer: |
| 8114 |
case MailboxTag::WasmMemory: |
| 8115 |
mbx->val.sarb.buffer->dropReference(); |
| 8116 |
break; |
| 8117 |
case MailboxTag::WasmModule: |
| 8118 |
mbx->val.module->Release(); |
| 8119 |
break; |
| 8120 |
default: |
| 8121 |
MOZ_CRASH(); |
| 8122 |
} |
| 8123 |
|
| 8124 |
mbx->tag = tag; |
| 8125 |
mbx->val = value; |
| 8126 |
} |
| 8127 |
|
| 8128 |
args.rval().setUndefined(); |
| 8129 |
return true; |
| 8130 |
} |
| 8131 |
|
| 8132 |
using Uint8Vector = Vector<uint8_t, 0, SystemAllocPolicy>; |
| 8133 |
|
| 8134 |
class StreamCacheEntry : public AtomicRefCounted<StreamCacheEntry>, |
| 8135 |
public JS::OptimizedEncodingListener { |
| 8136 |
using AtomicBase = AtomicRefCounted<StreamCacheEntry>; |
| 8137 |
|
| 8138 |
Uint8Vector bytes_; |
| 8139 |
ExclusiveData<Uint8Vector> optimized_; |
| 8140 |
|
| 8141 |
public: |
| 8142 |
explicit StreamCacheEntry(Uint8Vector&& original) |
| 8143 |
: bytes_(std::move(original)), |
| 8144 |
optimized_(mutexid::ShellStreamCacheEntryState) {} |
| 8145 |
|
| 8146 |
// Implement JS::OptimizedEncodingListener: |
| 8147 |
|
| 8148 |
MozExternalRefCountType MOZ_XPCOM_ABI AddRef() override { |
| 8149 |
AtomicBase::AddRef(); |
| 8150 |
return 1; // unused |
| 8151 |
} |
| 8152 |
MozExternalRefCountType MOZ_XPCOM_ABI Release() override { |
| 8153 |
AtomicBase::Release(); |
| 8154 |
return 0; // unused |
| 8155 |
} |
| 8156 |
|
| 8157 |
const Uint8Vector& bytes() const { return bytes_; } |
| 8158 |
|
| 8159 |
void storeOptimizedEncoding(const uint8_t* srcBytes, |
| 8160 |
size_t srcLength) override { |
| 8161 |
MOZ_ASSERT(srcLength > 0); |
| 8162 |
|
| 8163 |
// Tolerate races since a single StreamCacheEntry object can be used as |
| 8164 |
// the source of multiple streaming compilations. |
| 8165 |
auto dstBytes = optimized_.lock(); |
| 8166 |
if (dstBytes->length() > 0) { |
| 8167 |
return; |
| 8168 |
} |
| 8169 |
|
| 8170 |
if (!dstBytes->resize(srcLength)) { |
| 8171 |
return; |
| 8172 |
} |
| 8173 |
memcpy(dstBytes->begin(), srcBytes, srcLength); |
| 8174 |
} |
| 8175 |
|
| 8176 |
bool hasOptimizedEncoding() const { return !optimized_.lock()->empty(); } |
| 8177 |
const Uint8Vector& optimizedEncoding() const { |
| 8178 |
return optimized_.lock().get(); |
| 8179 |
} |
| 8180 |
}; |
| 8181 |
|
| 8182 |
using StreamCacheEntryPtr = RefPtr<StreamCacheEntry>; |
| 8183 |
|
| 8184 |
class StreamCacheEntryObject : public NativeObject { |
| 8185 |
static const unsigned CACHE_ENTRY_SLOT = 0; |
| 8186 |
static const JSClassOps classOps_; |
| 8187 |
static const JSPropertySpec properties_; |
| 8188 |
|
| 8189 |
static void finalize(JS::GCContext* gcx, JSObject* obj) { |
| 8190 |
obj->as<StreamCacheEntryObject>().cache().Release(); |
| 8191 |
} |
| 8192 |
|
| 8193 |
static bool cachedGetter(JSContext* cx, unsigned argc, Value* vp) { |
| 8194 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8195 |
if (!args.thisv().isObject() || |
| 8196 |
!args.thisv().toObject().is<StreamCacheEntryObject>()) { |
| 8197 |
JS_ReportErrorASCII(cx, "Expected StreamCacheEntry object"); |
| 8198 |
return false; |
| 8199 |
} |
| 8200 |
|
| 8201 |
StreamCacheEntryObject& obj = |
| 8202 |
args.thisv().toObject().as<StreamCacheEntryObject>(); |
| 8203 |
args.rval().setBoolean(obj.cache().hasOptimizedEncoding()); |
| 8204 |
return true; |
| 8205 |
} |
| 8206 |
static bool getBuffer(JSContext* cx, unsigned argc, Value* vp) { |
| 8207 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8208 |
if (!args.thisv().isObject() || |
| 8209 |
!args.thisv().toObject().is<StreamCacheEntryObject>()) { |
| 8210 |
JS_ReportErrorASCII(cx, "Expected StreamCacheEntry object"); |
| 8211 |
return false; |
| 8212 |
} |
| 8213 |
|
| 8214 |
auto& bytes = |
| 8215 |
args.thisv().toObject().as<StreamCacheEntryObject>().cache().bytes(); |
| 8216 |
auto* buffer = ArrayBufferObject::createZeroed(cx, bytes.length()); |
| 8217 |
if (!buffer) { |
| 8218 |
return false; |
| 8219 |
} |
| 8220 |
|
| 8221 |
memcpy(buffer->dataPointer(), bytes.begin(), bytes.length()); |
| 8222 |
|
| 8223 |
args.rval().setObject(*buffer); |
| 8224 |
return true; |
| 8225 |
} |
| 8226 |
|
| 8227 |
public: |
| 8228 |
static const unsigned RESERVED_SLOTS = 1; |
| 8229 |
static const JSClass class_; |
| 8230 |
static const JSPropertySpec properties[]; |
| 8231 |
|
| 8232 |
static bool construct(JSContext* cx, unsigned argc, Value* vp) { |
| 8233 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8234 |
if (!args.requireAtLeast(cx, "streamCacheEntry", 1)) { |
| 8235 |
return false; |
| 8236 |
} |
| 8237 |
|
| 8238 |
SharedMem<uint8_t*> ptr; |
| 8239 |
size_t numBytes; |
| 8240 |
if (!args[0].isObject() || |
| 8241 |
!IsBufferSource(cx, &args[0].toObject(), /*allowShared*/ true, |
| 8242 |
/*allowResizable*/ true, &ptr, &numBytes)) { |
| 8243 |
RootedObject callee(cx, &args.callee()); |
| 8244 |
ReportUsageErrorASCII(cx, callee, "Argument must be an ArrayBuffer"); |
| 8245 |
return false; |
| 8246 |
} |
| 8247 |
|
| 8248 |
Uint8Vector bytes; |
| 8249 |
if (!bytes.resize(numBytes)) { |
| 8250 |
ReportOutOfMemory(cx); |
| 8251 |
return false; |
| 8252 |
} |
| 8253 |
|
| 8254 |
memcpy(bytes.begin(), ptr.unwrap(), numBytes); |
| 8255 |
|
| 8256 |
RefPtr<StreamCacheEntry> cache = |
| 8257 |
cx->new_<StreamCacheEntry>(std::move(bytes)); |
| 8258 |
if (!cache) { |
| 8259 |
return false; |
| 8260 |
} |
| 8261 |
|
| 8262 |
Rooted<NativeObject*> obj( |
| 8263 |
cx, NewObjectWithGivenProto<StreamCacheEntryObject>(cx, nullptr)); |
| 8264 |
if (!obj) { |
| 8265 |
return false; |
| 8266 |
} |
| 8267 |
obj->initReservedSlot(CACHE_ENTRY_SLOT, |
| 8268 |
PrivateValue(cache.forget().take())); |
| 8269 |
|
| 8270 |
if (!JS_DefineProperty(cx, obj, "cached", cachedGetter, nullptr, 0)) { |
| 8271 |
return false; |
| 8272 |
} |
| 8273 |
if (!JS_DefineFunction(cx, obj, "getBuffer", getBuffer, 0, 0)) { |
| 8274 |
return false; |
| 8275 |
} |
| 8276 |
|
| 8277 |
args.rval().setObject(*obj); |
| 8278 |
return true; |
| 8279 |
} |
| 8280 |
|
| 8281 |
StreamCacheEntry& cache() const { |
| 8282 |
return *(StreamCacheEntry*)getReservedSlot(CACHE_ENTRY_SLOT).toPrivate(); |
| 8283 |
} |
| 8284 |
}; |
| 8285 |
|
| 8286 |
const JSClassOps StreamCacheEntryObject::classOps_ = { |
| 8287 |
nullptr, // addProperty |
| 8288 |
nullptr, // delProperty |
| 8289 |
nullptr, // enumerate |
| 8290 |
nullptr, // newEnumerate |
| 8291 |
nullptr, // resolve |
| 8292 |
nullptr, // mayResolve |
| 8293 |
StreamCacheEntryObject::finalize, // finalize |
| 8294 |
nullptr, // call |
| 8295 |
nullptr, // construct |
| 8296 |
nullptr, // trace |
| 8297 |
}; |
| 8298 |
|
| 8299 |
const JSClass StreamCacheEntryObject::class_ = { |
| 8300 |
"StreamCacheEntryObject", |
| 8301 |
JSCLASS_HAS_RESERVED_SLOTS(StreamCacheEntryObject::RESERVED_SLOTS) | |
| 8302 |
JSCLASS_BACKGROUND_FINALIZE, |
| 8303 |
&StreamCacheEntryObject::classOps_, |
| 8304 |
}; |
| 8305 |
|
| 8306 |
struct BufferStreamJob { |
| 8307 |
Variant<Uint8Vector, StreamCacheEntryPtr> source; |
| 8308 |
Thread thread; |
| 8309 |
JS::StreamConsumer* consumer; |
| 8310 |
|
| 8311 |
BufferStreamJob(Uint8Vector&& source, JS::StreamConsumer* consumer) |
| 8312 |
: source(AsVariant<Uint8Vector>(std::move(source))), consumer(consumer) {} |
| 8313 |
BufferStreamJob(StreamCacheEntry& source, JS::StreamConsumer* consumer) |
| 8314 |
: source(AsVariant<StreamCacheEntryPtr>(&source)), consumer(consumer) {} |
| 8315 |
}; |
| 8316 |
|
| 8317 |
struct BufferStreamState { |
| 8318 |
Vector<UniquePtr<BufferStreamJob>, 0, SystemAllocPolicy> jobs; |
| 8319 |
size_t delayMillis; |
| 8320 |
size_t chunkSize; |
| 8321 |
bool shutdown; |
| 8322 |
|
| 8323 |
BufferStreamState() : delayMillis(1), chunkSize(10), shutdown(false) {} |
| 8324 |
|
| 8325 |
~BufferStreamState() { MOZ_ASSERT(jobs.empty()); } |
| 8326 |
}; |
| 8327 |
|
| 8328 |
static ExclusiveWaitableData<BufferStreamState>* bufferStreamState; |
| 8329 |
|
| 8330 |
static void BufferStreamMain(BufferStreamJob* job) { |
| 8331 |
const uint8_t* bytes; |
| 8332 |
size_t byteLength; |
| 8333 |
JS::OptimizedEncodingListener* listener; |
| 8334 |
if (job->source.is<StreamCacheEntryPtr>()) { |
| 8335 |
StreamCacheEntry& cache = *job->source.as<StreamCacheEntryPtr>(); |
| 8336 |
if (cache.hasOptimizedEncoding()) { |
| 8337 |
const Uint8Vector& optimized = cache.optimizedEncoding(); |
| 8338 |
job->consumer->consumeOptimizedEncoding(optimized.begin(), |
| 8339 |
optimized.length()); |
| 8340 |
goto done; |
| 8341 |
} |
| 8342 |
|
| 8343 |
bytes = cache.bytes().begin(); |
| 8344 |
byteLength = cache.bytes().length(); |
| 8345 |
listener = &cache; |
| 8346 |
} else { |
| 8347 |
bytes = job->source.as<Uint8Vector>().begin(); |
| 8348 |
byteLength = job->source.as<Uint8Vector>().length(); |
| 8349 |
listener = nullptr; |
| 8350 |
} |
| 8351 |
|
| 8352 |
size_t byteOffset; |
| 8353 |
byteOffset = 0; |
| 8354 |
while (true) { |
| 8355 |
if (byteOffset == byteLength) { |
| 8356 |
job->consumer->streamEnd(listener); |
| 8357 |
break; |
| 8358 |
} |
| 8359 |
|
| 8360 |
bool shutdown; |
| 8361 |
size_t delayMillis; |
| 8362 |
size_t chunkSize; |
| 8363 |
{ |
| 8364 |
auto state = bufferStreamState->lock(); |
| 8365 |
shutdown = state->shutdown; |
| 8366 |
delayMillis = state->delayMillis; |
| 8367 |
chunkSize = state->chunkSize; |
| 8368 |
} |
| 8369 |
|
| 8370 |
if (shutdown) { |
| 8371 |
job->consumer->streamError(JSMSG_STREAM_CONSUME_ERROR); |
| 8372 |
break; |
| 8373 |
} |
| 8374 |
|
| 8375 |
ThisThread::SleepMilliseconds(delayMillis); |
| 8376 |
|
| 8377 |
chunkSize = std::min(chunkSize, byteLength - byteOffset); |
| 8378 |
|
| 8379 |
if (!job->consumer->consumeChunk(bytes + byteOffset, chunkSize)) { |
| 8380 |
break; |
| 8381 |
} |
| 8382 |
|
| 8383 |
byteOffset += chunkSize; |
| 8384 |
} |
| 8385 |
|
| 8386 |
done: |
| 8387 |
auto state = bufferStreamState->lock(); |
| 8388 |
size_t jobIndex = 0; |
| 8389 |
while (state->jobs[jobIndex].get() != job) { |
| 8390 |
jobIndex++; |
| 8391 |
} |
| 8392 |
job->thread.detach(); // quiet assert in ~Thread() called by erase(). |
| 8393 |
state->jobs.erase(state->jobs.begin() + jobIndex); |
| 8394 |
if (state->jobs.empty()) { |
| 8395 |
state.notify_all(/* jobs empty */); |
| 8396 |
} |
| 8397 |
} |
| 8398 |
|
| 8399 |
static bool ConsumeBufferSource(JSContext* cx, JS::HandleObject obj, |
| 8400 |
JS::MimeType, JS::StreamConsumer* consumer) { |
| 8401 |
{ |
| 8402 |
RootedValue url(cx); |
| 8403 |
if (!JS_GetProperty(cx, obj, "url", &url)) { |
| 8404 |
return false; |
| 8405 |
} |
| 8406 |
UniqueChars urlChars; |
| 8407 |
if (url.isString()) { |
| 8408 |
Rooted<JSString*> str(cx, url.toString()); |
| 8409 |
urlChars = JS_EncodeStringToUTF8(cx, str); |
| 8410 |
if (!urlChars) { |
| 8411 |
return false; |
| 8412 |
} |
| 8413 |
} |
| 8414 |
|
| 8415 |
RootedValue mapUrl(cx); |
| 8416 |
if (!JS_GetProperty(cx, obj, "sourceMappingURL", &mapUrl)) { |
| 8417 |
return false; |
| 8418 |
} |
| 8419 |
UniqueChars mapUrlChars; |
| 8420 |
if (mapUrl.isString()) { |
| 8421 |
Rooted<JSString*> str(cx, mapUrl.toString()); |
| 8422 |
mapUrlChars = JS_EncodeStringToUTF8(cx, str); |
| 8423 |
if (!mapUrlChars) { |
| 8424 |
return false; |
| 8425 |
} |
| 8426 |
} |
| 8427 |
|
| 8428 |
consumer->noteResponseURLs(urlChars.get(), mapUrlChars.get()); |
| 8429 |
} |
| 8430 |
|
| 8431 |
UniquePtr<BufferStreamJob> job; |
| 8432 |
|
| 8433 |
SharedMem<uint8_t*> dataPointer; |
| 8434 |
size_t byteLength; |
| 8435 |
if (IsBufferSource(cx, obj, /*allowShared*/ true, /*allowResizable*/ true, |
| 8436 |
&dataPointer, &byteLength)) { |
| 8437 |
Uint8Vector bytes; |
| 8438 |
if (!bytes.resize(byteLength)) { |
| 8439 |
JS_ReportOutOfMemory(cx); |
| 8440 |
return false; |
| 8441 |
} |
| 8442 |
|
| 8443 |
memcpy(bytes.begin(), dataPointer.unwrap(), byteLength); |
| 8444 |
job = cx->make_unique<BufferStreamJob>(std::move(bytes), consumer); |
| 8445 |
} else if (obj->is<StreamCacheEntryObject>()) { |
| 8446 |
job = cx->make_unique<BufferStreamJob>( |
| 8447 |
obj->as<StreamCacheEntryObject>().cache(), consumer); |
| 8448 |
} else { |
| 8449 |
JS_ReportErrorASCII( |
| 8450 |
cx, |
| 8451 |
"shell streaming consumes a buffer source (buffer or view) " |
| 8452 |
"or StreamCacheEntryObject"); |
| 8453 |
return false; |
| 8454 |
} |
| 8455 |
if (!job) { |
| 8456 |
return false; |
| 8457 |
} |
| 8458 |
|
| 8459 |
BufferStreamJob* jobPtr = job.get(); |
| 8460 |
|
| 8461 |
{ |
| 8462 |
auto state = bufferStreamState->lock(); |
| 8463 |
MOZ_ASSERT(!state->shutdown); |
| 8464 |
if (!state->jobs.append(std::move(job))) { |
| 8465 |
JS_ReportOutOfMemory(cx); |
| 8466 |
return false; |
| 8467 |
} |
| 8468 |
} |
| 8469 |
|
| 8470 |
{ |
| 8471 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 8472 |
if (!jobPtr->thread.init(BufferStreamMain, jobPtr)) { |
| 8473 |
oomUnsafe.crash("ConsumeBufferSource"); |
| 8474 |
} |
| 8475 |
} |
| 8476 |
|
| 8477 |
return true; |
| 8478 |
} |
| 8479 |
|
| 8480 |
static void ReportStreamError(JSContext* cx, size_t errorNumber) { |
| 8481 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber); |
| 8482 |
} |
| 8483 |
|
| 8484 |
static bool SetBufferStreamParams(JSContext* cx, unsigned argc, Value* vp) { |
| 8485 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8486 |
if (!args.requireAtLeast(cx, "setBufferStreamParams", 2)) { |
| 8487 |
return false; |
| 8488 |
} |
| 8489 |
|
| 8490 |
double delayMillis; |
| 8491 |
if (!ToNumber(cx, args[0], &delayMillis)) { |
| 8492 |
return false; |
| 8493 |
} |
| 8494 |
|
| 8495 |
double chunkSize; |
| 8496 |
if (!ToNumber(cx, args[1], &chunkSize)) { |
| 8497 |
return false; |
| 8498 |
} |
| 8499 |
|
| 8500 |
{ |
| 8501 |
auto state = bufferStreamState->lock(); |
| 8502 |
state->delayMillis = delayMillis; |
| 8503 |
state->chunkSize = chunkSize; |
| 8504 |
} |
| 8505 |
|
| 8506 |
args.rval().setUndefined(); |
| 8507 |
return true; |
| 8508 |
} |
| 8509 |
|
| 8510 |
static void ShutdownBufferStreams() { |
| 8511 |
auto state = bufferStreamState->lock(); |
| 8512 |
state->shutdown = true; |
| 8513 |
while (!state->jobs.empty()) { |
| 8514 |
state.wait(/* jobs empty */); |
| 8515 |
} |
| 8516 |
state->jobs.clearAndFree(); |
| 8517 |
} |
| 8518 |
|
| 8519 |
static bool DumpScopeChain(JSContext* cx, unsigned argc, Value* vp) { |
| 8520 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8521 |
RootedObject callee(cx, &args.callee()); |
| 8522 |
|
| 8523 |
if (js::SupportDifferentialTesting()) { |
| 8524 |
ReportUsageErrorASCII( |
| 8525 |
cx, callee, "Function not available in differential testing mode."); |
| 8526 |
return false; |
| 8527 |
} |
| 8528 |
|
| 8529 |
if (args.length() != 1) { |
| 8530 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments"); |
| 8531 |
return false; |
| 8532 |
} |
| 8533 |
|
| 8534 |
if (!args[0].isObject() || |
| 8535 |
!(args[0].toObject().is<JSFunction>() || |
| 8536 |
args[0].toObject().is<ShellModuleObjectWrapper>())) { |
| 8537 |
ReportUsageErrorASCII( |
| 8538 |
cx, callee, "Argument must be an interpreted function or a module"); |
| 8539 |
return false; |
| 8540 |
} |
| 8541 |
|
| 8542 |
RootedObject obj(cx, &args[0].toObject()); |
| 8543 |
RootedScript script(cx); |
| 8544 |
|
| 8545 |
if (obj->is<JSFunction>()) { |
| 8546 |
RootedFunction fun(cx, &obj->as<JSFunction>()); |
| 8547 |
if (!fun->isInterpreted()) { |
| 8548 |
ReportUsageErrorASCII(cx, callee, |
| 8549 |
"Argument must be an interpreted function"); |
| 8550 |
return false; |
| 8551 |
} |
| 8552 |
script = JSFunction::getOrCreateScript(cx, fun); |
| 8553 |
if (!script) { |
| 8554 |
return false; |
| 8555 |
} |
| 8556 |
} else { |
| 8557 |
script = obj->as<ShellModuleObjectWrapper>().get()->maybeScript(); |
| 8558 |
if (!script) { |
| 8559 |
JS_ReportErrorASCII(cx, "module does not have an associated script"); |
| 8560 |
return false; |
| 8561 |
} |
| 8562 |
} |
| 8563 |
|
| 8564 |
script->bodyScope()->dump(); |
| 8565 |
|
| 8566 |
args.rval().setUndefined(); |
| 8567 |
return true; |
| 8568 |
} |
| 8569 |
|
| 8570 |
// For testing GC marking, blackRoot() and grayRoot() will heap-allocate an |
| 8571 |
// array whose elements (as well as the array itself) will be marked as roots in |
| 8572 |
// subsequent GCs. |
| 8573 |
// |
| 8574 |
// Note that EnsureGrayRoot() will blacken the returned object, so it will not |
| 8575 |
// actually end up marked gray until the following GC clears the black bit |
| 8576 |
// (assuming nothing is holding onto it.) |
| 8577 |
// |
| 8578 |
// The idea is that you can set up a whole graph of objects to be marked gray, |
| 8579 |
// hanging off of the object returned from grayRoot(). Then you GC to clear the |
| 8580 |
// black bits and set the gray bits. |
| 8581 |
// |
| 8582 |
// To test grayness, register the objects of interest with addMarkObservers(), |
| 8583 |
// which takes an Array of objects (which will be marked black at the time |
| 8584 |
// they're passed in). Their mark bits may be retrieved at any time with |
| 8585 |
// getMarks(), in the form of an array of strings with each index corresponding |
| 8586 |
// to the original objects passed to addMarkObservers(). |
| 8587 |
|
| 8588 |
static bool EnsureRootArray(JSContext* cx, gc::MarkColor color, unsigned argc, |
| 8589 |
Value* vp) { |
| 8590 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8591 |
|
| 8592 |
auto priv = EnsureShellCompartmentPrivate(cx); |
| 8593 |
if (!priv) { |
| 8594 |
return false; |
| 8595 |
} |
| 8596 |
|
| 8597 |
GCPtr<ArrayObject*>& root = |
| 8598 |
(color == gc::MarkColor::Black) ? priv->blackRoot : priv->grayRoot; |
| 8599 |
|
| 8600 |
if (!root && !(root = NewTenuredDenseEmptyArray(cx))) { |
| 8601 |
return false; |
| 8602 |
} |
| 8603 |
|
| 8604 |
// Barrier to enforce the invariant that JS does not touch gray objects. |
| 8605 |
JSObject* obj = root; |
| 8606 |
JS::ExposeObjectToActiveJS(obj); |
| 8607 |
|
| 8608 |
args.rval().setObject(*obj); |
| 8609 |
return true; |
| 8610 |
} |
| 8611 |
|
| 8612 |
static bool EnsureBlackRoot(JSContext* cx, unsigned argc, Value* vp) { |
| 8613 |
return EnsureRootArray(cx, gc::MarkColor::Black, argc, vp); |
| 8614 |
} |
| 8615 |
|
| 8616 |
static bool EnsureGrayRoot(JSContext* cx, unsigned argc, Value* vp) { |
| 8617 |
return EnsureRootArray(cx, gc::MarkColor::Gray, argc, vp); |
| 8618 |
} |
| 8619 |
|
| 8620 |
static MarkBitObservers* EnsureMarkBitObservers(JSContext* cx) { |
| 8621 |
ShellContext* sc = GetShellContext(cx); |
| 8622 |
if (!sc->markObservers) { |
| 8623 |
auto* observers = |
| 8624 |
cx->new_<MarkBitObservers>(cx->runtime(), NonshrinkingGCObjectVector()); |
| 8625 |
if (!observers) { |
| 8626 |
return nullptr; |
| 8627 |
} |
| 8628 |
sc->markObservers.reset(observers); |
| 8629 |
} |
| 8630 |
return sc->markObservers.get(); |
| 8631 |
} |
| 8632 |
|
| 8633 |
static bool ClearMarkObservers(JSContext* cx, unsigned argc, Value* vp) { |
| 8634 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8635 |
|
| 8636 |
auto markObservers = EnsureMarkBitObservers(cx); |
| 8637 |
if (!markObservers) { |
| 8638 |
return false; |
| 8639 |
} |
| 8640 |
|
| 8641 |
markObservers->get().clear(); |
| 8642 |
|
| 8643 |
args.rval().setUndefined(); |
| 8644 |
return true; |
| 8645 |
} |
| 8646 |
|
| 8647 |
static bool AddMarkObservers(JSContext* cx, unsigned argc, Value* vp) { |
| 8648 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8649 |
|
| 8650 |
auto markObservers = EnsureMarkBitObservers(cx); |
| 8651 |
if (!markObservers) { |
| 8652 |
return false; |
| 8653 |
} |
| 8654 |
|
| 8655 |
if (!args.get(0).isObject()) { |
| 8656 |
JS_ReportErrorASCII(cx, "argument must be an Array of objects"); |
| 8657 |
return false; |
| 8658 |
} |
| 8659 |
|
| 8660 |
RootedObject observersArg(cx, &args[0].toObject()); |
| 8661 |
uint64_t length; |
| 8662 |
if (!GetLengthProperty(cx, observersArg, &length)) { |
| 8663 |
return false; |
| 8664 |
} |
| 8665 |
|
| 8666 |
if (length > UINT32_MAX) { |
| 8667 |
JS_ReportErrorASCII(cx, "Invalid length for observers array"); |
| 8668 |
return false; |
| 8669 |
} |
| 8670 |
|
| 8671 |
RootedValue value(cx); |
| 8672 |
RootedObject object(cx); |
| 8673 |
for (uint32_t i = 0; i < length; i++) { |
| 8674 |
if (!JS_GetElement(cx, observersArg, i, &value)) { |
| 8675 |
return false; |
| 8676 |
} |
| 8677 |
|
| 8678 |
if (!value.isObject()) { |
| 8679 |
JS_ReportErrorASCII(cx, "argument must be an Array of objects"); |
| 8680 |
return false; |
| 8681 |
} |
| 8682 |
|
| 8683 |
object = &value.toObject(); |
| 8684 |
if (gc::IsInsideNursery(object)) { |
| 8685 |
// WeakCaches are not swept during a minor GC. To prevent |
| 8686 |
// nursery-allocated contents from having the mark bits be deceptively |
| 8687 |
// black until the second GC, they would need to be marked weakly (cf |
| 8688 |
// NurseryAwareHashMap). It is simpler to evict the nursery to prevent |
| 8689 |
// nursery objects from being observed. |
| 8690 |
cx->runtime()->gc.evictNursery(); |
| 8691 |
} |
| 8692 |
|
| 8693 |
if (!markObservers->get().append(object)) { |
| 8694 |
ReportOutOfMemory(cx); |
| 8695 |
return false; |
| 8696 |
} |
| 8697 |
} |
| 8698 |
|
| 8699 |
args.rval().setInt32(length); |
| 8700 |
return true; |
| 8701 |
} |
| 8702 |
|
| 8703 |
static bool GetMarks(JSContext* cx, unsigned argc, Value* vp) { |
| 8704 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8705 |
|
| 8706 |
auto& observers = GetShellContext(cx)->markObservers; |
| 8707 |
if (!observers) { |
| 8708 |
args.rval().setUndefined(); |
| 8709 |
return true; |
| 8710 |
} |
| 8711 |
|
| 8712 |
size_t length = observers->get().length(); |
| 8713 |
Rooted<ArrayObject*> ret(cx, js::NewDenseEmptyArray(cx)); |
| 8714 |
if (!ret) { |
| 8715 |
return false; |
| 8716 |
} |
| 8717 |
|
| 8718 |
for (uint32_t i = 0; i < length; i++) { |
| 8719 |
const char* color; |
| 8720 |
JSObject* obj = observers->get()[i]; |
| 8721 |
if (!obj) { |
| 8722 |
color = "dead"; |
| 8723 |
} else if (obj->zone()->isGCPreparing()) { |
| 8724 |
color = "unmarked"; |
| 8725 |
} else { |
| 8726 |
gc::TenuredCell* cell = &obj->asTenured(); |
| 8727 |
if (cell->isMarkedGray()) { |
| 8728 |
color = "gray"; |
| 8729 |
} else if (cell->isMarkedBlack()) { |
| 8730 |
color = "black"; |
| 8731 |
} else { |
| 8732 |
color = "unmarked"; |
| 8733 |
} |
| 8734 |
} |
| 8735 |
JSString* s = JS_NewStringCopyZ(cx, color); |
| 8736 |
if (!s) { |
| 8737 |
return false; |
| 8738 |
} |
| 8739 |
if (!NewbornArrayPush(cx, ret, StringValue(s))) { |
| 8740 |
return false; |
| 8741 |
} |
| 8742 |
} |
| 8743 |
|
| 8744 |
args.rval().setObject(*ret); |
| 8745 |
return true; |
| 8746 |
} |
| 8747 |
|
| 8748 |
#ifndef __wasi__ |
| 8749 |
static bool WasmTextToBinary(JSContext* cx, unsigned argc, Value* vp) { |
| 8750 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8751 |
RootedObject callee(cx, &args.callee()); |
| 8752 |
|
| 8753 |
if (!args.requireAtLeast(cx, "wasmTextToBinary", 1)) { |
| 8754 |
return false; |
| 8755 |
} |
| 8756 |
|
| 8757 |
if (!args[0].isString()) { |
| 8758 |
ReportUsageErrorASCII(cx, callee, "First argument must be a String"); |
| 8759 |
return false; |
| 8760 |
} |
| 8761 |
|
| 8762 |
size_t textLen = args[0].toString()->length(); |
| 8763 |
|
| 8764 |
AutoStableStringChars twoByteChars(cx); |
| 8765 |
if (!twoByteChars.initTwoByte(cx, args[0].toString())) { |
| 8766 |
return false; |
| 8767 |
} |
| 8768 |
|
| 8769 |
wasm::Bytes bytes; |
| 8770 |
UniqueChars error; |
| 8771 |
if (!wasm::TextToBinary(twoByteChars.twoByteChars(), textLen, &bytes, |
| 8772 |
&error)) { |
| 8773 |
JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_WASM_TEXT_FAIL, |
| 8774 |
error.get() ? error.get() : "out of memory"); |
| 8775 |
return false; |
| 8776 |
} |
| 8777 |
|
| 8778 |
RootedObject binary(cx, JS_NewUint8Array(cx, bytes.length())); |
| 8779 |
if (!binary) { |
| 8780 |
return false; |
| 8781 |
} |
| 8782 |
|
| 8783 |
memcpy(binary->as<TypedArrayObject>().dataPointerUnshared(), bytes.begin(), |
| 8784 |
bytes.length()); |
| 8785 |
|
| 8786 |
args.rval().setObject(*binary); |
| 8787 |
return true; |
| 8788 |
} |
| 8789 |
|
| 8790 |
# ifndef __AFL_HAVE_MANUAL_CONTROL |
| 8791 |
# define __AFL_LOOP(x) true |
| 8792 |
# endif |
| 8793 |
|
| 8794 |
static bool WasmLoop(JSContext* cx, unsigned argc, Value* vp) { |
| 8795 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8796 |
RootedObject callee(cx, &args.callee()); |
| 8797 |
|
| 8798 |
if (args.length() < 1 || args.length() > 2) { |
| 8799 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments"); |
| 8800 |
return false; |
| 8801 |
} |
| 8802 |
|
| 8803 |
if (!args[0].isString()) { |
| 8804 |
ReportUsageErrorASCII(cx, callee, "First argument must be a String"); |
| 8805 |
return false; |
| 8806 |
} |
| 8807 |
|
| 8808 |
RootedObject importObj(cx); |
| 8809 |
if (!args.get(1).isUndefined()) { |
| 8810 |
if (!args.get(1).isObject()) { |
| 8811 |
ReportUsageErrorASCII(cx, callee, |
| 8812 |
"Second argument, if present, must be an Object"); |
| 8813 |
return false; |
| 8814 |
} |
| 8815 |
importObj = &args[1].toObject(); |
| 8816 |
} |
| 8817 |
|
| 8818 |
RootedString givenPath(cx, args[0].toString()); |
| 8819 |
RootedString filename(cx, ResolvePath(cx, givenPath, RootRelative)); |
| 8820 |
if (!filename) { |
| 8821 |
return false; |
| 8822 |
} |
| 8823 |
|
| 8824 |
while (__AFL_LOOP(1000)) { |
| 8825 |
Rooted<JSObject*> ret(cx, FileAsTypedArray(cx, filename)); |
| 8826 |
if (!ret) { |
| 8827 |
return false; |
| 8828 |
} |
| 8829 |
|
| 8830 |
Rooted<TypedArrayObject*> typedArray(cx, &ret->as<TypedArrayObject>()); |
| 8831 |
Rooted<WasmInstanceObject*> instanceObj(cx); |
| 8832 |
if (!wasm::Eval(cx, typedArray, importObj, &instanceObj)) { |
| 8833 |
// Clear any pending exceptions, we don't care about them |
| 8834 |
cx->clearPendingException(); |
| 8835 |
} |
| 8836 |
} |
| 8837 |
|
| 8838 |
# ifdef __AFL_HAVE_MANUAL_CONTROL // to silence unreachable code warning |
| 8839 |
return true; |
| 8840 |
# endif |
| 8841 |
} |
| 8842 |
#endif // __wasi__ |
| 8843 |
|
| 8844 |
static constexpr uint32_t DOM_OBJECT_SLOT = 0; |
| 8845 |
static constexpr uint32_t DOM_OBJECT_SLOT2 = 1; |
| 8846 |
|
| 8847 |
static const JSClass* GetDomClass(); |
| 8848 |
|
| 8849 |
static JSObject* GetDOMPrototype(JSContext* cx, JSObject* global); |
| 8850 |
|
| 8851 |
static void TransplantableDOMObject_finalize(JS::GCContext* gcx, |
| 8852 |
JSObject* obj) { |
| 8853 |
// Dummy finalize method so we can swap with background finalized object. |
| 8854 |
} |
| 8855 |
|
| 8856 |
static const JSClassOps TransplantableDOMObjectClassOps = { |
| 8857 |
nullptr, // addProperty |
| 8858 |
nullptr, // delProperty |
| 8859 |
nullptr, // enumerate |
| 8860 |
nullptr, // newEnumerate |
| 8861 |
nullptr, // resolve |
| 8862 |
nullptr, // mayResolve |
| 8863 |
TransplantableDOMObject_finalize, |
| 8864 |
nullptr, // call |
| 8865 |
nullptr, // construct |
| 8866 |
nullptr, |
| 8867 |
}; |
| 8868 |
|
| 8869 |
static const JSClass TransplantableDOMObjectClass = { |
| 8870 |
"TransplantableDOMObject", |
| 8871 |
JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(1) | |
| 8872 |
JSCLASS_BACKGROUND_FINALIZE, |
| 8873 |
&TransplantableDOMObjectClassOps}; |
| 8874 |
|
| 8875 |
static const JSClass TransplantableDOMProxyObjectClass = |
| 8876 |
PROXY_CLASS_DEF("TransplantableDOMProxyObject", |
| 8877 |
JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(1)); |
| 8878 |
|
| 8879 |
class TransplantableDOMProxyHandler final : public ForwardingProxyHandler { |
| 8880 |
public: |
| 8881 |
static const TransplantableDOMProxyHandler singleton; |
| 8882 |
static const char family; |
| 8883 |
|
| 8884 |
constexpr TransplantableDOMProxyHandler() : ForwardingProxyHandler(&family) {} |
| 8885 |
|
| 8886 |
// These two proxy traps are called in |js::DeadProxyTargetValue|, which in |
| 8887 |
// turn is called when nuking proxies. Because this proxy can temporarily be |
| 8888 |
// without an object in its private slot, see |EnsureExpandoObject|, the |
| 8889 |
// default implementation inherited from ForwardingProxyHandler can't be used, |
| 8890 |
// since it tries to derive the callable/constructible value from the target. |
| 8891 |
bool isCallable(JSObject* obj) const override { return false; } |
| 8892 |
bool isConstructor(JSObject* obj) const override { return false; } |
| 8893 |
|
| 8894 |
// Simplified implementation of |DOMProxyHandler::GetAndClearExpandoObject|. |
| 8895 |
static JSObject* GetAndClearExpandoObject( |
| 8896 |
JSObject* obj, JS::MutableHandle<JS::Value> restoreToken) { |
| 8897 |
Value v = GetProxyPrivate(obj); |
| 8898 |
restoreToken.set(v); |
| 8899 |
if (v.isUndefined()) { |
| 8900 |
return nullptr; |
| 8901 |
} |
| 8902 |
|
| 8903 |
SetProxyPrivate(obj, UndefinedValue()); |
| 8904 |
return &v.toObject(); |
| 8905 |
} |
| 8906 |
|
| 8907 |
static void RestoreExpando(JSObject* obj, const JS::Value& restoreToken) { |
| 8908 |
SetProxyPrivate(obj, restoreToken); |
| 8909 |
} |
| 8910 |
|
| 8911 |
// Simplified implementation of |DOMProxyHandler::EnsureExpandoObject|. |
| 8912 |
static JSObject* EnsureExpandoObject(JSContext* cx, JS::HandleObject obj) { |
| 8913 |
Value v = GetProxyPrivate(obj); |
| 8914 |
if (v.isObject()) { |
| 8915 |
return &v.toObject(); |
| 8916 |
} |
| 8917 |
MOZ_ASSERT(v.isUndefined()); |
| 8918 |
|
| 8919 |
JSObject* expando = JS_NewObjectWithGivenProto(cx, nullptr, nullptr); |
| 8920 |
if (!expando) { |
| 8921 |
return nullptr; |
| 8922 |
} |
| 8923 |
SetProxyPrivate(obj, ObjectValue(*expando)); |
| 8924 |
return expando; |
| 8925 |
} |
| 8926 |
}; |
| 8927 |
|
| 8928 |
const TransplantableDOMProxyHandler TransplantableDOMProxyHandler::singleton; |
| 8929 |
const char TransplantableDOMProxyHandler::family = 0; |
| 8930 |
|
| 8931 |
enum TransplantObjectSlots { |
| 8932 |
TransplantSourceObject = 0, |
| 8933 |
}; |
| 8934 |
|
| 8935 |
static bool TransplantObject(JSContext* cx, unsigned argc, Value* vp) { |
| 8936 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 8937 |
RootedFunction callee(cx, &args.callee().as<JSFunction>()); |
| 8938 |
|
| 8939 |
if (args.length() != 1 || !args[0].isObject()) { |
| 8940 |
JS_ReportErrorASCII(cx, "transplant() must be called with an object"); |
| 8941 |
return false; |
| 8942 |
} |
| 8943 |
|
| 8944 |
// |newGlobal| needs to be a GlobalObject. |
| 8945 |
RootedObject newGlobal( |
| 8946 |
cx, js::CheckedUnwrapDynamic(&args[0].toObject(), cx, |
| 8947 |
/* stopAtWindowProxy = */ false)); |
| 8948 |
if (!newGlobal) { |
| 8949 |
ReportAccessDenied(cx); |
| 8950 |
return false; |
| 8951 |
} |
| 8952 |
if (!JS_IsGlobalObject(newGlobal)) { |
| 8953 |
JS_ReportErrorNumberASCII( |
| 8954 |
cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE, |
| 8955 |
"\"global\" passed to transplant()", "not a global object"); |
| 8956 |
return false; |
| 8957 |
} |
| 8958 |
|
| 8959 |
const Value& reserved = |
| 8960 |
GetFunctionNativeReserved(callee, TransplantSourceObject); |
| 8961 |
RootedObject source(cx, CheckedUnwrapStatic(&reserved.toObject())); |
| 8962 |
if (!source) { |
| 8963 |
ReportAccessDenied(cx); |
| 8964 |
return false; |
| 8965 |
} |
| 8966 |
if (JS_IsDeadWrapper(source)) { |
| 8967 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT); |
| 8968 |
return false; |
| 8969 |
} |
| 8970 |
MOZ_ASSERT(source->getClass()->isDOMClass()); |
| 8971 |
|
| 8972 |
// The following steps aim to replicate the behavior of UpdateReflectorGlobal |
| 8973 |
// in dom/bindings/BindingUtils.cpp. In detail: |
| 8974 |
// 1. Check the recursion depth using checkConservative. |
| 8975 |
// 2. Enter the target compartment. |
| 8976 |
// 3. Clone the source object using JS_CloneObject. |
| 8977 |
// 4. Check if new wrappers can be created if source and target are in |
| 8978 |
// different compartments. |
| 8979 |
// 5. Copy all properties from source to a temporary holder object. |
| 8980 |
// 6. Actually transplant the object. |
| 8981 |
// 7. And finally copy the properties back to the source object. |
| 8982 |
// |
| 8983 |
// As an extension to the algorithm in UpdateReflectorGlobal, we also allow |
| 8984 |
// to transplant an object into the same compartment as the source object to |
| 8985 |
// cover all operations supported by JS_TransplantObject. |
| 8986 |
|
| 8987 |
AutoCheckRecursionLimit recursion(cx); |
| 8988 |
if (!recursion.checkConservative(cx)) { |
| 8989 |
return false; |
| 8990 |
} |
| 8991 |
|
| 8992 |
bool isProxy = IsProxy(source); |
| 8993 |
Rooted<JSObject*> expandoObject(cx); |
| 8994 |
Rooted<JS::Value> expandoRollbackToken(cx); |
| 8995 |
if (isProxy) { |
| 8996 |
expandoObject = TransplantableDOMProxyHandler::GetAndClearExpandoObject( |
| 8997 |
source, &expandoRollbackToken); |
| 8998 |
} |
| 8999 |
auto resetExpando = MakeScopeExit([&]() { |
| 9000 |
// We must clear the expando object from `source`, since otherwise it will |
| 9001 |
// be copied as part of JS_CloneObject. But on an error, it needs to be |
| 9002 |
// restored. |
| 9003 |
if (expandoObject) { |
| 9004 |
TransplantableDOMProxyHandler::RestoreExpando(source, |
| 9005 |
expandoRollbackToken); |
| 9006 |
} |
| 9007 |
}); |
| 9008 |
|
| 9009 |
JSAutoRealm ar(cx, newGlobal); |
| 9010 |
|
| 9011 |
RootedObject proto(cx); |
| 9012 |
if (JS::GetClass(source) == GetDomClass()) { |
| 9013 |
proto = GetDOMPrototype(cx, newGlobal); |
| 9014 |
} else { |
| 9015 |
proto = JS::GetRealmObjectPrototype(cx); |
| 9016 |
} |
| 9017 |
if (!proto) { |
| 9018 |
return false; |
| 9019 |
} |
| 9020 |
|
| 9021 |
RootedObject target(cx, JS_CloneObject(cx, source, proto)); |
| 9022 |
if (!target) { |
| 9023 |
return false; |
| 9024 |
} |
| 9025 |
|
| 9026 |
if (JS::GetCompartment(source) != JS::GetCompartment(target) && |
| 9027 |
!AllowNewWrapper(JS::GetCompartment(source), target)) { |
| 9028 |
JS_ReportErrorASCII(cx, "Cannot transplant into nuked compartment"); |
| 9029 |
return false; |
| 9030 |
} |
| 9031 |
|
| 9032 |
RootedObject copyFrom(cx, isProxy ? expandoObject : source); |
| 9033 |
RootedObject propertyHolder(cx, |
| 9034 |
JS_NewObjectWithGivenProto(cx, nullptr, nullptr)); |
| 9035 |
if (!propertyHolder) { |
| 9036 |
return false; |
| 9037 |
} |
| 9038 |
|
| 9039 |
if (!JS_CopyOwnPropertiesAndPrivateFields(cx, propertyHolder, copyFrom)) { |
| 9040 |
return false; |
| 9041 |
} |
| 9042 |
|
| 9043 |
// We've made it far enough to be able to mutate the source. Cleared slots |
| 9044 |
// will not be observed even if a failure occurs after this point. |
| 9045 |
resetExpando.release(); |
| 9046 |
|
| 9047 |
JS::SetReservedSlot(target, DOM_OBJECT_SLOT, |
| 9048 |
JS::GetReservedSlot(source, DOM_OBJECT_SLOT)); |
| 9049 |
JS::SetReservedSlot(source, DOM_OBJECT_SLOT, JS::PrivateValue(nullptr)); |
| 9050 |
if (JS::GetClass(source) == GetDomClass()) { |
| 9051 |
JS::SetReservedSlot(target, DOM_OBJECT_SLOT2, |
| 9052 |
JS::GetReservedSlot(source, DOM_OBJECT_SLOT2)); |
| 9053 |
JS::SetReservedSlot(source, DOM_OBJECT_SLOT2, UndefinedValue()); |
| 9054 |
} |
| 9055 |
|
| 9056 |
source = JS_TransplantObject(cx, source, target); |
| 9057 |
MOZ_RELEASE_ASSERT(source, "JS_TransplantObject is infallible"); |
| 9058 |
|
| 9059 |
AutoEnterOOMUnsafeRegion oomUnsafe; |
| 9060 |
|
| 9061 |
RootedObject copyTo(cx); |
| 9062 |
if (isProxy) { |
| 9063 |
copyTo = TransplantableDOMProxyHandler::EnsureExpandoObject(cx, source); |
| 9064 |
if (!copyTo) { |
| 9065 |
oomUnsafe.crash("source of transplant is corrupted"); |
| 9066 |
} |
| 9067 |
} else { |
| 9068 |
copyTo = source; |
| 9069 |
} |
| 9070 |
if (!JS_CopyOwnPropertiesAndPrivateFields(cx, copyTo, propertyHolder)) { |
| 9071 |
oomUnsafe.crash("source of transplant is corrupted"); |
| 9072 |
} |
| 9073 |
|
| 9074 |
args.rval().setUndefined(); |
| 9075 |
return true; |
| 9076 |
} |
| 9077 |
|
| 9078 |
static bool TransplantableObject(JSContext* cx, unsigned argc, Value* vp) { |
| 9079 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9080 |
RootedObject callee(cx, &args.callee()); |
| 9081 |
|
| 9082 |
if (args.length() > 1) { |
| 9083 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments"); |
| 9084 |
return false; |
| 9085 |
} |
| 9086 |
|
| 9087 |
bool createProxy = false; |
| 9088 |
RootedObject source(cx); |
| 9089 |
if (args.length() == 1 && !args[0].isUndefined()) { |
| 9090 |
if (!args[0].isObject()) { |
| 9091 |
ReportUsageErrorASCII(cx, callee, "Argument must be an object"); |
| 9092 |
return false; |
| 9093 |
} |
| 9094 |
|
| 9095 |
RootedObject options(cx, &args[0].toObject()); |
| 9096 |
RootedValue value(cx); |
| 9097 |
|
| 9098 |
if (!JS_GetProperty(cx, options, "proxy", &value)) { |
| 9099 |
return false; |
| 9100 |
} |
| 9101 |
createProxy = JS::ToBoolean(value); |
| 9102 |
|
| 9103 |
if (!JS_GetProperty(cx, options, "object", &value)) { |
| 9104 |
return false; |
| 9105 |
} |
| 9106 |
if (!value.isUndefined()) { |
| 9107 |
if (!value.isObject()) { |
| 9108 |
ReportUsageErrorASCII(cx, callee, "'object' option must be an object"); |
| 9109 |
return false; |
| 9110 |
} |
| 9111 |
|
| 9112 |
source = &value.toObject(); |
| 9113 |
if (JS::GetClass(source) != GetDomClass()) { |
| 9114 |
ReportUsageErrorASCII(cx, callee, "Object not a FakeDOMObject"); |
| 9115 |
return false; |
| 9116 |
} |
| 9117 |
|
| 9118 |
// |source| must be a tenured object to be transplantable. |
| 9119 |
if (gc::IsInsideNursery(source)) { |
| 9120 |
JS_GC(cx); |
| 9121 |
|
| 9122 |
MOZ_ASSERT(!gc::IsInsideNursery(source), |
| 9123 |
"Live objects should be tenured after one GC, because " |
| 9124 |
"the nursery has only a single generation"); |
| 9125 |
} |
| 9126 |
} |
| 9127 |
} |
| 9128 |
|
| 9129 |
if (!source) { |
| 9130 |
if (!createProxy) { |
| 9131 |
source = NewBuiltinClassInstance(cx, &TransplantableDOMObjectClass, |
| 9132 |
TenuredObject); |
| 9133 |
if (!source) { |
| 9134 |
return false; |
| 9135 |
} |
| 9136 |
|
| 9137 |
JS::SetReservedSlot(source, DOM_OBJECT_SLOT, JS::PrivateValue(nullptr)); |
| 9138 |
} else { |
| 9139 |
JSObject* expando = JS_NewPlainObject(cx); |
| 9140 |
if (!expando) { |
| 9141 |
return false; |
| 9142 |
} |
| 9143 |
RootedValue expandoVal(cx, ObjectValue(*expando)); |
| 9144 |
|
| 9145 |
ProxyOptions options; |
| 9146 |
options.setClass(&TransplantableDOMProxyObjectClass); |
| 9147 |
options.setLazyProto(true); |
| 9148 |
|
| 9149 |
source = NewProxyObject(cx, &TransplantableDOMProxyHandler::singleton, |
| 9150 |
expandoVal, nullptr, options); |
| 9151 |
if (!source) { |
| 9152 |
return false; |
| 9153 |
} |
| 9154 |
|
| 9155 |
SetProxyReservedSlot(source, DOM_OBJECT_SLOT, JS::PrivateValue(nullptr)); |
| 9156 |
} |
| 9157 |
} |
| 9158 |
|
| 9159 |
jsid emptyId = NameToId(cx->names().empty_); |
| 9160 |
RootedObject transplant( |
| 9161 |
cx, NewFunctionByIdWithReserved(cx, TransplantObject, 0, 0, emptyId)); |
| 9162 |
if (!transplant) { |
| 9163 |
return false; |
| 9164 |
} |
| 9165 |
|
| 9166 |
SetFunctionNativeReserved(transplant, TransplantSourceObject, |
| 9167 |
ObjectValue(*source)); |
| 9168 |
|
| 9169 |
RootedObject result(cx, JS_NewPlainObject(cx)); |
| 9170 |
if (!result) { |
| 9171 |
return false; |
| 9172 |
} |
| 9173 |
|
| 9174 |
RootedValue sourceVal(cx, ObjectValue(*source)); |
| 9175 |
RootedValue transplantVal(cx, ObjectValue(*transplant)); |
| 9176 |
if (!JS_DefineProperty(cx, result, "object", sourceVal, 0) || |
| 9177 |
!JS_DefineProperty(cx, result, "transplant", transplantVal, 0)) { |
| 9178 |
return false; |
| 9179 |
} |
| 9180 |
|
| 9181 |
args.rval().setObject(*result); |
| 9182 |
return true; |
| 9183 |
} |
| 9184 |
|
| 9185 |
#ifdef DEBUG |
| 9186 |
static bool DebugGetQueuedJobs(JSContext* cx, unsigned argc, Value* vp) { |
| 9187 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9188 |
|
| 9189 |
JSObject* jobs = js::GetJobsInInternalJobQueue(cx); |
| 9190 |
if (!jobs) { |
| 9191 |
return false; |
| 9192 |
} |
| 9193 |
|
| 9194 |
args.rval().setObject(*jobs); |
| 9195 |
return true; |
| 9196 |
} |
| 9197 |
#endif |
| 9198 |
|
| 9199 |
#ifdef FUZZING_INTERFACES |
| 9200 |
extern "C" { |
| 9201 |
size_t gluesmith(uint8_t* data, size_t size, uint8_t* out, size_t maxsize); |
| 9202 |
} |
| 9203 |
|
| 9204 |
static bool GetWasmSmithModule(JSContext* cx, unsigned argc, Value* vp) { |
| 9205 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9206 |
RootedObject callee(cx, &args.callee()); |
| 9207 |
|
| 9208 |
if (args.length() != 1) { |
| 9209 |
ReportUsageErrorASCII(cx, callee, "Wrong number of arguments"); |
| 9210 |
return false; |
| 9211 |
} |
| 9212 |
|
| 9213 |
if (!args[0].isObject() || !args[0].toObject().is<ArrayBufferObject>()) { |
| 9214 |
ReportUsageErrorASCII(cx, callee, "Argument must be ArrayBuffer."); |
| 9215 |
return false; |
| 9216 |
} |
| 9217 |
|
| 9218 |
ArrayBufferObject* arrayBuffer = &args[0].toObject().as<ArrayBufferObject>(); |
| 9219 |
size_t length = arrayBuffer->byteLength(); |
| 9220 |
uint8_t* data = arrayBuffer->dataPointer(); |
| 9221 |
|
| 9222 |
const size_t maxModuleSize = 4096; |
| 9223 |
uint8_t tmp[maxModuleSize]; |
| 9224 |
|
| 9225 |
size_t outSize = gluesmith(data, length, tmp, maxModuleSize); |
| 9226 |
if (!outSize) { |
| 9227 |
JS_ReportErrorASCII(cx, "Generated module is too large."); |
| 9228 |
return false; |
| 9229 |
} |
| 9230 |
|
| 9231 |
JS::Rooted<JSObject*> outArr(cx, JS_NewUint8ClampedArray(cx, outSize)); |
| 9232 |
if (!outArr) { |
| 9233 |
return false; |
| 9234 |
} |
| 9235 |
|
| 9236 |
{ |
| 9237 |
JS::AutoCheckCannotGC nogc; |
| 9238 |
bool isShared; |
| 9239 |
uint8_t* data = JS_GetUint8ClampedArrayData(outArr, &isShared, nogc); |
| 9240 |
MOZ_RELEASE_ASSERT(!isShared); |
| 9241 |
memcpy(data, tmp, outSize); |
| 9242 |
} |
| 9243 |
|
| 9244 |
args.rval().setObject(*outArr); |
| 9245 |
return true; |
| 9246 |
} |
| 9247 |
|
| 9248 |
#endif |
| 9249 |
|
| 9250 |
static bool IsValidJSON(JSContext* cx, unsigned argc, Value* vp) { |
| 9251 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9252 |
RootedObject callee(cx, &args.callee()); |
| 9253 |
|
| 9254 |
if (!args.get(0).isString()) { |
| 9255 |
ReportUsageErrorASCII(cx, callee, "First argument must be a String"); |
| 9256 |
return false; |
| 9257 |
} |
| 9258 |
|
| 9259 |
JS::Rooted<JSLinearString*> input(cx, args[0].toString()->ensureLinear(cx)); |
| 9260 |
if (!input) { |
| 9261 |
return false; |
| 9262 |
} |
| 9263 |
|
| 9264 |
bool result; |
| 9265 |
if (input->hasLatin1Chars()) { |
| 9266 |
JS::AutoCheckCannotGC nogc; |
| 9267 |
result = JS::IsValidJSON(input->latin1Chars(nogc), input->length()); |
| 9268 |
} else { |
| 9269 |
JS::AutoCheckCannotGC nogc; |
| 9270 |
result = JS::IsValidJSON(input->twoByteChars(nogc), input->length()); |
| 9271 |
} |
| 9272 |
|
| 9273 |
args.rval().setBoolean(result); |
| 9274 |
return true; |
| 9275 |
} |
| 9276 |
|
| 9277 |
// Quick file format for a LZ4 compressed file |
| 9278 |
static constexpr uint32_t LZ4MagicHeader = -1; |
| 9279 |
// A magic word and a length field |
| 9280 |
static constexpr size_t LZ4HeaderSize = sizeof(uint32_t) * 2; |
| 9281 |
static constexpr size_t LZ4MaxSize = UINT32_MAX; |
| 9282 |
|
| 9283 |
static bool CompressLZ4(JSContext* cx, unsigned argc, Value* vp) { |
| 9284 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9285 |
RootedObject callee(cx, &args.callee()); |
| 9286 |
|
| 9287 |
if (!args.get(0).isObject() || |
| 9288 |
!args.get(0).toObject().is<ArrayBufferObject>()) { |
| 9289 |
ReportUsageErrorASCII(cx, callee, "First argument must be an ArrayBuffer"); |
| 9290 |
return false; |
| 9291 |
} |
| 9292 |
|
| 9293 |
JS::Rooted<ArrayBufferObject*> bytes( |
| 9294 |
cx, &args.get(0).toObject().as<ArrayBufferObject>()); |
| 9295 |
size_t byteLength = bytes->byteLength(); |
| 9296 |
#ifdef JS_64BIT |
| 9297 |
if (byteLength > LZ4MaxSize) { |
| 9298 |
ReportOutOfMemory(cx); |
| 9299 |
return false; |
| 9300 |
} |
| 9301 |
#else |
| 9302 |
static_assert(LZ4MaxSize == UINT32_MAX, "don't need to check max on 32-bit"); |
| 9303 |
#endif |
| 9304 |
|
| 9305 |
// Create a buffer big enough for the header and the max amount of compressed |
| 9306 |
// bytes. |
| 9307 |
size_t outputCapacity = |
| 9308 |
LZ4HeaderSize + mozilla::Compression::LZ4::maxCompressedSize(byteLength); |
| 9309 |
|
| 9310 |
mozilla::UniquePtr<void, JS::FreePolicy> output(js_malloc(outputCapacity)); |
| 9311 |
if (!output) { |
| 9312 |
ReportOutOfMemory(cx); |
| 9313 |
return false; |
| 9314 |
} |
| 9315 |
|
| 9316 |
// Write the magic header word and decompressed size in bytes. |
| 9317 |
((uint32_t*)(output.get()))[0] = LZ4MagicHeader; |
| 9318 |
((uint32_t*)(output.get()))[1] = byteLength; |
| 9319 |
|
| 9320 |
// Compress the bytes into the output |
| 9321 |
char* compressedBytesStart = ((char*)output.get()) + LZ4HeaderSize; |
| 9322 |
size_t compressedBytesLength = mozilla::Compression::LZ4::compress( |
| 9323 |
(const char*)bytes->dataPointer(), byteLength, compressedBytesStart); |
| 9324 |
size_t outputLength = compressedBytesLength + LZ4HeaderSize; |
| 9325 |
|
| 9326 |
// Create an ArrayBuffer wrapping the compressed bytes |
| 9327 |
JSObject* outputArrayBuffer = |
| 9328 |
NewArrayBufferWithContents(cx, outputLength, std::move(output)); |
| 9329 |
if (!outputArrayBuffer) { |
| 9330 |
return false; |
| 9331 |
} |
| 9332 |
|
| 9333 |
args.rval().setObject(*outputArrayBuffer); |
| 9334 |
return true; |
| 9335 |
} |
| 9336 |
|
| 9337 |
static bool DecompressLZ4(JSContext* cx, unsigned argc, Value* vp) { |
| 9338 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9339 |
RootedObject callee(cx, &args.callee()); |
| 9340 |
|
| 9341 |
if (!args.get(0).isObject() || |
| 9342 |
!args.get(0).toObject().is<ArrayBufferObject>()) { |
| 9343 |
ReportUsageErrorASCII(cx, callee, "First argument must be an ArrayBuffer"); |
| 9344 |
return false; |
| 9345 |
} |
| 9346 |
|
| 9347 |
JS::Rooted<ArrayBufferObject*> bytes( |
| 9348 |
cx, &args.get(0).toObject().as<ArrayBufferObject>()); |
| 9349 |
size_t byteLength = bytes->byteLength(); |
| 9350 |
if (byteLength < LZ4HeaderSize) { |
| 9351 |
JS_ReportErrorASCII(cx, "Invalid LZ4 buffer"); |
| 9352 |
return false; |
| 9353 |
} |
| 9354 |
|
| 9355 |
// Check the magic header and get the decompressed byte length. |
| 9356 |
uint32_t magicHeader = ((uint32_t*)(bytes->dataPointer()))[0]; |
| 9357 |
uint32_t decompressedBytesLength = ((uint32_t*)(bytes->dataPointer()))[1]; |
| 9358 |
if (magicHeader != LZ4MagicHeader) { |
| 9359 |
JS_ReportErrorASCII(cx, "Invalid magic header"); |
| 9360 |
return false; |
| 9361 |
} |
| 9362 |
|
| 9363 |
// Allocate a buffer to store the decompressed bytes. |
| 9364 |
mozilla::UniquePtr<void, JS::FreePolicy> decompressedBytes( |
| 9365 |
js_malloc(decompressedBytesLength)); |
| 9366 |
if (!decompressedBytes) { |
| 9367 |
ReportOutOfMemory(cx); |
| 9368 |
return false; |
| 9369 |
} |
| 9370 |
|
| 9371 |
// Decompress the bytes into the output |
| 9372 |
const char* compressedBytesStart = |
| 9373 |
((const char*)bytes->dataPointer()) + LZ4HeaderSize; |
| 9374 |
size_t compressedBytesLength = byteLength - LZ4HeaderSize; |
| 9375 |
size_t actualDecompressedBytesLength = 0; |
| 9376 |
if (!mozilla::Compression::LZ4::decompress( |
| 9377 |
compressedBytesStart, compressedBytesLength, |
| 9378 |
(char*)decompressedBytes.get(), decompressedBytesLength, |
| 9379 |
&actualDecompressedBytesLength) || |
| 9380 |
actualDecompressedBytesLength != decompressedBytesLength) { |
| 9381 |
JS_ReportErrorASCII(cx, "Invalid LZ4 buffer"); |
| 9382 |
return false; |
| 9383 |
} |
| 9384 |
|
| 9385 |
// Create an ArrayBuffer wrapping the decompressed bytes |
| 9386 |
JSObject* outputArrayBuffer = NewArrayBufferWithContents( |
| 9387 |
cx, decompressedBytesLength, std::move(decompressedBytes)); |
| 9388 |
if (!outputArrayBuffer) { |
| 9389 |
return false; |
| 9390 |
} |
| 9391 |
|
| 9392 |
args.rval().setObject(*outputArrayBuffer); |
| 9393 |
return true; |
| 9394 |
} |
| 9395 |
|
| 9396 |
static bool SideEffectfulResolveObject_enumerate( |
| 9397 |
JSContext* cx, JS::HandleObject obj, JS::MutableHandleIdVector properties, |
| 9398 |
bool enumerableOnly) { |
| 9399 |
return properties.append(NameToId(cx->names().test)); |
| 9400 |
} |
| 9401 |
|
| 9402 |
static bool SideEffectfulResolveObject_resolve(JSContext* cx, HandleObject obj, |
| 9403 |
HandleId id, bool* resolvedp) { |
| 9404 |
*resolvedp = false; |
| 9405 |
if (JS::dbg::ShouldAvoidSideEffects(cx)) { |
| 9406 |
JS::ReportUncatchableException(cx); |
| 9407 |
return false; |
| 9408 |
} |
| 9409 |
|
| 9410 |
if (id == NameToId(cx->names().test)) { |
| 9411 |
RootedValue value(cx, JS::NumberValue(42)); |
| 9412 |
if (!JS_DefinePropertyById(cx, obj, id, value, JSPROP_ENUMERATE)) { |
| 9413 |
return false; |
| 9414 |
} |
| 9415 |
*resolvedp = true; |
| 9416 |
} |
| 9417 |
|
| 9418 |
return true; |
| 9419 |
} |
| 9420 |
|
| 9421 |
static const JSClassOps SideEffectfulResolveObject_classOps = { |
| 9422 |
nullptr, // addProperty |
| 9423 |
nullptr, // delProperty |
| 9424 |
nullptr, // enumerate |
| 9425 |
SideEffectfulResolveObject_enumerate, // newEnumerate |
| 9426 |
SideEffectfulResolveObject_resolve, // resolve |
| 9427 |
nullptr, // mayResolve |
| 9428 |
nullptr, // finalize |
| 9429 |
nullptr, // call |
| 9430 |
nullptr, // construct |
| 9431 |
nullptr, |
| 9432 |
}; |
| 9433 |
|
| 9434 |
static const JSClass SideEffectfulResolveObject_class = { |
| 9435 |
"SideEffectfulResolveObject", |
| 9436 |
0, |
| 9437 |
&SideEffectfulResolveObject_classOps, |
| 9438 |
}; |
| 9439 |
|
| 9440 |
static bool CreateSideEffectfulResolveObject(JSContext* cx, unsigned argc, |
| 9441 |
JS::Value* vp) { |
| 9442 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9443 |
|
| 9444 |
RootedObject obj(cx, JS_NewObject(cx, &SideEffectfulResolveObject_class)); |
| 9445 |
if (!obj) { |
| 9446 |
return false; |
| 9447 |
} |
| 9448 |
|
| 9449 |
args.rval().setObject(*obj); |
| 9450 |
return true; |
| 9451 |
} |
| 9452 |
|
| 9453 |
#ifdef MOZ_EXECUTION_TRACING |
| 9454 |
|
| 9455 |
static bool EnableExecutionTracing(JSContext* cx, unsigned argc, |
| 9456 |
JS::Value* vp) { |
| 9457 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9458 |
|
| 9459 |
if (!JS_TracerBeginTracing(cx)) { |
| 9460 |
return false; |
| 9461 |
} |
| 9462 |
|
| 9463 |
args.rval().setUndefined(); |
| 9464 |
return true; |
| 9465 |
} |
| 9466 |
|
| 9467 |
static bool GetExecutionTrace(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 9468 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9469 |
|
| 9470 |
JS::ExecutionTrace trace; |
| 9471 |
if (!JS_TracerSnapshotTrace(trace)) { |
| 9472 |
JS_ReportErrorASCII(cx, "Failed to get the execution trace"); |
| 9473 |
return false; |
| 9474 |
} |
| 9475 |
|
| 9476 |
JS::Rooted<JSString*> functionEnterStr(cx, |
| 9477 |
JS_AtomizeString(cx, "FunctionEnter")); |
| 9478 |
if (!functionEnterStr) { |
| 9479 |
return false; |
| 9480 |
} |
| 9481 |
JS::Rooted<JSString*> functionLeaveStr(cx, |
| 9482 |
JS_AtomizeString(cx, "FunctionLeave")); |
| 9483 |
if (!functionLeaveStr) { |
| 9484 |
return false; |
| 9485 |
} |
| 9486 |
JS::Rooted<JSString*> labelEnterStr(cx, JS_AtomizeString(cx, "LabelEnter")); |
| 9487 |
if (!labelEnterStr) { |
| 9488 |
return false; |
| 9489 |
} |
| 9490 |
JS::Rooted<JSString*> labelLeaveStr(cx, JS_AtomizeString(cx, "LabelLeave")); |
| 9491 |
if (!labelLeaveStr) { |
| 9492 |
return false; |
| 9493 |
} |
| 9494 |
JS::Rooted<JSString*> errorStr(cx, JS_AtomizeString(cx, "Error")); |
| 9495 |
if (!errorStr) { |
| 9496 |
return false; |
| 9497 |
} |
| 9498 |
|
| 9499 |
JS::Rooted<JSString*> interpreterStr(cx, JS_AtomizeString(cx, "interpreter")); |
| 9500 |
if (!interpreterStr) { |
| 9501 |
return false; |
| 9502 |
} |
| 9503 |
JS::Rooted<JSString*> baselineStr(cx, JS_AtomizeString(cx, "baseline")); |
| 9504 |
if (!baselineStr) { |
| 9505 |
return false; |
| 9506 |
} |
| 9507 |
JS::Rooted<JSString*> ionStr(cx, JS_AtomizeString(cx, "ion")); |
| 9508 |
if (!ionStr) { |
| 9509 |
return false; |
| 9510 |
} |
| 9511 |
JS::Rooted<JSString*> wasmStr(cx, JS_AtomizeString(cx, "wasm")); |
| 9512 |
if (!wasmStr) { |
| 9513 |
return false; |
| 9514 |
} |
| 9515 |
|
| 9516 |
JS::Rooted<JSString*> kindStr(cx, JS_AtomizeString(cx, "kind")); |
| 9517 |
if (!kindStr) { |
| 9518 |
return false; |
| 9519 |
} |
| 9520 |
JS::Rooted<JS::PropertyKey> kindId(cx, JS::PropertyKey::NonIntAtom(kindStr)); |
| 9521 |
|
| 9522 |
JS::Rooted<JSString*> implementationStr( |
| 9523 |
cx, JS_AtomizeString(cx, "implementation")); |
| 9524 |
if (!implementationStr) { |
| 9525 |
return false; |
| 9526 |
} |
| 9527 |
JS::Rooted<JS::PropertyKey> implementationId( |
| 9528 |
cx, JS::PropertyKey::NonIntAtom(implementationStr)); |
| 9529 |
|
| 9530 |
JS::Rooted<JSString*> timeStr(cx, JS_AtomizeString(cx, "time")); |
| 9531 |
if (!timeStr) { |
| 9532 |
return false; |
| 9533 |
} |
| 9534 |
JS::Rooted<JS::PropertyKey> timeId(cx, JS::PropertyKey::NonIntAtom(timeStr)); |
| 9535 |
|
| 9536 |
JS::Rooted<JSString*> eventsStr(cx, JS_AtomizeString(cx, "events")); |
| 9537 |
if (!eventsStr) { |
| 9538 |
return false; |
| 9539 |
} |
| 9540 |
JS::Rooted<JS::PropertyKey> eventsId(cx, |
| 9541 |
JS::PropertyKey::NonIntAtom(eventsStr)); |
| 9542 |
|
| 9543 |
JS::Rooted<JS::PropertyKey> lineNumberId(cx, |
| 9544 |
NameToId(cx->names().lineNumber)); |
| 9545 |
JS::Rooted<JS::PropertyKey> columnNumberId( |
| 9546 |
cx, NameToId(cx->names().columnNumber)); |
| 9547 |
JS::Rooted<JS::PropertyKey> scriptId(cx, NameToId(cx->names().script)); |
| 9548 |
JS::Rooted<JS::PropertyKey> nameId(cx, NameToId(cx->names().name)); |
| 9549 |
JS::Rooted<JS::PropertyKey> labelId(cx, NameToId(cx->names().label)); |
| 9550 |
JS::Rooted<JSString*> realmIDStr(cx, JS_AtomizeString(cx, "realmID")); |
| 9551 |
if (!realmIDStr) { |
| 9552 |
return false; |
| 9553 |
} |
| 9554 |
JS::Rooted<JS::PropertyKey> realmIDId( |
| 9555 |
cx, JS::PropertyKey::NonIntAtom(realmIDStr)); |
| 9556 |
|
| 9557 |
JS::Rooted<JSObject*> contextObj(cx); |
| 9558 |
JS::Rooted<ArrayObject*> eventsArray(cx); |
| 9559 |
JS::Rooted<JSObject*> eventObj(cx); |
| 9560 |
JS::Rooted<JSString*> str(cx); |
| 9561 |
|
| 9562 |
JS::Rooted<ArrayObject*> traceArray(cx, NewDenseEmptyArray(cx)); |
| 9563 |
if (!traceArray) { |
| 9564 |
return false; |
| 9565 |
} |
| 9566 |
|
| 9567 |
for (const auto& context : trace.contexts) { |
| 9568 |
contextObj = JS_NewPlainObject(cx); |
| 9569 |
if (!contextObj) { |
| 9570 |
return false; |
| 9571 |
} |
| 9572 |
|
| 9573 |
eventsArray = NewDenseEmptyArray(cx); |
| 9574 |
if (!eventsArray) { |
| 9575 |
return false; |
| 9576 |
} |
| 9577 |
|
| 9578 |
for (const auto& event : context.events) { |
| 9579 |
eventObj = JS_NewPlainObject(cx); |
| 9580 |
if (!eventObj) { |
| 9581 |
return false; |
| 9582 |
} |
| 9583 |
|
| 9584 |
switch (event.kind) { |
| 9585 |
case JS::ExecutionTrace::EventKind::FunctionEnter: |
| 9586 |
str = functionEnterStr; |
| 9587 |
break; |
| 9588 |
case JS::ExecutionTrace::EventKind::FunctionLeave: |
| 9589 |
str = functionLeaveStr; |
| 9590 |
break; |
| 9591 |
case JS::ExecutionTrace::EventKind::LabelEnter: |
| 9592 |
str = labelEnterStr; |
| 9593 |
break; |
| 9594 |
case JS::ExecutionTrace::EventKind::LabelLeave: |
| 9595 |
str = labelLeaveStr; |
| 9596 |
break; |
| 9597 |
case JS::ExecutionTrace::EventKind::Error: |
| 9598 |
str = errorStr; |
| 9599 |
break; |
| 9600 |
default: |
| 9601 |
MOZ_CRASH("Unexpected EventKind"); |
| 9602 |
break; |
| 9603 |
} |
| 9604 |
if (!JS_DefinePropertyById(cx, eventObj, kindId, str, JSPROP_ENUMERATE)) { |
| 9605 |
return false; |
| 9606 |
} |
| 9607 |
|
| 9608 |
if (event.kind == JS::ExecutionTrace::EventKind::FunctionEnter || |
| 9609 |
event.kind == JS::ExecutionTrace::EventKind::FunctionLeave) { |
| 9610 |
switch (event.functionEvent.implementation) { |
| 9611 |
case JS::ExecutionTrace::ImplementationType::Interpreter: |
| 9612 |
str = interpreterStr; |
| 9613 |
break; |
| 9614 |
case JS::ExecutionTrace::ImplementationType::Baseline: |
| 9615 |
str = baselineStr; |
| 9616 |
break; |
| 9617 |
case JS::ExecutionTrace::ImplementationType::Ion: |
| 9618 |
str = ionStr; |
| 9619 |
break; |
| 9620 |
case JS::ExecutionTrace::ImplementationType::Wasm: |
| 9621 |
str = wasmStr; |
| 9622 |
break; |
| 9623 |
default: |
| 9624 |
MOZ_CRASH("Unexpected ImplementationType"); |
| 9625 |
break; |
| 9626 |
} |
| 9627 |
if (!JS_DefinePropertyById(cx, eventObj, implementationId, str, |
| 9628 |
JSPROP_ENUMERATE)) { |
| 9629 |
return false; |
| 9630 |
} |
| 9631 |
|
| 9632 |
if (!JS_DefinePropertyById(cx, eventObj, lineNumberId, |
| 9633 |
event.functionEvent.lineNumber, |
| 9634 |
JSPROP_ENUMERATE)) { |
| 9635 |
return false; |
| 9636 |
} |
| 9637 |
|
| 9638 |
if (!JS_DefinePropertyById(cx, eventObj, columnNumberId, |
| 9639 |
event.functionEvent.column, |
| 9640 |
JSPROP_ENUMERATE)) { |
| 9641 |
return false; |
| 9642 |
} |
| 9643 |
|
| 9644 |
if (auto p = context.scriptUrls.lookup(event.functionEvent.scriptId)) { |
| 9645 |
str = JS_NewStringCopyUTF8Z( |
| 9646 |
cx, JS::ConstUTF8CharsZ(trace.stringBuffer.begin() + p->value())); |
| 9647 |
if (!str) { |
| 9648 |
return false; |
| 9649 |
} |
| 9650 |
|
| 9651 |
if (!JS_DefinePropertyById(cx, eventObj, scriptId, str, |
| 9652 |
JSPROP_ENUMERATE)) { |
| 9653 |
return false; |
| 9654 |
} |
| 9655 |
} else { |
| 9656 |
if (!JS_DefinePropertyById(cx, eventObj, scriptId, |
| 9657 |
JS::UndefinedHandleValue, |
| 9658 |
JSPROP_ENUMERATE)) { |
| 9659 |
return false; |
| 9660 |
} |
| 9661 |
} |
| 9662 |
|
| 9663 |
if (!JS_DefinePropertyById( |
| 9664 |
cx, eventObj, realmIDId, |
| 9665 |
// We are converting a uint64_t into double which is lossy. But |
| 9666 |
// this is okay because Firefox makes sure to only use 53 bits |
| 9667 |
// so it can be converted to and from a JS value without loss of |
| 9668 |
// precision. Additionally we don't set the realmID in JS shell. |
| 9669 |
double(event.functionEvent.realmID), JSPROP_ENUMERATE)) { |
| 9670 |
return false; |
| 9671 |
} |
| 9672 |
|
| 9673 |
if (auto p = context.atoms.lookup(event.functionEvent.functionNameId)) { |
| 9674 |
str = JS_NewStringCopyUTF8Z( |
| 9675 |
cx, JS::ConstUTF8CharsZ(trace.stringBuffer.begin() + p->value())); |
| 9676 |
if (!str) { |
| 9677 |
return false; |
| 9678 |
} |
| 9679 |
|
| 9680 |
if (!JS_DefinePropertyById(cx, eventObj, nameId, str, |
| 9681 |
JSPROP_ENUMERATE)) { |
| 9682 |
return false; |
| 9683 |
} |
| 9684 |
} else { |
| 9685 |
if (!JS_DefinePropertyById(cx, eventObj, nameId, |
| 9686 |
JS::UndefinedHandleValue, |
| 9687 |
JSPROP_ENUMERATE)) { |
| 9688 |
return false; |
| 9689 |
} |
| 9690 |
} |
| 9691 |
} else if (event.kind == JS::ExecutionTrace::EventKind::LabelEnter || |
| 9692 |
event.kind == JS::ExecutionTrace::EventKind::LabelLeave) { |
| 9693 |
str = JS_NewStringCopyUTF8Z( |
| 9694 |
cx, JS::ConstUTF8CharsZ(trace.stringBuffer.begin() + |
| 9695 |
event.labelEvent.label)); |
| 9696 |
if (!str) { |
| 9697 |
return false; |
| 9698 |
} |
| 9699 |
|
| 9700 |
if (!JS_DefinePropertyById(cx, eventObj, labelId, str, |
| 9701 |
JSPROP_ENUMERATE)) { |
| 9702 |
return false; |
| 9703 |
} |
| 9704 |
} |
| 9705 |
|
| 9706 |
if (event.kind != JS::ExecutionTrace::EventKind::Error) { |
| 9707 |
if (!JS_DefinePropertyById(cx, eventObj, timeId, event.time, |
| 9708 |
JSPROP_ENUMERATE)) { |
| 9709 |
return false; |
| 9710 |
} |
| 9711 |
} |
| 9712 |
|
| 9713 |
if (!NewbornArrayPush(cx, eventsArray, JS::ObjectValue(*eventObj))) { |
| 9714 |
return false; |
| 9715 |
} |
| 9716 |
} |
| 9717 |
|
| 9718 |
if (!JS_DefinePropertyById(cx, contextObj, eventsId, eventsArray, |
| 9719 |
JSPROP_ENUMERATE)) { |
| 9720 |
return false; |
| 9721 |
} |
| 9722 |
|
| 9723 |
if (!NewbornArrayPush(cx, traceArray, JS::ObjectValue(*contextObj))) { |
| 9724 |
return false; |
| 9725 |
} |
| 9726 |
} |
| 9727 |
|
| 9728 |
args.rval().setObject(*traceArray); |
| 9729 |
return true; |
| 9730 |
} |
| 9731 |
|
| 9732 |
static bool DisableExecutionTracing(JSContext* cx, unsigned argc, |
| 9733 |
JS::Value* vp) { |
| 9734 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 9735 |
|
| 9736 |
if (!JS_TracerEndTracing(cx)) { |
| 9737 |
return false; |
| 9738 |
} |
| 9739 |
|
| 9740 |
args.rval().setUndefined(); |
| 9741 |
return true; |
| 9742 |
} |
| 9743 |
|
| 9744 |
#endif // MOZ_EXECUTION_TRACING |
| 9745 |
|
| 9746 |
// clang-format off |
| 9747 |
static const JSFunctionSpecWithHelp shell_functions[] = { |
| 9748 |
JS_FN_HELP("options", Options, 0, 0, |
| 9749 |
"options([option ...])", |
| 9750 |
" Get or toggle JavaScript options."), |
| 9751 |
|
| 9752 |
JS_FN_HELP("load", Load, 1, 0, |
| 9753 |
"load(['foo.js' ...])", |
| 9754 |
" Load files named by string arguments. Filename is relative to the\n" |
| 9755 |
" current working directory."), |
| 9756 |
|
| 9757 |
JS_FN_HELP("loadRelativeToScript", LoadScriptRelativeToScript, 1, 0, |
| 9758 |
"loadRelativeToScript(['foo.js' ...])", |
| 9759 |
" Load files named by string arguments. Filename is relative to the\n" |
| 9760 |
" calling script."), |
| 9761 |
|
| 9762 |
JS_FN_HELP("evaluate", Evaluate, 2, 0, |
| 9763 |
"evaluate(code[, options])", |
| 9764 |
" Evaluate code as though it were the contents of a file.\n" |
| 9765 |
" options is an optional object that may have these properties:\n" |
| 9766 |
" isRunOnce: use the isRunOnce compiler option (default: false)\n" |
| 9767 |
" noScriptRval: use the no-script-rval compiler option (default: false)\n" |
| 9768 |
" fileName: filename for error messages and debug info\n" |
| 9769 |
" skipFileNameValidation: skip the filename-validation callback\n" |
| 9770 |
" lineNumber: starting line number for error messages and debug info\n" |
| 9771 |
" columnNumber: starting column number for error messages and debug info\n" |
| 9772 |
" global: global in which to execute the code\n" |
| 9773 |
" newContext: if true, create and use a new cx (default: false)\n" |
| 9774 |
" catchTermination: if true, catch termination (failure without\n" |
| 9775 |
" an exception value, as for slow scripts or out-of-memory)\n" |
| 9776 |
" and return 'terminated'\n" |
| 9777 |
" element: if present with value |v|, convert |v| to an object |o| and\n" |
| 9778 |
" mark the source as being attached to the DOM element |o|. If the\n" |
| 9779 |
" property is omitted or |v| is null, don't attribute the source to\n" |
| 9780 |
" any DOM element.\n" |
| 9781 |
" elementAttributeName: if present and not undefined, the name of\n" |
| 9782 |
" property of 'element' that holds this code. This is what\n" |
| 9783 |
" Debugger.Source.prototype.elementAttributeName returns.\n" |
| 9784 |
" sourceMapURL: if present with value |v|, convert |v| to a string, and\n" |
| 9785 |
" provide that as the code's source map URL. If omitted, attach no\n" |
| 9786 |
" source map URL to the code (although the code may provide one itself,\n" |
| 9787 |
" via a //#sourceMappingURL comment).\n" |
| 9788 |
" sourceIsLazy: if present and true, indicates that, after compilation, \n" |
| 9789 |
" script source should not be cached by the JS engine and should be \n" |
| 9790 |
" lazily loaded from the embedding as-needed.\n" |
| 9791 |
" forceFullParse: if present and true, disable syntax-parse.\n" |
| 9792 |
" loadBytecode: if true, and if the source is a CacheEntryObject,\n" |
| 9793 |
" the bytecode would be loaded and decoded from the cache entry instead\n" |
| 9794 |
" of being parsed, then it would be executed as usual.\n" |
| 9795 |
" saveBytecodeWithDelazifications: if true, and if the source is a\n" |
| 9796 |
" CacheEntryObject, the delazifications are collected during the\n" |
| 9797 |
" execution, and encoded after that, and saved into the cache entry.\n" |
| 9798 |
" execute: if false, do not execute the script, but do parse and/or\n" |
| 9799 |
" transcode.\n" |
| 9800 |
" assertEqBytecode: if true, and if both loadBytecode and either\n" |
| 9801 |
" saveBytecodeWithDelazifications is true, then the loaded\n" |
| 9802 |
" bytecode and the encoded bytecode are compared.\n" |
| 9803 |
" and an assertion is raised if they differ.\n" |
| 9804 |
" envChainObject: object to put on the scope chain, with its fields added\n" |
| 9805 |
" as var bindings, akin to how elements are added to the environment in\n" |
| 9806 |
" event handlers in Gecko.\n" |
| 9807 |
" supportUnscopables: if true, support Symbol.unscopables lookups for\n" |
| 9808 |
" envChainObject, similar to (syntactic) with-statements.\n" |
| 9809 |
), |
| 9810 |
|
| 9811 |
JS_FN_HELP("run", Run, 1, 0, |
| 9812 |
"run('foo.js')", |
| 9813 |
" Run the file named by the first argument, returning the number of\n" |
| 9814 |
" of milliseconds spent compiling and executing it."), |
| 9815 |
|
| 9816 |
JS_FN_HELP("readline", ReadLine, 0, 0, |
| 9817 |
"readline()", |
| 9818 |
" Read a single line from stdin."), |
| 9819 |
|
| 9820 |
JS_FN_HELP("readlineBuf", ReadLineBuf, 1, 0, |
| 9821 |
"readlineBuf([ buf ])", |
| 9822 |
" Emulate readline() on the specified string. The first call with a string\n" |
| 9823 |
" argument sets the source buffer. Subsequent calls without an argument\n" |
| 9824 |
" then read from this buffer line by line.\n"), |
| 9825 |
|
| 9826 |
JS_FN_HELP("print", Print, 0, 0, |
| 9827 |
"print([exp ...])", |
| 9828 |
" Evaluate and print expressions to stdout."), |
| 9829 |
|
| 9830 |
JS_FN_HELP("printErr", PrintErr, 0, 0, |
| 9831 |
"printErr([exp ...])", |
| 9832 |
" Evaluate and print expressions to stderr."), |
| 9833 |
|
| 9834 |
JS_FN_HELP("putstr", PutStr, 0, 0, |
| 9835 |
"putstr([exp])", |
| 9836 |
" Evaluate and print expression without newline."), |
| 9837 |
|
| 9838 |
JS_FN_HELP("dateNow", Now, 0, 0, |
| 9839 |
"dateNow()", |
| 9840 |
" Return the current time with sub-ms precision."), |
| 9841 |
|
| 9842 |
JS_FN_HELP("help", Help, 0, 0, |
| 9843 |
"help([function or interface object or /pattern/])", |
| 9844 |
" Display usage and help messages."), |
| 9845 |
|
| 9846 |
JS_FN_HELP("quit", Quit, 0, 0, |
| 9847 |
"quit()", |
| 9848 |
" Quit the shell."), |
| 9849 |
|
| 9850 |
JS_FN_HELP("assertEq", AssertEq, 2, 0, |
| 9851 |
"assertEq(actual, expected[, msg])", |
| 9852 |
" Throw if the first two arguments are not the same (both +0 or both -0,\n" |
| 9853 |
" both NaN, or non-zero and ===)."), |
| 9854 |
|
| 9855 |
JS_FN_HELP("startTimingMutator", StartTimingMutator, 0, 0, |
| 9856 |
"startTimingMutator()", |
| 9857 |
" Start accounting time to mutator vs GC."), |
| 9858 |
|
| 9859 |
JS_FN_HELP("stopTimingMutator", StopTimingMutator, 0, 0, |
| 9860 |
"stopTimingMutator()", |
| 9861 |
" Stop accounting time to mutator vs GC and dump the results."), |
| 9862 |
|
| 9863 |
JS_FN_HELP("throwError", ThrowError, 0, 0, |
| 9864 |
"throwError()", |
| 9865 |
" Throw an error from JS_ReportError."), |
| 9866 |
|
| 9867 |
JS_FN_HELP("createErrorReport", CreateErrorReport, 1, 0, |
| 9868 |
"createErrorReport(value)", |
| 9869 |
" Create an JS::ErrorReportBuilder object from the given value and serialize\n" |
| 9870 |
" to an object."), |
| 9871 |
|
| 9872 |
#if defined(DEBUG) || defined(JS_JITSPEW) |
| 9873 |
JS_FN_HELP("disassemble", DisassembleToString, 1, 0, |
| 9874 |
"disassemble([fun/code])", |
| 9875 |
" Return the disassembly for the given function or code.\n" |
| 9876 |
" All disassembly functions take these options as leading string arguments:\n" |
| 9877 |
" \"-r\" (disassemble recursively)\n" |
| 9878 |
" \"-l\" (show line numbers)\n" |
| 9879 |
" \"-S\" (omit source notes)"), |
| 9880 |
|
| 9881 |
JS_FN_HELP("dis", Disassemble, 1, 0, |
| 9882 |
"dis([fun/code])", |
| 9883 |
" Disassemble functions into bytecodes."), |
| 9884 |
|
| 9885 |
JS_FN_HELP("disfile", DisassFile, 1, 0, |
| 9886 |
"disfile('foo.js')", |
| 9887 |
" Disassemble script file into bytecodes.\n"), |
| 9888 |
|
| 9889 |
JS_FN_HELP("dissrc", DisassWithSrc, 1, 0, |
| 9890 |
"dissrc([fun/code])", |
| 9891 |
" Disassemble functions with source lines."), |
| 9892 |
|
| 9893 |
JS_FN_HELP("notes", Notes, 1, 0, |
| 9894 |
"notes([fun])", |
| 9895 |
" Show source notes for functions."), |
| 9896 |
|
| 9897 |
JS_FN_HELP("stackDump", StackDump, 3, 0, |
| 9898 |
"stackDump(showArgs, showLocals, showThisProps)", |
| 9899 |
" Tries to print a lot of information about the current stack. \n" |
| 9900 |
" Similar to the DumpJSStack() function in the browser."), |
| 9901 |
|
| 9902 |
#endif |
| 9903 |
|
| 9904 |
JS_FN_HELP("getslx", GetSLX, 1, 0, |
| 9905 |
"getslx(obj)", |
| 9906 |
" Get script line extent."), |
| 9907 |
|
| 9908 |
JS_FN_HELP("evalcx", EvalInContext, 1, 0, |
| 9909 |
"evalcx(s[, o])", |
| 9910 |
" Evaluate s in optional sandbox object o.\n" |
| 9911 |
" if (s == '' && !o) return new o with eager standard classes\n" |
| 9912 |
" if (s == 'lazy' && !o) return new o with lazy standard classes"), |
| 9913 |
|
| 9914 |
JS_FN_HELP("evalInWorker", EvalInWorker, 1, 0, |
| 9915 |
"evalInWorker(str)", |
| 9916 |
" Evaluate 'str' in a separate thread with its own runtime.\n"), |
| 9917 |
|
| 9918 |
JS_FN_HELP("getSharedObject", GetSharedObject, 0, 0, |
| 9919 |
"getSharedObject()", |
| 9920 |
" Retrieve the shared object from the cross-worker mailbox.\n" |
| 9921 |
" The object retrieved may not be identical to the object that was\n" |
| 9922 |
" installed, but it references the same shared memory.\n" |
| 9923 |
" getSharedObject performs an ordering memory barrier.\n"), |
| 9924 |
|
| 9925 |
JS_FN_HELP("setSharedObject", SetSharedObject, 0, 0, |
| 9926 |
"setSharedObject(obj)", |
| 9927 |
" Install the shared object in the cross-worker mailbox. The object\n" |
| 9928 |
" may be null. setSharedObject performs an ordering memory barrier.\n"), |
| 9929 |
|
| 9930 |
JS_FN_HELP("getSharedArrayBuffer", GetSharedObject, 0, 0, |
| 9931 |
"getSharedArrayBuffer()", |
| 9932 |
" Obsolete alias for getSharedObject().\n"), |
| 9933 |
|
| 9934 |
JS_FN_HELP("setSharedArrayBuffer", SetSharedObject, 0, 0, |
| 9935 |
"setSharedArrayBuffer(obj)", |
| 9936 |
" Obsolete alias for setSharedObject(obj).\n"), |
| 9937 |
|
| 9938 |
JS_FN_HELP("shapeOf", ShapeOf, 1, 0, |
| 9939 |
"shapeOf(obj)", |
| 9940 |
" Get the shape of obj (an implementation detail)."), |
| 9941 |
|
| 9942 |
#ifdef DEBUG |
| 9943 |
JS_FN_HELP("arrayInfo", ArrayInfo, 1, 0, |
| 9944 |
"arrayInfo(a1, a2, ...)", |
| 9945 |
" Report statistics about arrays."), |
| 9946 |
#endif |
| 9947 |
|
| 9948 |
JS_FN_HELP("sleep", Sleep_fn, 1, 0, |
| 9949 |
"sleep(dt)", |
| 9950 |
" Sleep for dt seconds."), |
| 9951 |
|
| 9952 |
JS_FN_HELP("parseModule", ParseModule, 3, 0, |
| 9953 |
"parseModule(code, 'filename', 'js' | 'json')", |
| 9954 |
" Parses source text as a JS module ('js', this is the default) or a JSON" |
| 9955 |
" module ('json') and returns a ModuleObject wrapper object."), |
| 9956 |
|
| 9957 |
JS_FN_HELP("instantiateModuleStencil", InstantiateModuleStencil, 1, 0, |
| 9958 |
"instantiateModuleStencil(stencil, [options])", |
| 9959 |
" Instantiates the given stencil as module, and return the module object."), |
| 9960 |
|
| 9961 |
JS_FN_HELP("instantiateModuleStencilXDR", InstantiateModuleStencilXDR, 1, 0, |
| 9962 |
"instantiateModuleStencilXDR(stencil, [options])", |
| 9963 |
" Reads the given stencil XDR object, instantiates the stencil as module, and" |
| 9964 |
" return the module object."), |
| 9965 |
|
| 9966 |
JS_FN_HELP("registerModule", RegisterModule, 2, 0, |
| 9967 |
"registerModule(specifier, module)", |
| 9968 |
" Register a module with the module loader, so that subsequent import from\n" |
| 9969 |
" |specifier| will resolve to |module|. Returns |module|."), |
| 9970 |
|
| 9971 |
JS_FN_HELP("clearModules", ClearModules, 0, 0, |
| 9972 |
"clearModules()", |
| 9973 |
" Clear knowledge of all loaded modules."), |
| 9974 |
|
| 9975 |
JS_FN_HELP("moduleLink", ModuleLink, 1, 0, |
| 9976 |
"moduleLink(moduleOjbect)", |
| 9977 |
" Link a module graph, performing the spec's Link method."), |
| 9978 |
|
| 9979 |
JS_FN_HELP("moduleEvaluate", ModuleEvaluate, 1, 0, |
| 9980 |
"moduleEvaluate(moduleOjbect)", |
| 9981 |
" Evaluate a module graph, performing the spec's Evaluate method."), |
| 9982 |
|
| 9983 |
JS_FN_HELP("getModuleEnvironmentNames", GetModuleEnvironmentNames, 1, 0, |
| 9984 |
"getModuleEnvironmentNames(module)", |
| 9985 |
" Get the list of a module environment's bound names for a specified module.\n"), |
| 9986 |
|
| 9987 |
JS_FN_HELP("getModuleEnvironmentValue", GetModuleEnvironmentValue, 2, 0, |
| 9988 |
"getModuleEnvironmentValue(module, name)", |
| 9989 |
" Get the value of a bound name in a module environment.\n"), |
| 9990 |
|
| 9991 |
JS_FN_HELP("dumpStencil", DumpStencil, 1, 0, |
| 9992 |
"dumpStencil(code, [options])", |
| 9993 |
" Parses a string and returns string that represents stencil.\n" |
| 9994 |
" If present, |options| may have properties saying how the code should be\n" |
| 9995 |
" compiled:\n" |
| 9996 |
" module: if present and true, compile the source as module.\n" |
| 9997 |
" CompileOptions-related properties of evaluate function's option can also\n" |
| 9998 |
" be used."), |
| 9999 |
|
| 10000 |
JS_FN_HELP("parse", Parse, 1, 0, |
| 10001 |
"parse(code, [options])", |
| 10002 |
" Parses a string, potentially throwing. If present, |options| may\n" |
| 10003 |
" have properties saying how the code should be compiled:\n" |
| 10004 |
" module: if present and true, compile the source as module.\n" |
| 10005 |
" CompileOptions-related properties of evaluate function's option can also\n" |
| 10006 |
" be used. except forceFullParse. This function always use full parse."), |
| 10007 |
|
| 10008 |
JS_FN_HELP("syntaxParse", SyntaxParse, 1, 0, |
| 10009 |
"syntaxParse(code)", |
| 10010 |
" Check the syntax of a string, returning success value"), |
| 10011 |
|
| 10012 |
JS_FN_HELP("offThreadCompileModuleToStencil", OffThreadCompileModuleToStencil, 1, 0, |
| 10013 |
"offThreadCompileModuleToStencil(code[, options])", |
| 10014 |
" Compile |code| on a helper thread, returning a job ID. To wait for the\n" |
| 10015 |
" compilation to finish and and get the module stencil object call\n" |
| 10016 |
" |finishOffThreadStencil| passing the job ID."), |
| 10017 |
|
| 10018 |
JS_FN_HELP("offThreadDecodeStencil", OffThreadDecodeStencil, 1, 0, |
| 10019 |
"offThreadDecodeStencil(cacheEntry[, options])", |
| 10020 |
" Decode |code| on a helper thread, returning a job ID. To wait for the\n" |
| 10021 |
" decoding to finish and run the code, call |finishOffThreadStencil| passing\n" |
| 10022 |
" the job ID. If present, |options| may have properties saying how the code\n" |
| 10023 |
" should be compiled (see also offThreadCompileToStencil)."), |
| 10024 |
|
| 10025 |
JS_FN_HELP("offThreadCompileToStencil", OffThreadCompileToStencil, 1, 0, |
| 10026 |
"offThreadCompileToStencil(code[, options])", |
| 10027 |
" Compile |code| on a helper thread, returning a job ID. To wait for the\n" |
| 10028 |
" compilation to finish and get the stencil object, call\n" |
| 10029 |
" |finishOffThreadStencil| passing the job ID. If present, \n" |
| 10030 |
" |options| may have properties saying how the code should be compiled:\n" |
| 10031 |
" noScriptRval: use the no-script-rval compiler option (default: false)\n" |
| 10032 |
" fileName: filename for error messages and debug info\n" |
| 10033 |
" lineNumber: starting line number for error messages and debug info\n" |
| 10034 |
" columnNumber: starting column number for error messages and debug info\n" |
| 10035 |
" element: if present with value |v|, convert |v| to an object |o| and\n" |
| 10036 |
" mark the source as being attached to the DOM element |o|. If the\n" |
| 10037 |
" property is omitted or |v| is null, don't attribute the source to\n" |
| 10038 |
" any DOM element.\n" |
| 10039 |
" elementAttributeName: if present and not undefined, the name of\n" |
| 10040 |
" property of 'element' that holds this code. This is what\n" |
| 10041 |
" Debugger.Source.prototype.elementAttributeName returns."), |
| 10042 |
|
| 10043 |
JS_FN_HELP("finishOffThreadStencil", FinishOffThreadStencil, 0, 0, |
| 10044 |
"finishOffThreadStencil([jobID])", |
| 10045 |
" Wait for an off-thread compilation or decode job to complete. The job ID\n" |
| 10046 |
" can be ommitted if there is only one job pending. If an error occurred,\n" |
| 10047 |
" throw the appropriate exception; otherwise, return the stencil object," |
| 10048 |
" that can be passed to |evalStencil|."), |
| 10049 |
|
| 10050 |
JS_FN_HELP("timeout", Timeout, 1, 0, |
| 10051 |
"timeout([seconds], [func])", |
| 10052 |
" Get/Set the limit in seconds for the execution time for the current context.\n" |
| 10053 |
" When the timeout expires the current interrupt callback is invoked.\n" |
| 10054 |
" The timeout is used just once. If the callback returns a falsy value, the\n" |
| 10055 |
" script is aborted. A negative value for seconds (this is the default) cancels\n" |
| 10056 |
" any pending timeout.\n" |
| 10057 |
" If a second argument is provided, it is installed as the interrupt handler,\n" |
| 10058 |
" exactly as if by |setInterruptCallback|.\n"), |
| 10059 |
|
| 10060 |
JS_FN_HELP("interruptIf", InterruptIf, 1, 0, |
| 10061 |
"interruptIf(cond)", |
| 10062 |
" Requests interrupt callback if cond is true. If a callback function is set via\n" |
| 10063 |
" |timeout| or |setInterruptCallback|, it will be called. No-op otherwise."), |
| 10064 |
|
| 10065 |
JS_FN_HELP("invokeInterruptCallback", InvokeInterruptCallbackWrapper, 0, 0, |
| 10066 |
"invokeInterruptCallback(fun)", |
| 10067 |
" Forcefully set the interrupt flag and invoke the interrupt handler. If a\n" |
| 10068 |
" callback function is set via |timeout| or |setInterruptCallback|, it will\n" |
| 10069 |
" be called. Before returning, fun is called with the return value of the\n" |
| 10070 |
" interrupt handler."), |
| 10071 |
|
| 10072 |
JS_FN_HELP("setInterruptCallback", SetInterruptCallback, 1, 0, |
| 10073 |
"setInterruptCallback(func)", |
| 10074 |
" Sets func as the interrupt callback function.\n" |
| 10075 |
" Calling this function will replace any callback set by |timeout|.\n" |
| 10076 |
" If the callback returns a falsy value, the script is aborted.\n"), |
| 10077 |
|
| 10078 |
JS_FN_HELP("setPrefValue", SetPrefValue, 2, 0, |
| 10079 |
"setPrefValue(name, value)", |
| 10080 |
" Set the value of the JS pref with the given name."), |
| 10081 |
|
| 10082 |
JS_FN_HELP("setJitCompilerOption", SetJitCompilerOption, 2, 0, |
| 10083 |
"setJitCompilerOption(<option>, <number>)", |
| 10084 |
" Set a compiler option indexed in JSCompileOption enum to a number.\n"), |
| 10085 |
|
| 10086 |
#ifdef DEBUG |
| 10087 |
JS_FN_HELP("interruptRegexp", InterruptRegexp, 2, 0, |
| 10088 |
"interruptRegexp(<regexp>, <string>)", |
| 10089 |
" Interrrupt the execution of regular expression.\n"), |
| 10090 |
#endif |
| 10091 |
JS_FN_HELP("checkRegExpSyntax", CheckRegExpSyntax, 1, 0, |
| 10092 |
"checkRegExpSyntax(<string>)", |
| 10093 |
" Return undefined if the string parses as a RegExp. If the string does not\n" |
| 10094 |
" parse correctly, return the SyntaxError that occurred."), |
| 10095 |
|
| 10096 |
JS_FN_HELP("enableLastWarning", EnableLastWarning, 0, 0, |
| 10097 |
"enableLastWarning()", |
| 10098 |
" Enable storing the last warning."), |
| 10099 |
JS_FN_HELP("disableLastWarning", DisableLastWarning, 0, 0, |
| 10100 |
"disableLastWarning()", |
| 10101 |
" Disable storing the last warning."), |
| 10102 |
|
| 10103 |
JS_FN_HELP("getLastWarning", GetLastWarning, 0, 0, |
| 10104 |
"getLastWarning()", |
| 10105 |
" Returns an object that represents the last warning."), |
| 10106 |
|
| 10107 |
JS_FN_HELP("clearLastWarning", ClearLastWarning, 0, 0, |
| 10108 |
"clearLastWarning()", |
| 10109 |
" Clear the last warning."), |
| 10110 |
|
| 10111 |
JS_FN_HELP("elapsed", Elapsed, 0, 0, |
| 10112 |
"elapsed()", |
| 10113 |
" Execution time elapsed for the current thread."), |
| 10114 |
|
| 10115 |
JS_FN_HELP("decompileFunction", DecompileFunction, 1, 0, |
| 10116 |
"decompileFunction(func)", |
| 10117 |
" Decompile a function."), |
| 10118 |
|
| 10119 |
JS_FN_HELP("decompileThis", DecompileThisScript, 0, 0, |
| 10120 |
"decompileThis()", |
| 10121 |
" Decompile the currently executing script."), |
| 10122 |
|
| 10123 |
JS_FN_HELP("valueToSource", ValueToSource, 1, 0, |
| 10124 |
"valueToSource(value)", |
| 10125 |
" Format a value for inspection."), |
| 10126 |
|
| 10127 |
JS_FN_HELP("thisFilename", ThisFilename, 0, 0, |
| 10128 |
"thisFilename()", |
| 10129 |
" Return the filename of the current script"), |
| 10130 |
|
| 10131 |
JS_FN_HELP("newGlobal", NewGlobal, 1, 0, |
| 10132 |
"newGlobal([options])", |
| 10133 |
" Return a new global object/realm. The new global is created in the\n" |
| 10134 |
" 'newGlobal' function object's compartment and zone, unless the\n" |
| 10135 |
" '--more-compartments' command-line flag was given, in which case new\n" |
| 10136 |
" globals get a fresh compartment and zone. If options is given, it may\n" |
| 10137 |
" have any of the following properties:\n" |
| 10138 |
" sameCompartmentAs: If an object, the global will be in the same\n" |
| 10139 |
" compartment and zone as the given object.\n" |
| 10140 |
" sameZoneAs: The global will be in a new compartment in the same zone\n" |
| 10141 |
" as the given object.\n" |
| 10142 |
" newCompartment: If true, the global will always be created in a new\n" |
| 10143 |
" compartment and zone.\n" |
| 10144 |
" invisibleToDebugger: If true, the global will be invisible to the\n" |
| 10145 |
" debugger (default false)\n" |
| 10146 |
" discardSource: If true, discard source after compiling a script\n" |
| 10147 |
" (default false).\n" |
| 10148 |
" useWindowProxy: the global will be created with a WindowProxy attached. In this\n" |
| 10149 |
" case, the WindowProxy will be returned.\n" |
| 10150 |
" freezeBuiltins: certain builtin constructors will be frozen when created and\n" |
| 10151 |
" their prototypes will be sealed. These constructors will be defined on the\n" |
| 10152 |
" global as non-configurable and non-writable.\n" |
| 10153 |
" immutablePrototype: whether the global's prototype is immutable.\n" |
| 10154 |
" principal: if present, its value converted to a number must be an\n" |
| 10155 |
" integer that fits in 32 bits; use that as the new realm's\n" |
| 10156 |
" principal. Shell principals are toys, meant only for testing; one\n" |
| 10157 |
" shell principal subsumes another if its set bits are a superset of\n" |
| 10158 |
" the other's. Thus, a principal of 0 subsumes nothing, while a\n" |
| 10159 |
" principals of ~0 subsumes all other principals. The absence of a\n" |
| 10160 |
" principal is treated as if its bits were 0xffff, for subsumption\n" |
| 10161 |
" purposes. If this property is omitted, supply no principal.\n" |
| 10162 |
" systemPrincipal: If true, use the shell's trusted principals for the\n" |
| 10163 |
" new realm. This creates a realm that's marked as a 'system' realm."), |
| 10164 |
|
| 10165 |
JS_FN_HELP("nukeAllCCWs", NukeAllCCWs, 0, 0, |
| 10166 |
"nukeAllCCWs()", |
| 10167 |
" Like nukeCCW, but for all CrossCompartmentWrappers targeting the current realm."), |
| 10168 |
|
| 10169 |
JS_FN_HELP("recomputeWrappers", RecomputeWrappers, 2, 0, |
| 10170 |
"recomputeWrappers([src, [target]])", |
| 10171 |
" Recompute all cross-compartment wrappers. src and target are both optional\n" |
| 10172 |
" and can be used to filter source or target compartments: the unwrapped\n" |
| 10173 |
" object's compartment is used as CompartmentFilter.\n"), |
| 10174 |
|
| 10175 |
JS_FN_HELP("dumpObjectWrappers", DumpObjectWrappers, 2, 0, |
| 10176 |
"dumpObjectWrappers()", |
| 10177 |
" Print information about cross-compartment object wrappers.\n"), |
| 10178 |
|
| 10179 |
JS_FN_HELP("wrapWithProto", WrapWithProto, 2, 0, |
| 10180 |
"wrapWithProto(obj)", |
| 10181 |
" Wrap an object into a noop wrapper with prototype semantics."), |
| 10182 |
|
| 10183 |
JS_FN_HELP("createExternalArrayBuffer", CreateExternalArrayBuffer, 1, 0, |
| 10184 |
"createExternalArrayBuffer(size)", |
| 10185 |
" Create an array buffer that has external data of size."), |
| 10186 |
|
| 10187 |
JS_FN_HELP("createMappedArrayBuffer", CreateMappedArrayBuffer, 1, 0, |
| 10188 |
"createMappedArrayBuffer(filename, [offset, [size]])", |
| 10189 |
" Create an array buffer that mmaps the given file."), |
| 10190 |
|
| 10191 |
JS_FN_HELP("createUserArrayBuffer", CreateUserArrayBuffer, 1, 0, |
| 10192 |
"createUserArrayBuffer(size)", |
| 10193 |
" Create an array buffer that uses user-controlled memory."), |
| 10194 |
|
| 10195 |
JS_FN_HELP("addPromiseReactions", AddPromiseReactions, 3, 0, |
| 10196 |
"addPromiseReactions(promise, onResolve, onReject)", |
| 10197 |
" Calls the JS::AddPromiseReactions JSAPI function with the given arguments."), |
| 10198 |
|
| 10199 |
JS_FN_HELP("ignoreUnhandledRejections", IgnoreUnhandledRejections, 0, 0, |
| 10200 |
"ignoreUnhandledRejections()", |
| 10201 |
" By default, js shell tracks unhandled promise rejections and reports\n" |
| 10202 |
" them at the end of the exectuion. If a testcase isn't interested\n" |
| 10203 |
" in those rejections, call this to stop tracking and reporting."), |
| 10204 |
|
| 10205 |
JS_FN_HELP("getMaxArgs", GetMaxArgs, 0, 0, |
| 10206 |
"getMaxArgs()", |
| 10207 |
" Return the maximum number of supported args for a call."), |
| 10208 |
|
| 10209 |
JS_FN_HELP("createIsHTMLDDA", CreateIsHTMLDDA, 0, 0, |
| 10210 |
"createIsHTMLDDA()", |
| 10211 |
" Return an object |obj| that \"looks like\" the |document.all| object in\n" |
| 10212 |
" browsers in certain ways: |typeof obj === \"undefined\"|, |obj == null|\n" |
| 10213 |
" and |obj == undefined| (vice versa for !=), |ToBoolean(obj) === false|,\n" |
| 10214 |
" and when called with no arguments or the single argument \"\" returns\n" |
| 10215 |
" null. (Calling |obj| any other way crashes or throws an exception.)\n" |
| 10216 |
" This function implements the exact requirements of the $262.IsHTMLDDA\n" |
| 10217 |
" property in test262."), |
| 10218 |
|
| 10219 |
JS_FN_HELP("cacheEntry", CacheEntry, 1, 0, |
| 10220 |
"cacheEntry(code)", |
| 10221 |
" Return a new opaque object which emulates a cache entry of a script. This\n" |
| 10222 |
" object encapsulates the code and its cached content. The cache entry is filled\n" |
| 10223 |
" and read by the \"evaluate\" function by using it in place of the source, and\n" |
| 10224 |
" by setting \"saveBytecodeWithDelazifications\" and \"loadBytecode\" options."), |
| 10225 |
|
| 10226 |
JS_FN_HELP("streamCacheEntry", StreamCacheEntryObject::construct, 1, 0, |
| 10227 |
"streamCacheEntry(buffer)", |
| 10228 |
" Create a shell-only object that holds wasm bytecode and can be streaming-\n" |
| 10229 |
" compiled and cached by WebAssembly.{compile,instantiate}Streaming(). On a\n" |
| 10230 |
" second compilation of the same cache entry, the cached code will be used."), |
| 10231 |
|
| 10232 |
JS_FN_HELP("printProfilerEvents", PrintProfilerEvents, 0, 0, |
| 10233 |
"printProfilerEvents()", |
| 10234 |
" Register a callback with the profiler that prints javascript profiler events\n" |
| 10235 |
" to stderr. Callback is only registered if profiling is enabled."), |
| 10236 |
|
| 10237 |
JS_FN_HELP("enableSingleStepProfiling", EnableSingleStepProfiling, 0, 0, |
| 10238 |
"enableSingleStepProfiling()", |
| 10239 |
" This function will fail on platforms that don't support single-step profiling\n" |
| 10240 |
" (currently ARM and MIPS64 support it). When enabled, at every instruction a\n" |
| 10241 |
" backtrace will be recorded and stored in an array. Adjacent duplicate backtraces\n" |
| 10242 |
" are discarded."), |
| 10243 |
|
| 10244 |
JS_FN_HELP("disableSingleStepProfiling", DisableSingleStepProfiling, 0, 0, |
| 10245 |
"disableSingleStepProfiling()", |
| 10246 |
" Return the array of backtraces recorded by enableSingleStepProfiling."), |
| 10247 |
|
| 10248 |
JS_FN_HELP("enableGeckoProfiling", EnableGeckoProfiling, 0, 0, |
| 10249 |
"enableGeckoProfiling()", |
| 10250 |
" Enables Gecko Profiler instrumentation and corresponding assertions, with slow\n" |
| 10251 |
" assertions disabled.\n"), |
| 10252 |
|
| 10253 |
JS_FN_HELP("enableGeckoProfilingWithSlowAssertions", EnableGeckoProfilingWithSlowAssertions, 0, 0, |
| 10254 |
"enableGeckoProfilingWithSlowAssertions()", |
| 10255 |
" Enables Gecko Profiler instrumentation and corresponding assertions, with slow\n" |
| 10256 |
" assertions enabled.\n"), |
| 10257 |
|
| 10258 |
JS_FN_HELP("disableGeckoProfiling", DisableGeckoProfiling, 0, 0, |
| 10259 |
"disableGeckoProfiling()", |
| 10260 |
" Disables Gecko Profiler instrumentation"), |
| 10261 |
|
| 10262 |
JS_FN_HELP("isLatin1", IsLatin1, 1, 0, |
| 10263 |
"isLatin1(s)", |
| 10264 |
" Return true iff the string's characters are stored as Latin1."), |
| 10265 |
|
| 10266 |
JS_FN_HELP("stackPointerInfo", StackPointerInfo, 0, 0, |
| 10267 |
"stackPointerInfo()", |
| 10268 |
" Return an int32 value which corresponds to the offset of the latest stack\n" |
| 10269 |
" pointer, such that one can take the differences of 2 to estimate a frame-size."), |
| 10270 |
|
| 10271 |
JS_FN_HELP("enqueueJob", EnqueueJob, 1, 0, |
| 10272 |
"enqueueJob(fn)", |
| 10273 |
" Enqueue 'fn' on the shell's job queue."), |
| 10274 |
|
| 10275 |
JS_FN_HELP("globalOfFirstJobInQueue", GlobalOfFirstJobInQueue, 0, 0, |
| 10276 |
"globalOfFirstJobInQueue()", |
| 10277 |
" Returns the global of the first item in the job queue. Throws an exception\n" |
| 10278 |
" if the queue is empty.\n"), |
| 10279 |
|
| 10280 |
JS_FN_HELP("drainJobQueue", DrainJobQueue, 0, 0, |
| 10281 |
"drainJobQueue()", |
| 10282 |
"Take jobs from the shell's job queue in FIFO order and run them until the\n" |
| 10283 |
"queue is empty.\n"), |
| 10284 |
|
| 10285 |
JS_FN_HELP("setPromiseRejectionTrackerCallback", SetPromiseRejectionTrackerCallback, 1, 0, |
| 10286 |
"setPromiseRejectionTrackerCallback()", |
| 10287 |
"Sets the callback to be invoked whenever a Promise rejection is unhandled\n" |
| 10288 |
"or a previously-unhandled rejection becomes handled."), |
| 10289 |
|
| 10290 |
JS_FN_HELP("dumpScopeChain", DumpScopeChain, 1, 0, |
| 10291 |
"dumpScopeChain(obj)", |
| 10292 |
" Prints the scope chain of an interpreted function or a module."), |
| 10293 |
|
| 10294 |
JS_FN_HELP("blackRoot", EnsureBlackRoot, 0, 0, |
| 10295 |
"blackRoot()", |
| 10296 |
" Return an array in the current compartment whose elements will be marked\n" |
| 10297 |
" as black roots by the GC."), |
| 10298 |
|
| 10299 |
JS_FN_HELP("grayRoot", EnsureGrayRoot, 0, 0, |
| 10300 |
"grayRoot()", |
| 10301 |
" Return an array in the current compartment whose elements will be marked\n" |
| 10302 |
" as gray roots by the GC."), |
| 10303 |
|
| 10304 |
JS_FN_HELP("addMarkObservers", AddMarkObservers, 1, 0, |
| 10305 |
"addMarkObservers(array_of_objects)", |
| 10306 |
" Register an array of objects whose mark bits will be tested by calls to\n" |
| 10307 |
" getMarks. The objects will be in calling compartment. Objects from\n" |
| 10308 |
" multiple compartments may be monitored by calling this function in\n" |
| 10309 |
" different compartments."), |
| 10310 |
|
| 10311 |
JS_FN_HELP("clearMarkObservers", ClearMarkObservers, 1, 0, |
| 10312 |
"clearMarkObservers()", |
| 10313 |
" Clear out the list of objects whose mark bits will be tested.\n"), |
| 10314 |
|
| 10315 |
JS_FN_HELP("getMarks", GetMarks, 0, 0, |
| 10316 |
"getMarks()", |
| 10317 |
" Return an array of strings representing the current state of the mark\n" |
| 10318 |
" bits ('gray' or 'black', or 'dead' if the object has been collected)\n" |
| 10319 |
" for the objects registered via addMarkObservers. Note that some of the\n" |
| 10320 |
" objects tested may be from different compartments than the one in which\n" |
| 10321 |
" this function runs."), |
| 10322 |
|
| 10323 |
JS_FN_HELP("bindToAsyncStack", BindToAsyncStack, 2, 0, |
| 10324 |
"bindToAsyncStack(fn, { stack, cause, explicit })", |
| 10325 |
" Returns a new function that calls 'fn' with no arguments, passing\n" |
| 10326 |
" 'undefined' as the 'this' value, and supplies an async stack for the\n" |
| 10327 |
" call as described by the second argument, an object with the following\n" |
| 10328 |
" properties (which are not optional, unless specified otherwise):\n" |
| 10329 |
"\n" |
| 10330 |
" stack: A SavedFrame object, like that returned by 'saveStack'. Stacks\n" |
| 10331 |
" captured during calls to the returned function capture this as\n" |
| 10332 |
" their async stack parent, accessible via a SavedFrame's\n" |
| 10333 |
" 'asyncParent' property.\n" |
| 10334 |
"\n" |
| 10335 |
" cause: A string, supplied as the async cause on the top frame of\n" |
| 10336 |
" captured async stacks.\n" |
| 10337 |
"\n" |
| 10338 |
" explicit: A boolean value, indicating whether the given 'stack' should\n" |
| 10339 |
" always supplant the returned function's true callers (true),\n" |
| 10340 |
" or only when there are no other JavaScript frames on the stack\n" |
| 10341 |
" below it (false). If omitted, this is treated as 'true'."), |
| 10342 |
|
| 10343 |
#ifndef __wasi__ |
| 10344 |
JS_FN_HELP("wasmCompileInSeparateProcess", WasmCompileInSeparateProcess, 1, 0, |
| 10345 |
"wasmCompileInSeparateProcess(buffer)", |
| 10346 |
" Compile the given buffer in a separate process, serialize the resulting\n" |
| 10347 |
" wasm::Module into bytes, and deserialize those bytes in the current\n" |
| 10348 |
" process, returning the resulting WebAssembly.Module."), |
| 10349 |
|
| 10350 |
JS_FN_HELP("wasmTextToBinary", WasmTextToBinary, 1, 0, |
| 10351 |
"wasmTextToBinary(str)", |
| 10352 |
" Translates the given text wasm module into its binary encoding."), |
| 10353 |
#endif // __wasi__ |
| 10354 |
|
| 10355 |
JS_FN_HELP("transplantableObject", TransplantableObject, 0, 0, |
| 10356 |
"transplantableObject([options])", |
| 10357 |
" Returns the pair {object, transplant}. |object| is an object which can be\n" |
| 10358 |
" transplanted into a new object when the |transplant| function, which must\n" |
| 10359 |
" be invoked with a global object, is called.\n" |
| 10360 |
" |object| is swapped with a cross-compartment wrapper if the global object\n" |
| 10361 |
" is in a different compartment.\n" |
| 10362 |
"\n" |
| 10363 |
" If options is given, it may have any of the following properties:\n" |
| 10364 |
" proxy: Create a DOM Proxy object instead of a plain DOM object.\n" |
| 10365 |
" object: Don't create a new DOM object, but instead use the supplied\n" |
| 10366 |
" FakeDOMObject."), |
| 10367 |
|
| 10368 |
JS_FN_HELP("cpuNow", CpuNow, /* nargs= */ 0, /* flags = */ 0, |
| 10369 |
"cpuNow()", |
| 10370 |
" Returns the approximate processor time used by the process since an arbitrary epoch, in seconds.\n" |
| 10371 |
" Only the difference between two calls to `cpuNow()` is meaningful."), |
| 10372 |
|
| 10373 |
#ifdef FUZZING_JS_FUZZILLI |
| 10374 |
JS_FN_HELP("fuzzilli", Fuzzilli, 0, 0, |
| 10375 |
"fuzzilli(operation, arg)", |
| 10376 |
" Exposes functionality used by the Fuzzilli JavaScript fuzzer."), |
| 10377 |
#endif |
| 10378 |
|
| 10379 |
#ifdef FUZZING_INTERFACES |
| 10380 |
JS_FN_HELP("getWasmSmithModule", GetWasmSmithModule, 1, 0, |
| 10381 |
"getWasmSmithModule(arrayBuffer)", |
| 10382 |
" Call wasm-smith to generate a random wasm module from the provided data."), |
| 10383 |
#endif |
| 10384 |
|
| 10385 |
JS_FN_HELP("isValidJSON", IsValidJSON, 1, 0, |
| 10386 |
"isValidJSON(source)", |
| 10387 |
" Returns true if the given source is valid JSON."), |
| 10388 |
|
| 10389 |
JS_FN_HELP("compressLZ4", CompressLZ4, 1, 0, |
| 10390 |
"compressLZ4(bytes)", |
| 10391 |
" Return a compressed copy of bytes using LZ4."), |
| 10392 |
|
| 10393 |
JS_FN_HELP("decompressLZ4", DecompressLZ4, 1, 0, |
| 10394 |
"decompressLZ4(bytes)", |
| 10395 |
" Return a decompressed copy of bytes using LZ4."), |
| 10396 |
|
| 10397 |
JS_FN_HELP("createSideEffectfulResolveObject", CreateSideEffectfulResolveObject, 0, 0, |
| 10398 |
"createSideEffectfulResolveObject()", |
| 10399 |
" Return an object with a property 'obj.test == 42', backed by a resolve hook " |
| 10400 |
" with the Debugger shouldAvoidSideEffects flag integration."), |
| 10401 |
|
| 10402 |
JS_FN_HELP("getUseCounterResults", GetUseCounterResults, 0, 0, |
| 10403 |
"getUseCounterResults()", |
| 10404 |
" Return the values of the shell use counters."), |
| 10405 |
|
| 10406 |
JS_FS_HELP_END |
| 10407 |
}; |
| 10408 |
// clang-format on |
| 10409 |
|
| 10410 |
// clang-format off |
| 10411 |
#ifdef FUZZING_JS_FUZZILLI |
| 10412 |
static const JSFunctionSpec shell_function_fuzzilli_hash[] = { |
| 10413 |
JS_INLINABLE_FN("fuzzilli_hash", fuzzilli_hash, 1, 0, FuzzilliHash), |
| 10414 |
JS_FS_END, |
| 10415 |
}; |
| 10416 |
#endif |
| 10417 |
// clang-format on |
| 10418 |
|
| 10419 |
// clang-format off |
| 10420 |
static const JSFunctionSpecWithHelp diff_testing_unsafe_functions[] = { |
| 10421 |
|
| 10422 |
JS_FS_HELP_END |
| 10423 |
}; |
| 10424 |
// clang-format on |
| 10425 |
|
| 10426 |
// clang-format off |
| 10427 |
static const JSFunctionSpecWithHelp fuzzing_unsafe_functions[] = { |
| 10428 |
JS_FN_HELP("getSelfHostedValue", GetSelfHostedValue, 1, 0, |
| 10429 |
"getSelfHostedValue()", |
| 10430 |
" Get a self-hosted value by its name. Note that these values don't get \n" |
| 10431 |
" cached, so repeatedly getting the same value creates multiple distinct clones."), |
| 10432 |
|
| 10433 |
JS_FN_HELP("line2pc", LineToPC, 0, 0, |
| 10434 |
"line2pc([fun,] line)", |
| 10435 |
" Map line number to PC."), |
| 10436 |
|
| 10437 |
JS_FN_HELP("pc2line", PCToLine, 0, 0, |
| 10438 |
"pc2line(fun[, pc])", |
| 10439 |
" Map PC to line number."), |
| 10440 |
|
| 10441 |
JS_INLINABLE_FN_HELP("assertFloat32", testingFunc_assertFloat32, 2, 0, TestAssertFloat32, |
| 10442 |
"assertFloat32(value, isFloat32)", |
| 10443 |
" In IonMonkey only, asserts that value has (resp. hasn't) the MIRType::Float32 if isFloat32 is true (resp. false)."), |
| 10444 |
|
| 10445 |
JS_INLINABLE_FN_HELP("assertRecoveredOnBailout", testingFunc_assertRecoveredOnBailout, 2, 0, |
| 10446 |
TestAssertRecoveredOnBailout, |
| 10447 |
"assertRecoveredOnBailout(var)", |
| 10448 |
" In IonMonkey only, asserts that variable has RecoveredOnBailout flag."), |
| 10449 |
|
| 10450 |
JS_FN_HELP("withSourceHook", WithSourceHook, 1, 0, |
| 10451 |
"withSourceHook(hook, fun)", |
| 10452 |
" Set this JS runtime's lazy source retrieval hook (that is, the hook\n" |
| 10453 |
" used to find sources compiled with |CompileOptions::LAZY_SOURCE|) to\n" |
| 10454 |
" |hook|; call |fun| with no arguments; and then restore the runtime's\n" |
| 10455 |
" original hook. Return or throw whatever |fun| did. |hook| gets\n" |
| 10456 |
" passed the requested code's URL, and should return a string.\n" |
| 10457 |
"\n" |
| 10458 |
" Notes:\n" |
| 10459 |
"\n" |
| 10460 |
" 1) SpiderMonkey may assert if the returned code isn't close enough\n" |
| 10461 |
" to the script's real code, so this function is not fuzzer-safe.\n" |
| 10462 |
"\n" |
| 10463 |
" 2) The runtime can have only one source retrieval hook active at a\n" |
| 10464 |
" time. If |fun| is not careful, |hook| could be asked to retrieve the\n" |
| 10465 |
" source code for compilations that occurred long before it was set,\n" |
| 10466 |
" and that it knows nothing about. The reverse applies as well: the\n" |
| 10467 |
" original hook, that we reinstate after the call to |fun| completes,\n" |
| 10468 |
" might be asked for the source code of compilations that |fun|\n" |
| 10469 |
" performed, and which, presumably, only |hook| knows how to find.\n"), |
| 10470 |
|
| 10471 |
JS_FN_HELP("crash", Crash, 0, 0, |
| 10472 |
"crash([message, [{disable_minidump:true}]])", |
| 10473 |
" Crashes the process with a MOZ_CRASH, optionally providing a message.\n" |
| 10474 |
" An options object may be passed as the second argument. If the key\n" |
| 10475 |
" 'suppress_minidump' is set to true, then a minidump will not be\n" |
| 10476 |
" generated by the crash (which only has an effect if the breakpad\n" |
| 10477 |
" dumping library is loaded.)"), |
| 10478 |
|
| 10479 |
#ifndef __wasi__ |
| 10480 |
JS_FN_HELP("wasmLoop", WasmLoop, 2, 0, |
| 10481 |
"wasmLoop(filename, imports)", |
| 10482 |
" Performs an AFL-style persistent loop reading data from the given file and passing it\n" |
| 10483 |
" to the 'wasmEval' function together with the specified imports object."), |
| 10484 |
#endif // __wasi__ |
| 10485 |
|
| 10486 |
JS_FN_HELP("setBufferStreamParams", SetBufferStreamParams, 2, 0, |
| 10487 |
"setBufferStreamParams(delayMillis, chunkByteSize)", |
| 10488 |
" Set the delay time (between calls to StreamConsumer::consumeChunk) and chunk\n" |
| 10489 |
" size (in bytes)."), |
| 10490 |
|
| 10491 |
#ifdef JS_CACHEIR_SPEW |
| 10492 |
JS_FN_HELP("cacheIRHealthReport", CacheIRHealthReport, 0, 0, |
| 10493 |
"cacheIRHealthReport()", |
| 10494 |
" Show health rating of CacheIR stubs."), |
| 10495 |
#endif |
| 10496 |
|
| 10497 |
#ifdef DEBUG |
| 10498 |
JS_FN_HELP("debugGetQueuedJobs", DebugGetQueuedJobs, 0, 0, |
| 10499 |
"debugGetQueuedJobs()", |
| 10500 |
" Returns an array of queued jobs."), |
| 10501 |
#endif |
| 10502 |
|
| 10503 |
#ifdef JS_HAS_INTL_API |
| 10504 |
// One of the extras is AddMozDateTimeFormatConstructor, which is not fuzzing |
| 10505 |
// safe, since it doesn't validate the custom format pattern. |
| 10506 |
// |
| 10507 |
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1887585#c1 |
| 10508 |
JS_FN_HELP("addIntlExtras", AddIntlExtras, 1, 0, |
| 10509 |
"addIntlExtras(obj)", |
| 10510 |
"Adds various not-yet-standardized Intl functions as properties on the\n" |
| 10511 |
"provided object (this should generally be Intl itself). The added\n" |
| 10512 |
"functions and their behavior are experimental: don't depend upon them\n" |
| 10513 |
"unless you're willing to update your code if these experimental APIs change\n" |
| 10514 |
"underneath you."), |
| 10515 |
#endif // JS_HAS_INTL_API |
| 10516 |
|
| 10517 |
#ifdef MOZ_EXECUTION_TRACING |
| 10518 |
JS_FN_HELP("enableExecutionTracing", EnableExecutionTracing, 0, 0, |
| 10519 |
"enableExecutionTracing()", |
| 10520 |
" Enable execution tracing for the current context."), |
| 10521 |
|
| 10522 |
JS_FN_HELP("getExecutionTrace", GetExecutionTrace, 0, 0, |
| 10523 |
"getExecutionTrace()", |
| 10524 |
" Get the execution trace."), |
| 10525 |
|
| 10526 |
JS_FN_HELP("disableExecutionTracing", DisableExecutionTracing, 0, 0, |
| 10527 |
"disableExecutionTracing()", |
| 10528 |
" Disable execution tracing for the current context."), |
| 10529 |
#endif // MOZ_EXECUTION_TRACING |
| 10530 |
|
| 10531 |
JS_FN_HELP("startRecordingTelemetry", StartRecordingTelemetry, 1, 0, |
| 10532 |
"startRecordingTelemetry(probeName)", |
| 10533 |
" Start recording telemetry samples for the specified probe."), |
| 10534 |
|
| 10535 |
JS_FN_HELP("stopRecordingTelemetry", StopRecordingTelemetry, 1, 0, |
| 10536 |
"stopRecordingTelemetry(probeName)", |
| 10537 |
" Stop recording telemetry samples for the specified probe."), |
| 10538 |
|
| 10539 |
JS_FN_HELP("getTelemetrySamples", GetTelemetrySamples, 1, 0, |
| 10540 |
"getTelemetry(probeName)", |
| 10541 |
" Return an array of recorded telemetry samples for the specified probe."), |
| 10542 |
|
| 10543 |
JS_FS_HELP_END |
| 10544 |
}; |
| 10545 |
// clang-format on |
| 10546 |
|
| 10547 |
// clang-format off |
| 10548 |
static const JSFunctionSpecWithHelp performance_functions[] = { |
| 10549 |
JS_FN_HELP("now", Now, 0, 0, |
| 10550 |
"now()", |
| 10551 |
" Return the current time with sub-ms precision.\n" |
| 10552 |
" This function is an alias of the dateNow() function."), |
| 10553 |
JS_FS_HELP_END |
| 10554 |
}; |
| 10555 |
// clang-format on |
| 10556 |
|
| 10557 |
// clang-format off |
| 10558 |
static const JSFunctionSpecWithHelp console_functions[] = { |
| 10559 |
JS_FN_HELP("log", Print, 0, 0, |
| 10560 |
"log([exp ...])", |
| 10561 |
" Evaluate and print expressions to stdout.\n" |
| 10562 |
" This function is an alias of the print() function."), |
| 10563 |
JS_FS_HELP_END |
| 10564 |
}; |
| 10565 |
// clang-format on |
| 10566 |
|
| 10567 |
bool DefineConsole(JSContext* cx, HandleObject global) { |
| 10568 |
RootedObject obj(cx, JS_NewPlainObject(cx)); |
| 10569 |
return obj && JS_DefineFunctionsWithHelp(cx, obj, console_functions) && |
| 10570 |
JS_DefineProperty(cx, global, "console", obj, 0); |
| 10571 |
} |
| 10572 |
|
| 10573 |
#ifdef MOZ_PROFILING |
| 10574 |
# define PROFILING_FUNCTION_COUNT 5 |
| 10575 |
# ifdef MOZ_CALLGRIND |
| 10576 |
# define CALLGRIND_FUNCTION_COUNT 3 |
| 10577 |
# else |
| 10578 |
# define CALLGRIND_FUNCTION_COUNT 0 |
| 10579 |
# endif |
| 10580 |
# ifdef MOZ_VTUNE |
| 10581 |
# define VTUNE_FUNCTION_COUNT 4 |
| 10582 |
# else |
| 10583 |
# define VTUNE_FUNCTION_COUNT 0 |
| 10584 |
# endif |
| 10585 |
# define EXTERNAL_FUNCTION_COUNT \ |
| 10586 |
(PROFILING_FUNCTION_COUNT + CALLGRIND_FUNCTION_COUNT + VTUNE_FUNCTION_COUNT) |
| 10587 |
#else |
| 10588 |
# define EXTERNAL_FUNCTION_COUNT 0 |
| 10589 |
#endif |
| 10590 |
|
| 10591 |
#undef PROFILING_FUNCTION_COUNT |
| 10592 |
#undef CALLGRIND_FUNCTION_COUNT |
| 10593 |
#undef VTUNE_FUNCTION_COUNT |
| 10594 |
#undef EXTERNAL_FUNCTION_COUNT |
| 10595 |
|
| 10596 |
static bool PrintHelpString(JSContext* cx, HandleValue v) { |
| 10597 |
RootedString str(cx, v.toString()); |
| 10598 |
MOZ_ASSERT(gOutFile->isOpen()); |
| 10599 |
|
| 10600 |
UniqueChars bytes = JS_EncodeStringToUTF8(cx, str); |
| 10601 |
if (!bytes) { |
| 10602 |
return false; |
| 10603 |
} |
| 10604 |
|
| 10605 |
fprintf(gOutFile->fp, "%s\n", bytes.get()); |
| 10606 |
return true; |
| 10607 |
} |
| 10608 |
|
| 10609 |
static bool PrintHelp(JSContext* cx, HandleObject obj) { |
| 10610 |
RootedValue usage(cx); |
| 10611 |
if (!JS_GetProperty(cx, obj, "usage", &usage)) { |
| 10612 |
return false; |
| 10613 |
} |
| 10614 |
RootedValue help(cx); |
| 10615 |
if (!JS_GetProperty(cx, obj, "help", &help)) { |
| 10616 |
return false; |
| 10617 |
} |
| 10618 |
|
| 10619 |
if (!usage.isString() || !help.isString()) { |
| 10620 |
return true; |
| 10621 |
} |
| 10622 |
|
| 10623 |
return PrintHelpString(cx, usage) && PrintHelpString(cx, help); |
| 10624 |
} |
| 10625 |
|
| 10626 |
struct ExtraGlobalBindingWithHelp { |
| 10627 |
const char* name; |
| 10628 |
const char* help; |
| 10629 |
}; |
| 10630 |
|
| 10631 |
// clang-format off |
| 10632 |
static ExtraGlobalBindingWithHelp extraGlobalBindingsWithHelp[] = { |
| 10633 |
// Defined in BindScriptArgs. |
| 10634 |
{ |
| 10635 |
"scriptArgs", |
| 10636 |
" An array containing the command line arguments passed after the path\n" |
| 10637 |
" to a JS script."}, |
| 10638 |
{ |
| 10639 |
"scriptPath", |
| 10640 |
" The path to the JS script passed to JS shell. This does not reflect\n" |
| 10641 |
" modules evaluated via -m option."}, |
| 10642 |
|
| 10643 |
// Defined in DefineConsole. |
| 10644 |
{ |
| 10645 |
"console", |
| 10646 |
" An object with console.log() which aliases print()."}, |
| 10647 |
|
| 10648 |
// Defined in NewGlobalObject. |
| 10649 |
{ |
| 10650 |
"performance", |
| 10651 |
" An object with the following properties:\n" |
| 10652 |
" performance.now()\n" |
| 10653 |
" See help(performance.now)\n" |
| 10654 |
" performance.mozMemory.gc\n" |
| 10655 |
" An object that represents GC statistics with the following properties:\n" |
| 10656 |
" gcBytes\n" |
| 10657 |
" gcMaxBytes\n" |
| 10658 |
" mallocBytes\n" |
| 10659 |
" gcIsHighFrequencyMode\n" |
| 10660 |
" gcNumber\n" |
| 10661 |
" majorGCCount\n" |
| 10662 |
" minorGCCount\n" |
| 10663 |
" sliceCount\n" |
| 10664 |
" compartmentCount\n" |
| 10665 |
" lastStartReason\n" |
| 10666 |
" zone.gcBytes\n" |
| 10667 |
" zone.gcTriggerBytes\n" |
| 10668 |
" zone.gcAllocTrigger\n" |
| 10669 |
" zone.mallocBytes\n" |
| 10670 |
" zone.mallocTriggerBytes\n" |
| 10671 |
" zone.gcNumber"}, |
| 10672 |
{ |
| 10673 |
"new FakeDOMObject()", |
| 10674 |
" A constructor to test IonMonkey DOM optimizations in JS shell.\n" |
| 10675 |
" The prototype object has the following properties:\n" |
| 10676 |
" FakeDOMObject.prototype.x\n" |
| 10677 |
" Generic getter/setter with JSJitInfo\n" |
| 10678 |
" FakeDOMObject.prototype.slot\n" |
| 10679 |
" Getter with JSJitInfo.slotIndex\n" |
| 10680 |
" FakeDOMObject.prototype.global\n" |
| 10681 |
" Getter/setter with JSJitInfo::AliasEverything\n" |
| 10682 |
" FakeDOMObject.prototype.doFoo()\n" |
| 10683 |
" Method with JSJitInfo\n" |
| 10684 |
" FakeDOMObject.prototype.getObject()\n" |
| 10685 |
" Method with JSJitInfo that returns an object."}, |
| 10686 |
}; |
| 10687 |
// clang-format on |
| 10688 |
|
| 10689 |
static bool MatchPattern(JSContext* cx, JS::Handle<RegExpObject*> regex, |
| 10690 |
JS::Handle<JSString*> inputStr, bool* result) { |
| 10691 |
JS::Rooted<JSString*> linearInputStr(cx, inputStr); |
| 10692 |
if (!linearInputStr->ensureLinear(cx)) { |
| 10693 |
return false; |
| 10694 |
} |
| 10695 |
|
| 10696 |
// Execute the regular expression in |regex|'s compartment. |
| 10697 |
JSAutoRealm ar(cx, regex); |
| 10698 |
if (!cx->compartment()->wrap(cx, &linearInputStr)) { |
| 10699 |
return false; |
| 10700 |
} |
| 10701 |
JS::Rooted<JSLinearString*> input(cx, &linearInputStr->asLinear()); |
| 10702 |
size_t ignored = 0; |
| 10703 |
JS::Rooted<JS::Value> v(cx); |
| 10704 |
if (!ExecuteRegExpLegacy(cx, nullptr, regex, input, &ignored, true, &v)) { |
| 10705 |
return false; |
| 10706 |
} |
| 10707 |
*result = !v.isNull(); |
| 10708 |
return true; |
| 10709 |
} |
| 10710 |
|
| 10711 |
static bool PrintEnumeratedHelp(JSContext* cx, HandleObject obj, |
| 10712 |
HandleObject pattern, bool brief) { |
| 10713 |
RootedIdVector idv(cx); |
| 10714 |
if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_HIDDEN, &idv)) { |
| 10715 |
return false; |
| 10716 |
} |
| 10717 |
|
| 10718 |
Rooted<RegExpObject*> regex(cx); |
| 10719 |
if (pattern) { |
| 10720 |
regex = &UncheckedUnwrap(pattern)->as<RegExpObject>(); |
| 10721 |
} |
| 10722 |
|
| 10723 |
for (size_t i = 0; i < idv.length(); i++) { |
| 10724 |
RootedValue v(cx); |
| 10725 |
RootedId id(cx, idv[i]); |
| 10726 |
if (!JS_GetPropertyById(cx, obj, id, &v)) { |
| 10727 |
return false; |
| 10728 |
} |
| 10729 |
if (!v.isObject()) { |
| 10730 |
continue; |
| 10731 |
} |
| 10732 |
|
| 10733 |
RootedObject funcObj(cx, &v.toObject()); |
| 10734 |
if (regex) { |
| 10735 |
// Only pay attention to objects with a 'help' property, which will |
| 10736 |
// either be documented functions or interface objects. |
| 10737 |
if (!JS_GetProperty(cx, funcObj, "help", &v)) { |
| 10738 |
return false; |
| 10739 |
} |
| 10740 |
if (!v.isString()) { |
| 10741 |
continue; |
| 10742 |
} |
| 10743 |
|
| 10744 |
// For functions, match against the name. For interface objects, |
| 10745 |
// match against the usage string. |
| 10746 |
if (!JS_GetProperty(cx, funcObj, "name", &v)) { |
| 10747 |
return false; |
| 10748 |
} |
| 10749 |
if (!v.isString()) { |
| 10750 |
if (!JS_GetProperty(cx, funcObj, "usage", &v)) { |
| 10751 |
return false; |
| 10752 |
} |
| 10753 |
if (!v.isString()) { |
| 10754 |
continue; |
| 10755 |
} |
| 10756 |
} |
| 10757 |
|
| 10758 |
Rooted<JSString*> inputStr(cx, v.toString()); |
| 10759 |
bool result = false; |
| 10760 |
if (!MatchPattern(cx, regex, inputStr, &result)) { |
| 10761 |
return false; |
| 10762 |
} |
| 10763 |
if (!result) { |
| 10764 |
continue; |
| 10765 |
} |
| 10766 |
} |
| 10767 |
|
| 10768 |
if (!PrintHelp(cx, funcObj)) { |
| 10769 |
return false; |
| 10770 |
} |
| 10771 |
} |
| 10772 |
|
| 10773 |
return true; |
| 10774 |
} |
| 10775 |
|
| 10776 |
static bool PrintExtraGlobalEnumeratedHelp(JSContext* cx, HandleObject pattern, |
| 10777 |
bool brief) { |
| 10778 |
Rooted<RegExpObject*> regex(cx); |
| 10779 |
if (pattern) { |
| 10780 |
regex = &UncheckedUnwrap(pattern)->as<RegExpObject>(); |
| 10781 |
} |
| 10782 |
|
| 10783 |
for (const auto& item : extraGlobalBindingsWithHelp) { |
| 10784 |
if (regex) { |
| 10785 |
JS::Rooted<JSString*> name(cx, JS_NewStringCopyZ(cx, item.name)); |
| 10786 |
if (!name) { |
| 10787 |
return false; |
| 10788 |
} |
| 10789 |
|
| 10790 |
bool result = false; |
| 10791 |
if (!MatchPattern(cx, regex, name, &result)) { |
| 10792 |
return false; |
| 10793 |
} |
| 10794 |
if (!result) { |
| 10795 |
continue; |
| 10796 |
} |
| 10797 |
} |
| 10798 |
fprintf(gOutFile->fp, "%s\n", item.name); |
| 10799 |
fprintf(gOutFile->fp, "%s\n", item.help); |
| 10800 |
} |
| 10801 |
|
| 10802 |
return true; |
| 10803 |
} |
| 10804 |
|
| 10805 |
static bool Help(JSContext* cx, unsigned argc, Value* vp) { |
| 10806 |
if (!gOutFile->isOpen()) { |
| 10807 |
JS_ReportErrorASCII(cx, "output file is closed"); |
| 10808 |
return false; |
| 10809 |
} |
| 10810 |
|
| 10811 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 10812 |
args.rval().setUndefined(); |
| 10813 |
RootedObject global(cx, JS::CurrentGlobalOrNull(cx)); |
| 10814 |
|
| 10815 |
// help() - display the version and dump out help for all functions on the |
| 10816 |
// global. |
| 10817 |
if (args.length() == 0) { |
| 10818 |
fprintf(gOutFile->fp, "%s\n", JS_GetImplementationVersion()); |
| 10819 |
|
| 10820 |
if (!PrintEnumeratedHelp(cx, global, nullptr, false)) { |
| 10821 |
return false; |
| 10822 |
} |
| 10823 |
if (!PrintExtraGlobalEnumeratedHelp(cx, nullptr, false)) { |
| 10824 |
return false; |
| 10825 |
} |
| 10826 |
return true; |
| 10827 |
} |
| 10828 |
|
| 10829 |
RootedValue v(cx); |
| 10830 |
|
| 10831 |
if (args[0].isPrimitive()) { |
| 10832 |
// help("foo") |
| 10833 |
JS_ReportErrorASCII(cx, "primitive arg"); |
| 10834 |
return false; |
| 10835 |
} |
| 10836 |
|
| 10837 |
RootedObject obj(cx, &args[0].toObject()); |
| 10838 |
if (!obj) { |
| 10839 |
return true; |
| 10840 |
} |
| 10841 |
bool isRegexp; |
| 10842 |
if (!JS::ObjectIsRegExp(cx, obj, &isRegexp)) { |
| 10843 |
return false; |
| 10844 |
} |
| 10845 |
|
| 10846 |
if (isRegexp) { |
| 10847 |
// help(/pattern/) |
| 10848 |
if (!PrintEnumeratedHelp(cx, global, obj, false)) { |
| 10849 |
return false; |
| 10850 |
} |
| 10851 |
if (!PrintExtraGlobalEnumeratedHelp(cx, obj, false)) { |
| 10852 |
return false; |
| 10853 |
} |
| 10854 |
return true; |
| 10855 |
} |
| 10856 |
|
| 10857 |
// help(function) |
| 10858 |
// help(namespace_obj) |
| 10859 |
return PrintHelp(cx, obj); |
| 10860 |
} |
| 10861 |
|
| 10862 |
static const JSErrorFormatString jsShell_ErrorFormatString[JSShellErr_Limit] = { |
| 10863 |
#define MSG_DEF(name, count, exception, format) \ |
| 10864 |
{#name, format, count, JSEXN_ERR}, |
| 10865 |
#include "jsshell.msg" |
| 10866 |
#undef MSG_DEF |
| 10867 |
}; |
| 10868 |
|
| 10869 |
const JSErrorFormatString* js::shell::my_GetErrorMessage( |
| 10870 |
void* userRef, const unsigned errorNumber) { |
| 10871 |
if (errorNumber == 0 || errorNumber >= JSShellErr_Limit) { |
| 10872 |
return nullptr; |
| 10873 |
} |
| 10874 |
|
| 10875 |
return &jsShell_ErrorFormatString[errorNumber]; |
| 10876 |
} |
| 10877 |
|
| 10878 |
static bool CreateLastWarningObject(JSContext* cx, JSErrorReport* report) { |
| 10879 |
RootedObject warningObj(cx, JS_NewObject(cx, nullptr)); |
| 10880 |
if (!warningObj) { |
| 10881 |
return false; |
| 10882 |
} |
| 10883 |
|
| 10884 |
if (!CopyErrorReportToObject(cx, report, warningObj)) { |
| 10885 |
return false; |
| 10886 |
} |
| 10887 |
|
| 10888 |
GetShellContext(cx)->lastWarning.setObject(*warningObj); |
| 10889 |
return true; |
| 10890 |
} |
| 10891 |
|
| 10892 |
static FILE* ErrorFilePointer() { |
| 10893 |
if (gErrFile->isOpen()) { |
| 10894 |
return gErrFile->fp; |
| 10895 |
} |
| 10896 |
|
| 10897 |
fprintf(stderr, "error file is closed; falling back to stderr\n"); |
| 10898 |
return stderr; |
| 10899 |
} |
| 10900 |
|
| 10901 |
bool shell::PrintStackTrace(JSContext* cx, HandleObject stackObj) { |
| 10902 |
if (!stackObj || !stackObj->is<SavedFrame>()) { |
| 10903 |
return true; |
| 10904 |
} |
| 10905 |
|
| 10906 |
JSPrincipals* principals = stackObj->nonCCWRealm()->principals(); |
| 10907 |
RootedString stackStr(cx); |
| 10908 |
if (!BuildStackString(cx, principals, stackObj, &stackStr, 2)) { |
| 10909 |
return false; |
| 10910 |
} |
| 10911 |
|
| 10912 |
UniqueChars stack = JS_EncodeStringToUTF8(cx, stackStr); |
| 10913 |
if (!stack) { |
| 10914 |
return false; |
| 10915 |
} |
| 10916 |
|
| 10917 |
FILE* fp = ErrorFilePointer(); |
| 10918 |
fputs("Stack:\n", fp); |
| 10919 |
fputs(stack.get(), fp); |
| 10920 |
|
| 10921 |
return true; |
| 10922 |
} |
| 10923 |
|
| 10924 |
js::shell::AutoReportException::~AutoReportException() { |
| 10925 |
if (!JS_IsExceptionPending(cx)) { |
| 10926 |
return; |
| 10927 |
} |
| 10928 |
|
| 10929 |
auto printError = [](JSContext* cx, auto& report, const auto& exnStack, |
| 10930 |
const char* prefix = nullptr) { |
| 10931 |
if (!report.init(cx, exnStack, JS::ErrorReportBuilder::WithSideEffects)) { |
| 10932 |
fprintf(stderr, "out of memory initializing JS::ErrorReportBuilder\n"); |
| 10933 |
fflush(stderr); |
| 10934 |
JS_ClearPendingException(cx); |
| 10935 |
return false; |
| 10936 |
} |
| 10937 |
|
| 10938 |
MOZ_ASSERT(!report.report()->isWarning()); |
| 10939 |
|
| 10940 |
FILE* fp = ErrorFilePointer(); |
| 10941 |
if (prefix) { |
| 10942 |
fputs(prefix, fp); |
| 10943 |
} |
| 10944 |
JS::PrintError(fp, report, reportWarnings); |
| 10945 |
JS_ClearPendingException(cx); |
| 10946 |
|
| 10947 |
// If possible, use the original error stack as the source of truth, because |
| 10948 |
// finally block handlers may have overwritten the exception stack. |
| 10949 |
RootedObject stack(cx, exnStack.stack()); |
| 10950 |
if (exnStack.exception().isObject()) { |
| 10951 |
RootedObject exception(cx, &exnStack.exception().toObject()); |
| 10952 |
if (JSObject* exceptionStack = JS::ExceptionStackOrNull(exception)) { |
| 10953 |
stack.set(exceptionStack); |
| 10954 |
} |
| 10955 |
} |
| 10956 |
|
| 10957 |
if (!PrintStackTrace(cx, stack)) { |
| 10958 |
fputs("(Unable to print stack trace)\n", fp); |
| 10959 |
JS_ClearPendingException(cx); |
| 10960 |
} |
| 10961 |
|
| 10962 |
return true; |
| 10963 |
}; |
| 10964 |
|
| 10965 |
// Get exception object and stack before printing and clearing exception. |
| 10966 |
JS::ExceptionStack exnStack(cx); |
| 10967 |
if (!JS::StealPendingExceptionStack(cx, &exnStack)) { |
| 10968 |
fprintf(stderr, "out of memory while stealing exception\n"); |
| 10969 |
fflush(stderr); |
| 10970 |
JS_ClearPendingException(cx); |
| 10971 |
return; |
| 10972 |
} |
| 10973 |
|
| 10974 |
ShellContext* sc = GetShellContext(cx); |
| 10975 |
JS::ErrorReportBuilder report(cx); |
| 10976 |
if (!printError(cx, report, exnStack)) { |
| 10977 |
// Return if we couldn't initialize the error report. |
| 10978 |
return; |
| 10979 |
} |
| 10980 |
|
| 10981 |
// Print the error's cause, if available. |
| 10982 |
if (exnStack.exception().isObject()) { |
| 10983 |
JSObject* exception = &exnStack.exception().toObject(); |
| 10984 |
if (exception->is<ErrorObject>()) { |
| 10985 |
auto* error = &exception->as<ErrorObject>(); |
| 10986 |
if (auto maybeCause = error->getCause()) { |
| 10987 |
RootedValue cause(cx, maybeCause.value()); |
| 10988 |
|
| 10989 |
RootedObject causeStack(cx); |
| 10990 |
if (cause.isObject()) { |
| 10991 |
RootedObject causeObj(cx, &cause.toObject()); |
| 10992 |
causeStack = JS::ExceptionStackOrNull(causeObj); |
| 10993 |
} |
| 10994 |
|
| 10995 |
JS::ExceptionStack exnStack(cx, cause, causeStack); |
| 10996 |
JS::ErrorReportBuilder report(cx); |
| 10997 |
printError(cx, report, exnStack, "Caused by: "); |
| 10998 |
} |
| 10999 |
} |
| 11000 |
} |
| 11001 |
|
| 11002 |
#if defined(DEBUG) || defined(JS_OOM_BREAKPOINT) |
| 11003 |
// Don't quit the shell if an unhandled exception is reported during OOM |
| 11004 |
// testing. |
| 11005 |
if (cx->runningOOMTest) { |
| 11006 |
return; |
| 11007 |
} |
| 11008 |
#endif |
| 11009 |
|
| 11010 |
if (report.report()->errorNumber == JSMSG_OUT_OF_MEMORY) { |
| 11011 |
sc->exitCode = EXITCODE_OUT_OF_MEMORY; |
| 11012 |
} else { |
| 11013 |
sc->exitCode = EXITCODE_RUNTIME_ERROR; |
| 11014 |
} |
| 11015 |
} |
| 11016 |
|
| 11017 |
void js::shell::WarningReporter(JSContext* cx, JSErrorReport* report) { |
| 11018 |
ShellContext* sc = GetShellContext(cx); |
| 11019 |
FILE* fp = ErrorFilePointer(); |
| 11020 |
|
| 11021 |
MOZ_ASSERT(report->isWarning()); |
| 11022 |
|
| 11023 |
if (sc->lastWarningEnabled) { |
| 11024 |
JS::AutoSaveExceptionState savedExc(cx); |
| 11025 |
if (!CreateLastWarningObject(cx, report)) { |
| 11026 |
fputs("Unhandled error happened while creating last warning object.\n", |
| 11027 |
fp); |
| 11028 |
fflush(fp); |
| 11029 |
} |
| 11030 |
savedExc.restore(); |
| 11031 |
} |
| 11032 |
|
| 11033 |
// Print the warning. |
| 11034 |
JS::PrintError(fp, report, reportWarnings); |
| 11035 |
} |
| 11036 |
|
| 11037 |
static bool global_enumerate(JSContext* cx, JS::HandleObject obj, |
| 11038 |
JS::MutableHandleIdVector properties, |
| 11039 |
bool enumerableOnly) { |
| 11040 |
#ifdef LAZY_STANDARD_CLASSES |
| 11041 |
return JS_NewEnumerateStandardClasses(cx, obj, properties, enumerableOnly); |
| 11042 |
#else |
| 11043 |
return true; |
| 11044 |
#endif |
| 11045 |
} |
| 11046 |
|
| 11047 |
static bool global_resolve(JSContext* cx, HandleObject obj, HandleId id, |
| 11048 |
bool* resolvedp) { |
| 11049 |
#ifdef LAZY_STANDARD_CLASSES |
| 11050 |
if (!JS_ResolveStandardClass(cx, obj, id, resolvedp)) { |
| 11051 |
return false; |
| 11052 |
} |
| 11053 |
#endif |
| 11054 |
return true; |
| 11055 |
} |
| 11056 |
|
| 11057 |
static bool global_mayResolve(const JSAtomState& names, jsid id, |
| 11058 |
JSObject* maybeObj) { |
| 11059 |
return JS_MayResolveStandardClass(names, id, maybeObj); |
| 11060 |
} |
| 11061 |
|
| 11062 |
static const JSClassOps global_classOps = { |
| 11063 |
nullptr, // addProperty |
| 11064 |
nullptr, // delProperty |
| 11065 |
nullptr, // enumerate |
| 11066 |
global_enumerate, // newEnumerate |
| 11067 |
global_resolve, // resolve |
| 11068 |
global_mayResolve, // mayResolve |
| 11069 |
nullptr, // finalize |
| 11070 |
nullptr, // call |
| 11071 |
nullptr, // construct |
| 11072 |
JS_GlobalObjectTraceHook, // trace |
| 11073 |
}; |
| 11074 |
|
| 11075 |
static constexpr uint32_t DOM_PROTOTYPE_SLOT = JSCLASS_GLOBAL_SLOT_COUNT; |
| 11076 |
static constexpr uint32_t DOM_GLOBAL_SLOTS = 1; |
| 11077 |
|
| 11078 |
static const JSClass global_class = { |
| 11079 |
"global", |
| 11080 |
JSCLASS_GLOBAL_FLAGS | JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(DOM_GLOBAL_SLOTS), |
| 11081 |
&global_classOps, |
| 11082 |
}; |
| 11083 |
|
| 11084 |
/* |
| 11085 |
* Define a FakeDOMObject constructor. It returns an object with a getter, |
| 11086 |
* setter and method with attached JitInfo. This object can be used to test |
| 11087 |
* IonMonkey DOM optimizations in the shell. |
| 11088 |
*/ |
| 11089 |
|
| 11090 |
/* Fow now just use to a constant we can check. */ |
| 11091 |
static const void* DOM_PRIVATE_VALUE = (void*)0x1234; |
| 11092 |
|
| 11093 |
static bool dom_genericGetter(JSContext* cx, unsigned argc, JS::Value* vp); |
| 11094 |
|
| 11095 |
static bool dom_genericSetter(JSContext* cx, unsigned argc, JS::Value* vp); |
| 11096 |
|
| 11097 |
static bool dom_genericMethod(JSContext* cx, unsigned argc, JS::Value* vp); |
| 11098 |
|
| 11099 |
static bool dom_get_x(JSContext* cx, HandleObject obj, void* self, |
| 11100 |
JSJitGetterCallArgs args) { |
| 11101 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11102 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11103 |
args.rval().set(JS_NumberValue(double(3.14))); |
| 11104 |
return true; |
| 11105 |
} |
| 11106 |
|
| 11107 |
static bool dom_set_x(JSContext* cx, HandleObject obj, void* self, |
| 11108 |
JSJitSetterCallArgs args) { |
| 11109 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11110 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11111 |
return true; |
| 11112 |
} |
| 11113 |
|
| 11114 |
static bool dom_get_slot(JSContext* cx, HandleObject obj, void* self, |
| 11115 |
JSJitGetterCallArgs args) { |
| 11116 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11117 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11118 |
|
| 11119 |
Value v = JS::GetReservedSlot(obj, DOM_OBJECT_SLOT2); |
| 11120 |
MOZ_ASSERT(v.toInt32() == 42); |
| 11121 |
args.rval().set(v); |
| 11122 |
return true; |
| 11123 |
} |
| 11124 |
|
| 11125 |
static bool dom_get_global(JSContext* cx, HandleObject obj, void* self, |
| 11126 |
JSJitGetterCallArgs args) { |
| 11127 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11128 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11129 |
|
| 11130 |
// Return the current global (instead of obj->global()) to test cx->realm |
| 11131 |
// switching in the JIT. |
| 11132 |
args.rval().setObject(*ToWindowProxyIfWindow(cx->global())); |
| 11133 |
|
| 11134 |
return true; |
| 11135 |
} |
| 11136 |
|
| 11137 |
static bool dom_set_global(JSContext* cx, HandleObject obj, void* self, |
| 11138 |
JSJitSetterCallArgs args) { |
| 11139 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11140 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11141 |
|
| 11142 |
// Throw an exception if our argument is not the current global. This lets |
| 11143 |
// us test cx->realm switching. |
| 11144 |
if (!args[0].isObject() || |
| 11145 |
ToWindowIfWindowProxy(&args[0].toObject()) != cx->global()) { |
| 11146 |
JS_ReportErrorASCII(cx, "Setter not called with matching global argument"); |
| 11147 |
return false; |
| 11148 |
} |
| 11149 |
|
| 11150 |
return true; |
| 11151 |
} |
| 11152 |
|
| 11153 |
static bool dom_doFoo(JSContext* cx, HandleObject obj, void* self, |
| 11154 |
const JSJitMethodCallArgs& args) { |
| 11155 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11156 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11157 |
MOZ_ASSERT(cx->realm() == args.callee().as<JSFunction>().realm()); |
| 11158 |
|
| 11159 |
/* Just return args.length(). */ |
| 11160 |
args.rval().setInt32(args.length()); |
| 11161 |
return true; |
| 11162 |
} |
| 11163 |
|
| 11164 |
static bool dom_doBar(JSContext* cx, HandleObject obj, void* self, |
| 11165 |
const JSJitMethodCallArgs& args) { |
| 11166 |
MOZ_ASSERT(JS::GetClass(obj) == GetDomClass()); |
| 11167 |
MOZ_ASSERT(self == DOM_PRIVATE_VALUE); |
| 11168 |
MOZ_ASSERT(cx->realm() == args.callee().as<JSFunction>().realm()); |
| 11169 |
|
| 11170 |
static const JSClass barClass = { |
| 11171 |
"BarObj", |
| 11172 |
}; |
| 11173 |
|
| 11174 |
JSObject* retObj = |
| 11175 |
JS_NewObjectWithGivenProtoAndUseAllocSite(cx, &barClass, nullptr); |
| 11176 |
if (!retObj) { |
| 11177 |
return false; |
| 11178 |
} |
| 11179 |
|
| 11180 |
args.rval().setObject(*retObj); |
| 11181 |
return true; |
| 11182 |
} |
| 11183 |
|
| 11184 |
static const JSJitInfo dom_x_getterinfo = { |
| 11185 |
{(JSJitGetterOp)dom_get_x}, |
| 11186 |
{0}, /* protoID */ |
| 11187 |
{0}, /* depth */ |
| 11188 |
JSJitInfo::Getter, |
| 11189 |
JSJitInfo::AliasNone, /* aliasSet */ |
| 11190 |
JSVAL_TYPE_UNKNOWN, /* returnType */ |
| 11191 |
true, /* isInfallible. False in setters. */ |
| 11192 |
true, /* isMovable */ |
| 11193 |
true, /* isEliminatable */ |
| 11194 |
false, /* isAlwaysInSlot */ |
| 11195 |
false, /* isLazilyCachedInSlot */ |
| 11196 |
false, /* isTypedMethod */ |
| 11197 |
0 /* slotIndex */ |
| 11198 |
}; |
| 11199 |
|
| 11200 |
static const JSJitInfo dom_x_setterinfo = { |
| 11201 |
{(JSJitGetterOp)dom_set_x}, |
| 11202 |
{0}, /* protoID */ |
| 11203 |
{0}, /* depth */ |
| 11204 |
JSJitInfo::Setter, |
| 11205 |
JSJitInfo::AliasEverything, /* aliasSet */ |
| 11206 |
JSVAL_TYPE_UNKNOWN, /* returnType */ |
| 11207 |
false, /* isInfallible. False in setters. */ |
| 11208 |
false, /* isMovable. */ |
| 11209 |
false, /* isEliminatable. */ |
| 11210 |
false, /* isAlwaysInSlot */ |
| 11211 |
false, /* isLazilyCachedInSlot */ |
| 11212 |
false, /* isTypedMethod */ |
| 11213 |
0 /* slotIndex */ |
| 11214 |
}; |
| 11215 |
|
| 11216 |
static const JSJitInfo dom_slot_getterinfo = { |
| 11217 |
{(JSJitGetterOp)dom_get_slot}, |
| 11218 |
{0}, /* protoID */ |
| 11219 |
{0}, /* depth */ |
| 11220 |
JSJitInfo::Getter, |
| 11221 |
JSJitInfo::AliasNone, /* aliasSet */ |
| 11222 |
JSVAL_TYPE_INT32, /* returnType */ |
| 11223 |
false, /* isInfallible. False in setters. */ |
| 11224 |
true, /* isMovable */ |
| 11225 |
true, /* isEliminatable */ |
| 11226 |
true, /* isAlwaysInSlot */ |
| 11227 |
false, /* isLazilyCachedInSlot */ |
| 11228 |
false, /* isTypedMethod */ |
| 11229 |
DOM_OBJECT_SLOT2 /* slotIndex */ |
| 11230 |
}; |
| 11231 |
|
| 11232 |
// Note: this getter uses AliasEverything and is marked as fallible and |
| 11233 |
// non-movable (1) to prevent Ion from getting too clever optimizing it and |
| 11234 |
// (2) it's nice to have a few different kinds of getters in the shell. |
| 11235 |
static const JSJitInfo dom_global_getterinfo = { |
| 11236 |
{(JSJitGetterOp)dom_get_global}, |
| 11237 |
{0}, /* protoID */ |
| 11238 |
{0}, /* depth */ |
| 11239 |
JSJitInfo::Getter, |
| 11240 |
JSJitInfo::AliasEverything, /* aliasSet */ |
| 11241 |
JSVAL_TYPE_OBJECT, /* returnType */ |
| 11242 |
false, /* isInfallible. False in setters. */ |
| 11243 |
false, /* isMovable */ |
| 11244 |
false, /* isEliminatable */ |
| 11245 |
false, /* isAlwaysInSlot */ |
| 11246 |
false, /* isLazilyCachedInSlot */ |
| 11247 |
false, /* isTypedMethod */ |
| 11248 |
0 /* slotIndex */ |
| 11249 |
}; |
| 11250 |
|
| 11251 |
static const JSJitInfo dom_global_setterinfo = { |
| 11252 |
{(JSJitGetterOp)dom_set_global}, |
| 11253 |
{0}, /* protoID */ |
| 11254 |
{0}, /* depth */ |
| 11255 |
JSJitInfo::Setter, |
| 11256 |
JSJitInfo::AliasEverything, /* aliasSet */ |
| 11257 |
JSVAL_TYPE_UNKNOWN, /* returnType */ |
| 11258 |
false, /* isInfallible. False in setters. */ |
| 11259 |
false, /* isMovable. */ |
| 11260 |
false, /* isEliminatable. */ |
| 11261 |
false, /* isAlwaysInSlot */ |
| 11262 |
false, /* isLazilyCachedInSlot */ |
| 11263 |
false, /* isTypedMethod */ |
| 11264 |
0 /* slotIndex */ |
| 11265 |
}; |
| 11266 |
|
| 11267 |
static const JSJitInfo doFoo_methodinfo = { |
| 11268 |
{(JSJitGetterOp)dom_doFoo}, |
| 11269 |
{0}, /* protoID */ |
| 11270 |
{0}, /* depth */ |
| 11271 |
JSJitInfo::Method, |
| 11272 |
JSJitInfo::AliasEverything, /* aliasSet */ |
| 11273 |
JSVAL_TYPE_UNKNOWN, /* returnType */ |
| 11274 |
false, /* isInfallible. False in setters. */ |
| 11275 |
false, /* isMovable */ |
| 11276 |
false, /* isEliminatable */ |
| 11277 |
false, /* isAlwaysInSlot */ |
| 11278 |
false, /* isLazilyCachedInSlot */ |
| 11279 |
false, /* isTypedMethod */ |
| 11280 |
0 /* slotIndex */ |
| 11281 |
}; |
| 11282 |
|
| 11283 |
static const JSJitInfo doBar_methodinfo = { |
| 11284 |
{(JSJitGetterOp)dom_doBar}, |
| 11285 |
{0}, /* protoID */ |
| 11286 |
{0}, /* depth */ |
| 11287 |
JSJitInfo::Method, |
| 11288 |
JSJitInfo::AliasEverything, /* aliasSet */ |
| 11289 |
JSVAL_TYPE_OBJECT, /* returnType */ |
| 11290 |
false, /* isInfallible. False in setters. */ |
| 11291 |
false, /* isMovable */ |
| 11292 |
false, /* isEliminatable */ |
| 11293 |
false, /* isAlwaysInSlot */ |
| 11294 |
false, /* isLazilyCachedInSlot */ |
| 11295 |
false, /* isTypedMethod */ |
| 11296 |
0 /* slotIndex */ |
| 11297 |
}; |
| 11298 |
|
| 11299 |
static const JSPropertySpec dom_props[] = { |
| 11300 |
JSPropertySpec::nativeAccessors("x", JSPROP_ENUMERATE, dom_genericGetter, |
| 11301 |
&dom_x_getterinfo, dom_genericSetter, |
| 11302 |
&dom_x_setterinfo), |
| 11303 |
JSPropertySpec::nativeAccessors("slot", JSPROP_ENUMERATE, dom_genericGetter, |
| 11304 |
&dom_slot_getterinfo), |
| 11305 |
JSPropertySpec::nativeAccessors("global", JSPROP_ENUMERATE, |
| 11306 |
dom_genericGetter, &dom_global_getterinfo, |
| 11307 |
dom_genericSetter, &dom_global_setterinfo), |
| 11308 |
JS_PS_END, |
| 11309 |
}; |
| 11310 |
|
| 11311 |
static const JSFunctionSpec dom_methods[] = { |
| 11312 |
JS_FNINFO("doFoo", dom_genericMethod, &doFoo_methodinfo, 3, |
| 11313 |
JSPROP_ENUMERATE), |
| 11314 |
JS_FNINFO("doBar", dom_genericMethod, &doBar_methodinfo, 3, |
| 11315 |
JSPROP_ENUMERATE), |
| 11316 |
JS_FS_END, |
| 11317 |
}; |
| 11318 |
|
| 11319 |
static void FakeDOMObject_finalize(JS::GCContext* gcx, JSObject* obj) { |
| 11320 |
// Dummy finalize method so we can swap with background finalized object. |
| 11321 |
} |
| 11322 |
|
| 11323 |
static const JSClassOps FakeDOMObjectClassOps = { |
| 11324 |
nullptr, // addProperty |
| 11325 |
nullptr, // delProperty |
| 11326 |
nullptr, // enumerate |
| 11327 |
nullptr, // newEnumerate |
| 11328 |
nullptr, // resolve |
| 11329 |
nullptr, // mayResolve |
| 11330 |
FakeDOMObject_finalize, |
| 11331 |
nullptr, // call |
| 11332 |
nullptr, // construct |
| 11333 |
nullptr, |
| 11334 |
}; |
| 11335 |
|
| 11336 |
static const JSClass dom_class = {"FakeDOMObject", |
| 11337 |
JSCLASS_IS_DOMJSCLASS | |
| 11338 |
JSCLASS_HAS_RESERVED_SLOTS(2) | |
| 11339 |
JSCLASS_BACKGROUND_FINALIZE, |
| 11340 |
&FakeDOMObjectClassOps}; |
| 11341 |
|
| 11342 |
static const JSClass* GetDomClass() { return &dom_class; } |
| 11343 |
|
| 11344 |
static bool dom_genericGetter(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 11345 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 11346 |
|
| 11347 |
if (!args.thisv().isObject()) { |
| 11348 |
args.rval().setUndefined(); |
| 11349 |
return true; |
| 11350 |
} |
| 11351 |
|
| 11352 |
RootedObject obj(cx, &args.thisv().toObject()); |
| 11353 |
if (JS::GetClass(obj) != &dom_class) { |
| 11354 |
args.rval().set(UndefinedValue()); |
| 11355 |
return true; |
| 11356 |
} |
| 11357 |
|
| 11358 |
JS::Value val = JS::GetReservedSlot(obj, DOM_OBJECT_SLOT); |
| 11359 |
|
| 11360 |
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev()); |
| 11361 |
MOZ_ASSERT(info->type() == JSJitInfo::Getter); |
| 11362 |
JSJitGetterOp getter = info->getter; |
| 11363 |
return getter(cx, obj, val.toPrivate(), JSJitGetterCallArgs(args)); |
| 11364 |
} |
| 11365 |
|
| 11366 |
static bool dom_genericSetter(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 11367 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 11368 |
|
| 11369 |
if (args.length() < 1 || !args.thisv().isObject()) { |
| 11370 |
args.rval().setUndefined(); |
| 11371 |
return true; |
| 11372 |
} |
| 11373 |
|
| 11374 |
RootedObject obj(cx, &args.thisv().toObject()); |
| 11375 |
if (JS::GetClass(obj) != &dom_class) { |
| 11376 |
args.rval().set(UndefinedValue()); |
| 11377 |
return true; |
| 11378 |
} |
| 11379 |
|
| 11380 |
JS::Value val = JS::GetReservedSlot(obj, DOM_OBJECT_SLOT); |
| 11381 |
|
| 11382 |
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev()); |
| 11383 |
MOZ_ASSERT(info->type() == JSJitInfo::Setter); |
| 11384 |
JSJitSetterOp setter = info->setter; |
| 11385 |
if (!setter(cx, obj, val.toPrivate(), JSJitSetterCallArgs(args))) { |
| 11386 |
return false; |
| 11387 |
} |
| 11388 |
args.rval().set(UndefinedValue()); |
| 11389 |
return true; |
| 11390 |
} |
| 11391 |
|
| 11392 |
static bool dom_genericMethod(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 11393 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 11394 |
|
| 11395 |
if (!args.thisv().isObject()) { |
| 11396 |
args.rval().setUndefined(); |
| 11397 |
return true; |
| 11398 |
} |
| 11399 |
|
| 11400 |
RootedObject obj(cx, &args.thisv().toObject()); |
| 11401 |
if (JS::GetClass(obj) != &dom_class) { |
| 11402 |
args.rval().set(UndefinedValue()); |
| 11403 |
return true; |
| 11404 |
} |
| 11405 |
|
| 11406 |
JS::Value val = JS::GetReservedSlot(obj, DOM_OBJECT_SLOT); |
| 11407 |
|
| 11408 |
const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev()); |
| 11409 |
MOZ_ASSERT(info->type() == JSJitInfo::Method); |
| 11410 |
JSJitMethodOp method = info->method; |
| 11411 |
return method(cx, obj, val.toPrivate(), JSJitMethodCallArgs(args)); |
| 11412 |
} |
| 11413 |
|
| 11414 |
static void InitDOMObject(HandleObject obj) { |
| 11415 |
JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, |
| 11416 |
PrivateValue(const_cast<void*>(DOM_PRIVATE_VALUE))); |
| 11417 |
JS::SetReservedSlot(obj, DOM_OBJECT_SLOT2, Int32Value(42)); |
| 11418 |
} |
| 11419 |
|
| 11420 |
static JSObject* GetDOMPrototype(JSContext* cx, JSObject* global) { |
| 11421 |
MOZ_ASSERT(JS_IsGlobalObject(global)); |
| 11422 |
if (JS::GetClass(global) != &global_class) { |
| 11423 |
JS_ReportErrorASCII(cx, "Can't get FakeDOMObject prototype in sandbox"); |
| 11424 |
return nullptr; |
| 11425 |
} |
| 11426 |
|
| 11427 |
const JS::Value& slot = JS::GetReservedSlot(global, DOM_PROTOTYPE_SLOT); |
| 11428 |
MOZ_ASSERT(slot.isObject()); |
| 11429 |
return &slot.toObject(); |
| 11430 |
} |
| 11431 |
|
| 11432 |
static bool dom_constructor(JSContext* cx, unsigned argc, JS::Value* vp) { |
| 11433 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 11434 |
|
| 11435 |
RootedObject callee(cx, &args.callee()); |
| 11436 |
RootedValue protov(cx); |
| 11437 |
if (!GetProperty(cx, callee, callee, cx->names().prototype, &protov)) { |
| 11438 |
return false; |
| 11439 |
} |
| 11440 |
|
| 11441 |
if (!protov.isObject()) { |
| 11442 |
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_PROTOTYPE, |
| 11443 |
"FakeDOMObject"); |
| 11444 |
return false; |
| 11445 |
} |
| 11446 |
|
| 11447 |
RootedObject proto(cx, &protov.toObject()); |
| 11448 |
RootedObject domObj(cx, JS_NewObjectWithGivenProto(cx, &dom_class, proto)); |
| 11449 |
if (!domObj) { |
| 11450 |
return false; |
| 11451 |
} |
| 11452 |
|
| 11453 |
InitDOMObject(domObj); |
| 11454 |
|
| 11455 |
args.rval().setObject(*domObj); |
| 11456 |
return true; |
| 11457 |
} |
| 11458 |
|
| 11459 |
static bool InstanceClassHasProtoAtDepth(const JSClass* clasp, uint32_t protoID, |
| 11460 |
uint32_t depth) { |
| 11461 |
// Only the (fake) DOM object supports any JIT optimizations. |
| 11462 |
return clasp == GetDomClass(); |
| 11463 |
} |
| 11464 |
|
| 11465 |
static bool InstanceClassIsError(const JSClass* clasp) { return false; } |
| 11466 |
|
| 11467 |
static bool ShellBuildId(JS::BuildIdCharVector* buildId) { |
| 11468 |
// The browser embeds the date into the buildid and the buildid is embedded |
| 11469 |
// in the binary, so every 'make' necessarily builds a new firefox binary. |
| 11470 |
// Fortunately, the actual firefox executable is tiny -- all the code is in |
| 11471 |
// libxul.so and other shared modules -- so this isn't a big deal. Not so |
| 11472 |
// for the statically-linked JS shell. To avoid recompiling js.cpp and |
| 11473 |
// re-linking 'js' on every 'make', we use a constant buildid and rely on |
| 11474 |
// the shell user to manually clear any caches between cache-breaking updates. |
| 11475 |
const char buildid[] = "JS-shell"; |
| 11476 |
return buildId->append(buildid, sizeof(buildid)); |
| 11477 |
} |
| 11478 |
|
| 11479 |
static bool TimesAccessed(JSContext* cx, unsigned argc, Value* vp) { |
| 11480 |
static int32_t accessed = 0; |
| 11481 |
CallArgs args = CallArgsFromVp(argc, vp); |
| 11482 |
args.rval().setInt32(++accessed); |
| 11483 |
return true; |
| 11484 |
} |
| 11485 |
|
| 11486 |
static const JSPropertySpec TestingProperties[] = { |
| 11487 |
JS_PSG("timesAccessed", TimesAccessed, 0), |
| 11488 |
JS_PS_END, |
| 11489 |
}; |
| 11490 |
|
| 11491 |
static JSObject* NewGlobalObject(JSContext* cx, JS::RealmOptions& options, |
| 11492 |
JSPrincipals* principals, ShellGlobalKind kind, |
| 11493 |
bool immutablePrototype) { |
| 11494 |
RootedObject glob(cx, |
| 11495 |
JS_NewGlobalObject(cx, &global_class, principals, |
| 11496 |
JS::DontFireOnNewGlobalHook, options)); |
| 11497 |
if (!glob) { |
| 11498 |
return nullptr; |
| 11499 |
} |
| 11500 |
|
| 11501 |
{ |
| 11502 |
JSAutoRealm ar(cx, glob); |
| 11503 |
|
| 11504 |
if (kind == ShellGlobalKind::WindowProxy) { |
| 11505 |
RootedObject proxy(cx, NewShellWindowProxy(cx, glob)); |
| 11506 |
if (!proxy) { |
| 11507 |
return nullptr; |
| 11508 |
} |
| 11509 |
js::SetWindowProxy(cx, glob, proxy); |
| 11510 |
} |
| 11511 |
|
| 11512 |
#ifndef LAZY_STANDARD_CLASSES |
| 11513 |
if (!JS::InitRealmStandardClasses(cx)) { |
| 11514 |
return nullptr; |
| 11515 |
} |
| 11516 |
#endif |
| 11517 |
|
| 11518 |
if (immutablePrototype) { |
| 11519 |
bool succeeded; |
| 11520 |
if (!JS_SetImmutablePrototype(cx, glob, &succeeded)) { |
| 11521 |
return nullptr; |
| 11522 |
} |
| 11523 |
MOZ_ASSERT(succeeded, |
| 11524 |
"a fresh, unexposed global object is always capable of " |
| 11525 |
"having its [[Prototype]] be immutable"); |
| 11526 |
} |
| 11527 |
|
| 11528 |
#ifdef JS_HAS_CTYPES |
| 11529 |
if (!fuzzingSafe && !JS::InitCTypesClass(cx, glob)) { |
| 11530 |
return nullptr; |
| 11531 |
} |
| 11532 |
#endif |
| 11533 |
if (!JS_InitReflectParse(cx, glob)) { |
| 11534 |
return nullptr; |
| 11535 |
} |
| 11536 |
if (!JS_DefineDebuggerObject(cx, glob)) { |
| 11537 |
return nullptr; |
| 11538 |
} |
| 11539 |
if (!JS_DefineFunctionsWithHelp(cx, glob, shell_functions) || |
| 11540 |
!JS_DefineProfilingFunctions(cx, glob)) { |
| 11541 |
return nullptr; |
| 11542 |
} |
| 11543 |
#ifdef FUZZING_JS_FUZZILLI |
| 11544 |
if (!JS_DefineFunctions(cx, glob, shell_function_fuzzilli_hash)) { |
| 11545 |
return nullptr; |
| 11546 |
} |
| 11547 |
#endif |
| 11548 |
if (!js::DefineTestingFunctions(cx, glob, fuzzingSafe, |
| 11549 |
disableOOMFunctions)) { |
| 11550 |
return nullptr; |
| 11551 |
} |
| 11552 |
if (!JS_DefineProperties(cx, glob, TestingProperties)) { |
| 11553 |
return nullptr; |
| 11554 |
} |
| 11555 |
|
| 11556 |
if (!fuzzingSafe) { |
| 11557 |
if (!JS_DefineFunctionsWithHelp(cx, glob, fuzzing_unsafe_functions)) { |
| 11558 |
return nullptr; |
| 11559 |
} |
| 11560 |
if (!DefineConsole(cx, glob)) { |
| 11561 |
return nullptr; |
| 11562 |
} |
| 11563 |
} |
| 11564 |
|
| 11565 |
if (!DefineOS(cx, glob, fuzzingSafe, &gOutFile, &gErrFile)) { |
| 11566 |
return nullptr; |
| 11567 |
} |
| 11568 |
|
| 11569 |
if (!js::SupportDifferentialTesting()) { |
| 11570 |
if (!JS_DefineFunctionsWithHelp(cx, glob, |
| 11571 |
diff_testing_unsafe_functions)) { |
| 11572 |
return nullptr; |
| 11573 |
} |
| 11574 |
|
| 11575 |
RootedObject performanceObj(cx, JS_NewObject(cx, nullptr)); |
| 11576 |
if (!performanceObj) { |
| 11577 |
return nullptr; |
| 11578 |
} |
| 11579 |
if (!JS_DefineFunctionsWithHelp(cx, performanceObj, |
| 11580 |
performance_functions)) { |
| 11581 |
return nullptr; |
| 11582 |
} |
| 11583 |
RootedObject mozMemoryObj(cx, JS_NewObject(cx, nullptr)); |
| 11584 |
if (!mozMemoryObj) { |
| 11585 |
return nullptr; |
| 11586 |
} |
| 11587 |
RootedObject gcObj(cx, gc::NewMemoryInfoObject(cx)); |
| 11588 |
if (!gcObj) { |
| 11589 |
return nullptr; |
| 11590 |
} |
| 11591 |
if (!JS_DefineProperty(cx, glob, "performance", performanceObj, |
| 11592 |
JSPROP_ENUMERATE)) { |
| 11593 |
return nullptr; |
| 11594 |
} |
| 11595 |
if (!JS_DefineProperty(cx, performanceObj, "mozMemory", mozMemoryObj, |
| 11596 |
JSPROP_ENUMERATE)) { |
| 11597 |
return nullptr; |
| 11598 |
} |
| 11599 |
if (!JS_DefineProperty(cx, mozMemoryObj, "gc", gcObj, JSPROP_ENUMERATE)) { |
| 11600 |
return nullptr; |
| 11601 |
} |
| 11602 |
} |
| 11603 |
|
| 11604 |
/* Initialize FakeDOMObject. */ |
| 11605 |
static const js::DOMCallbacks DOMcallbacks = {InstanceClassHasProtoAtDepth, |
| 11606 |
InstanceClassIsError}; |
| 11607 |
SetDOMCallbacks(cx, &DOMcallbacks); |
| 11608 |
|
| 11609 |
RootedObject domProto( |
| 11610 |
cx, JS_InitClass(cx, glob, &dom_class, nullptr, "FakeDOMObject", |
| 11611 |
dom_constructor, 0, dom_props, dom_methods, nullptr, |
| 11612 |
nullptr)); |
| 11613 |
if (!domProto) { |
| 11614 |
return nullptr; |
| 11615 |
} |
| 11616 |
|
| 11617 |
// FakeDOMObject.prototype is the only DOM object which needs to retrieved |
| 11618 |
// in the shell; store it directly instead of creating a separate layer |
| 11619 |
// (ProtoAndIfaceCache) as done in the browser. |
| 11620 |
JS::SetReservedSlot(glob, DOM_PROTOTYPE_SLOT, ObjectValue(*domProto)); |
| 11621 |
|
| 11622 |
/* Initialize FakeDOMObject.prototype */ |
| 11623 |
InitDOMObject(domProto); |
| 11624 |
|
| 11625 |
if (!DefineToStringTag(cx, glob, cx->names().global)) { |
| 11626 |
return nullptr; |
| 11627 |
} |
| 11628 |
|
| 11629 |
JS_FireOnNewGlobalObject(cx, glob); |
| 11630 |
} |
| 11631 |
|
| 11632 |
return glob; |
| 11633 |
} |
| 11634 |
|
| 11635 |
static bool BindScriptArgs(JSContext* cx, OptionParser* op) { |
| 11636 |
AutoReportException are(cx); |
| 11637 |
|
| 11638 |
MultiStringRange msr = op->getMultiStringArg("scriptArgs"); |
| 11639 |
RootedObject scriptArgs(cx); |
| 11640 |
scriptArgs = JS::NewArrayObject(cx, 0); |
| 11641 |
if (!scriptArgs) { |
| 11642 |
return false; |
| 11643 |
} |
| 11644 |
|
| 11645 |
if (!JS_DefineProperty(cx, cx->global(), "scriptArgs", scriptArgs, 0)) { |
| 11646 |
return false; |
| 11647 |
} |
| 11648 |
|
| 11649 |
for (size_t i = 0; !msr.empty(); msr.popFront(), ++i) { |
| 11650 |
const char* scriptArg = msr.front(); |
| 11651 |
UniqueChars scriptArgUtf8 = JS::EncodeNarrowToUtf8(cx, scriptArg); |
| 11652 |
if (!scriptArgUtf8) { |
| 11653 |
return false; |
| 11654 |
} |
| 11655 |
RootedString str(cx, NewStringCopyUTF8(cx, scriptArgUtf8.get())); |
| 11656 |
if (!str || !JS_DefineElement(cx, scriptArgs, i, str, JSPROP_ENUMERATE)) { |
| 11657 |
return false; |
| 11658 |
} |
| 11659 |
} |
| 11660 |
|
| 11661 |
RootedValue scriptPathValue(cx); |
| 11662 |
if (const char* scriptPath = op->getStringArg("script")) { |
| 11663 |
UniqueChars scriptPathUtf8 = JS::EncodeNarrowToUtf8(cx, scriptPath); |
| 11664 |
if (!scriptPathUtf8) { |
| 11665 |
return false; |
| 11666 |
} |
| 11667 |
RootedString scriptPathString(cx, |
| 11668 |
NewStringCopyUTF8(cx, scriptPathUtf8.get())); |
| 11669 |
if (!scriptPathString) { |
| 11670 |
return false; |
| 11671 |
} |
| 11672 |
scriptPathValue = StringValue(scriptPathString); |
| 11673 |
} else { |
| 11674 |
scriptPathValue = UndefinedValue(); |
| 11675 |
} |
| 11676 |
|
| 11677 |
if (!JS_DefineProperty(cx, cx->global(), "scriptPath", scriptPathValue, 0)) { |
| 11678 |
return false; |
| 11679 |
} |
| 11680 |
|
| 11681 |
return true; |
| 11682 |
} |
| 11683 |
|
| 11684 |
static bool OptionFailure(const char* option, const char* str) { |
| 11685 |
fprintf(stderr, "Unrecognized option for %s: %s\n", option, str); |
| 11686 |
return false; |
| 11687 |
} |
| 11688 |
|
| 11689 |
template <typename... Ts> |
| 11690 |
auto minVal(Ts... args); |
| 11691 |
template <typename T> |
| 11692 |
auto minVal(T a) { |
| 11693 |
return a; |
| 11694 |
} |
| 11695 |
|
| 11696 |
template <typename T, typename... Ts> |
| 11697 |
auto minVal(T a, Ts... args) { |
| 11698 |
return std::min(a, minVal(args...)); |
| 11699 |
} |
| 11700 |
|
| 11701 |
[[nodiscard]] static bool ProcessArgs(JSContext* cx, OptionParser* op) { |
| 11702 |
ShellContext* sc = GetShellContext(cx); |
| 11703 |
|
| 11704 |
/* |scriptArgs| gets bound on the global before any code is run. */ |
| 11705 |
if (!BindScriptArgs(cx, op)) { |
| 11706 |
return false; |
| 11707 |
} |
| 11708 |
|
| 11709 |
MultiStringRange filePaths = op->getMultiStringOption('f'); |
| 11710 |
MultiStringRange utf16FilePaths = op->getMultiStringOption('u'); |
| 11711 |
MultiStringRange preludePaths = op->getMultiStringOption('p'); |
| 11712 |
MultiStringRange codeChunks = op->getMultiStringOption('e'); |
| 11713 |
MultiStringRange modulePaths = op->getMultiStringOption('m'); |
| 11714 |
|
| 11715 |
#ifdef FUZZING_JS_FUZZILLI |
| 11716 |
// Check for REPRL file source |
| 11717 |
if (op->getBoolOption("reprl")) { |
| 11718 |
return FuzzilliReprlGetAndRun(cx); |
| 11719 |
} |
| 11720 |
#endif /* FUZZING_JS_FUZZILLI */ |
| 11721 |
|
| 11722 |
if (filePaths.empty() && utf16FilePaths.empty() && codeChunks.empty() && |
| 11723 |
modulePaths.empty() && !op->getStringArg("script")) { |
| 11724 |
// Always use the interactive shell when -i is used. Without -i we let |
| 11725 |
// Process figure it out based on isatty. |
| 11726 |
bool forceTTY = op->getBoolOption('i'); |
| 11727 |
return Process(cx, nullptr, forceTTY, FileScript); |
| 11728 |
} |
| 11729 |
|
| 11730 |
while (!preludePaths.empty() || !filePaths.empty() || |
| 11731 |
!utf16FilePaths.empty() || !codeChunks.empty() || |
| 11732 |
!modulePaths.empty()) { |
| 11733 |
size_t ppArgno = preludePaths.empty() ? SIZE_MAX : preludePaths.argno(); |
| 11734 |
size_t fpArgno = filePaths.empty() ? SIZE_MAX : filePaths.argno(); |
| 11735 |
size_t ufpArgno = |
| 11736 |
utf16FilePaths.empty() ? SIZE_MAX : utf16FilePaths.argno(); |
| 11737 |
size_t ccArgno = codeChunks.empty() ? SIZE_MAX : codeChunks.argno(); |
| 11738 |
size_t mpArgno = modulePaths.empty() ? SIZE_MAX : modulePaths.argno(); |
| 11739 |
size_t minArgno = minVal(ppArgno, fpArgno, ufpArgno, ccArgno, mpArgno); |
| 11740 |
|
| 11741 |
if (ppArgno == minArgno) { |
| 11742 |
UniqueChars path = JS::EncodeNarrowToUtf8(cx, preludePaths.front()); |
| 11743 |
if (!path) { |
| 11744 |
return false; |
| 11745 |
} |
| 11746 |
if (!Process(cx, path.get(), false, PreludeScript)) { |
| 11747 |
return false; |
| 11748 |
} |
| 11749 |
|
| 11750 |
preludePaths.popFront(); |
| 11751 |
continue; |
| 11752 |
} |
| 11753 |
|
| 11754 |
if (fpArgno == minArgno) { |
| 11755 |
UniqueChars path = JS::EncodeNarrowToUtf8(cx, filePaths.front()); |
| 11756 |
if (!path) { |
| 11757 |
return false; |
| 11758 |
} |
| 11759 |
if (!Process(cx, path.get(), false, FileScript)) { |
| 11760 |
return false; |
| 11761 |
} |
| 11762 |
|
| 11763 |
filePaths.popFront(); |
| 11764 |
continue; |
| 11765 |
} |
| 11766 |
|
| 11767 |
if (ufpArgno == minArgno) { |
| 11768 |
UniqueChars path = JS::EncodeNarrowToUtf8(cx, utf16FilePaths.front()); |
| 11769 |
if (!path) { |
| 11770 |
return false; |
| 11771 |
} |
| 11772 |
if (!Process(cx, path.get(), false, FileScriptUtf16)) { |
| 11773 |
return false; |
| 11774 |
} |
| 11775 |
|
| 11776 |
utf16FilePaths.popFront(); |
| 11777 |
continue; |
| 11778 |
} |
| 11779 |
|
| 11780 |
if (ccArgno == minArgno) { |
| 11781 |
UniqueChars code = JS::EncodeNarrowToUtf8(cx, codeChunks.front()); |
| 11782 |
if (!code) { |
| 11783 |
return false; |
| 11784 |
} |
| 11785 |
|
| 11786 |
// Command line scripts are always parsed with full-parse to evaluate |
| 11787 |
// conditions which might filter code coverage conditions. |
| 11788 |
JS::CompileOptions opts(cx); |
| 11789 |
opts.setFileAndLine("-e", 1).setForceFullParse(); |
| 11790 |
|
| 11791 |
JS::SourceText<Utf8Unit> srcBuf; |
| 11792 |
if (!srcBuf.init(cx, code.get(), strlen(code.get()), |
| 11793 |
JS::SourceOwnership::Borrowed)) { |
| 11794 |
return false; |
| 11795 |
} |
| 11796 |
|
| 11797 |
RootedValue rval(cx); |
| 11798 |
if (!JS::Evaluate(cx, opts, srcBuf, &rval)) { |
| 11799 |
return false; |
| 11800 |
} |
| 11801 |
|
| 11802 |
codeChunks.popFront(); |
| 11803 |
if (sc->quitting) { |
| 11804 |
break; |
| 11805 |
} |
| 11806 |
|
| 11807 |
continue; |
| 11808 |
} |
| 11809 |
|
| 11810 |
MOZ_ASSERT(mpArgno == minArgno); |
| 11811 |
|
| 11812 |
UniqueChars path = JS::EncodeNarrowToUtf8(cx, modulePaths.front()); |
| 11813 |
if (!path) { |
| 11814 |
return false; |
| 11815 |
} |
| 11816 |
if (!Process(cx, path.get(), false, FileModule)) { |
| 11817 |
return false; |
| 11818 |
} |
| 11819 |
|
| 11820 |
modulePaths.popFront(); |
| 11821 |
} |
| 11822 |
|
| 11823 |
if (sc->quitting) { |
| 11824 |
return false; |
| 11825 |
} |
| 11826 |
|
| 11827 |
/* The |script| argument is processed after all options. */ |
| 11828 |
if (const char* path = op->getStringArg("script")) { |
| 11829 |
UniqueChars pathUtf8 = JS::EncodeNarrowToUtf8(cx, path); |
| 11830 |
if (!pathUtf8) { |
| 11831 |
return false; |
| 11832 |
} |
| 11833 |
if (!Process(cx, pathUtf8.get(), false, FileScript)) { |
| 11834 |
return false; |
| 11835 |
} |
| 11836 |
} |
| 11837 |
|
| 11838 |
if (op->getBoolOption('i')) { |
| 11839 |
if (!Process(cx, nullptr, true, FileScript)) { |
| 11840 |
return false; |
| 11841 |
} |
| 11842 |
} |
| 11843 |
|
| 11844 |
return true; |
| 11845 |
} |
| 11846 |
|
| 11847 |
static void SetWorkerContextOptions(JSContext* cx) { |
| 11848 |
// Copy option values from the main thread. |
| 11849 |
JS::ContextOptionsRef(cx) |
| 11850 |
.setAsmJS(enableAsmJS) |
| 11851 |
.setWasm(enableWasm) |
| 11852 |
.setWasmBaseline(enableWasmBaseline) |
| 11853 |
.setWasmIon(enableWasmOptimizing) |
| 11854 |
|
| 11855 |
.setTestWasmAwaitTier2(enableTestWasmAwaitTier2) |
| 11856 |
.setSourcePragmas(enableSourcePragmas); |
| 11857 |
|
| 11858 |
cx->runtime()->setOffthreadBaselineCompilationEnabled( |
| 11859 |
offthreadBaselineCompilation); |
| 11860 |
cx->runtime()->setOffthreadIonCompilationEnabled(offthreadIonCompilation); |
| 11861 |
cx->runtime()->profilingScripts = |
| 11862 |
enableCodeCoverage || enableDisassemblyDumps; |
| 11863 |
|
| 11864 |
#ifdef JS_GC_ZEAL |
| 11865 |
if (gZealBits && gZealFrequency) { |
| 11866 |
for (size_t i = 0; i < size_t(gc::ZealMode::Count); i++) { |
| 11867 |
if (gZealBits & (1 << i)) { |
| 11868 |
cx->runtime()->gc.setZeal(i, gZealFrequency); |
| 11869 |
} |
| 11870 |
} |
| 11871 |
} |
| 11872 |
#endif |
| 11873 |
|
| 11874 |
JS_SetNativeStackQuota(cx, gWorkerStackSize); |
| 11875 |
} |
| 11876 |
|
| 11877 |
[[nodiscard]] static bool PrintUnhandledRejection( |
| 11878 |
JSContext* cx, Handle<PromiseObject*> promise) { |
| 11879 |
RootedValue reason(cx, promise->reason()); |
| 11880 |
RootedObject site(cx, promise->resolutionSite()); |
| 11881 |
|
| 11882 |
RootedString str(cx, JS_ValueToSource(cx, reason)); |
| 11883 |
if (!str) { |
| 11884 |
return false; |
| 11885 |
} |
| 11886 |
|
| 11887 |
UniqueChars utf8chars = JS_EncodeStringToUTF8(cx, str); |
| 11888 |
if (!utf8chars) { |
| 11889 |
return false; |
| 11890 |
} |
| 11891 |
|
| 11892 |
FILE* fp = ErrorFilePointer(); |
| 11893 |
fprintf(fp, "Unhandled rejection: %s\n", utf8chars.get()); |
| 11894 |
|
| 11895 |
if (!site) { |
| 11896 |
fputs("(no stack trace available)\n", stderr); |
| 11897 |
return true; |
| 11898 |
} |
| 11899 |
|
| 11900 |
JSPrincipals* principals = cx->realm()->principals(); |
| 11901 |
RootedString stackStr(cx); |
| 11902 |
if (!BuildStackString(cx, principals, site, &stackStr, 2)) { |
| 11903 |
return false; |
| 11904 |
} |
| 11905 |
|
| 11906 |
UniqueChars stack = JS_EncodeStringToUTF8(cx, stackStr); |
| 11907 |
if (!stack) { |
| 11908 |
return false; |
| 11909 |
} |
| 11910 |
|
| 11911 |
fputs("Stack:\n", fp); |
| 11912 |
fputs(stack.get(), fp); |
| 11913 |
|
| 11914 |
return true; |
| 11915 |
} |
| 11916 |
|
| 11917 |
[[nodiscard]] static bool ReportUnhandledRejections(JSContext* cx) { |
| 11918 |
ShellContext* sc = GetShellContext(cx); |
| 11919 |
if (!sc->trackUnhandledRejections) { |
| 11920 |
return true; |
| 11921 |
} |
| 11922 |
|
| 11923 |
if (!sc->unhandledRejectedPromises) { |
| 11924 |
return true; |
| 11925 |
} |
| 11926 |
|
| 11927 |
AutoRealm ar(cx, sc->unhandledRejectedPromises); |
| 11928 |
|
| 11929 |
if (sc->unhandledRejectedPromises->size() == 0) { |
| 11930 |
return true; |
| 11931 |
} |
| 11932 |
|
| 11933 |
sc->exitCode = EXITCODE_RUNTIME_ERROR; |
| 11934 |
|
| 11935 |
RootedValue iter(cx); |
| 11936 |
if (!SetObject::iterator(cx, SetObject::IteratorKind::Values, |
| 11937 |
sc->unhandledRejectedPromises, &iter)) { |
| 11938 |
return false; |
| 11939 |
} |
| 11940 |
|
| 11941 |
Rooted<SetIteratorObject*> iterObj(cx, |
| 11942 |
&iter.toObject().as<SetIteratorObject>()); |
| 11943 |
JSObject* obj = SetIteratorObject::createResult(cx); |
| 11944 |
if (!obj) { |
| 11945 |
return false; |
| 11946 |
} |
| 11947 |
|
| 11948 |
Rooted<ArrayObject*> resultObj(cx, &obj->as<ArrayObject>()); |
| 11949 |
while (true) { |
| 11950 |
bool done = SetIteratorObject::next(iterObj, resultObj); |
| 11951 |
if (done) { |
| 11952 |
break; |
| 11953 |
} |
| 11954 |
|
| 11955 |
RootedObject obj(cx, &resultObj->getDenseElement(0).toObject()); |
| 11956 |
Rooted<PromiseObject*> promise(cx, obj->maybeUnwrapIf<PromiseObject>()); |
| 11957 |
if (!promise) { |
| 11958 |
FILE* fp = ErrorFilePointer(); |
| 11959 |
fputs( |
| 11960 |
"Unhandled rejection: dead proxy found in unhandled " |
| 11961 |
"rejections set\n", |
| 11962 |
fp); |
| 11963 |
continue; |
| 11964 |
} |
| 11965 |
|
| 11966 |
AutoRealm ar2(cx, promise); |
| 11967 |
|
| 11968 |
if (!PrintUnhandledRejection(cx, promise)) { |
| 11969 |
return false; |
| 11970 |
} |
| 11971 |
} |
| 11972 |
|
| 11973 |
sc->unhandledRejectedPromises = nullptr; |
| 11974 |
|
| 11975 |
return true; |
| 11976 |
} |
| 11977 |
|
| 11978 |
bool ShellContext::registerWithCx(JSContext* cx) { |
| 11979 |
cx_ = cx; |
| 11980 |
JS_SetContextPrivate(cx, this); |
| 11981 |
|
| 11982 |
if (isWorker) { |
| 11983 |
SetWorkerContextOptions(cx); |
| 11984 |
} |
| 11985 |
|
| 11986 |
JS::SetWarningReporter(cx, WarningReporter); |
| 11987 |
JS_SetFutexCanWait(cx); |
| 11988 |
JS_InitDestroyPrincipalsCallback(cx, ShellPrincipals::destroy); |
| 11989 |
JS_SetDestroyCompartmentCallback(cx, DestroyShellCompartmentPrivate); |
| 11990 |
js::SetWindowProxyClass(cx, &ShellWindowProxyClass); |
| 11991 |
|
| 11992 |
js::UseInternalJobQueues(cx); |
| 11993 |
|
| 11994 |
js::SetPreserveWrapperCallbacks(cx, DummyPreserveWrapperCallback, |
| 11995 |
DummyHasReleasedWrapperCallback); |
| 11996 |
|
| 11997 |
JS::SetHostCleanupFinalizationRegistryCallback( |
| 11998 |
cx, ShellCleanupFinalizationRegistryCallback, this); |
| 11999 |
JS_AddExtraGCRootsTracer(cx, TraceBlackRoots, nullptr); |
| 12000 |
JS_SetGrayGCRootsTracer(cx, TraceGrayRoots, nullptr); |
| 12001 |
|
| 12002 |
return true; |
| 12003 |
} |
| 12004 |
|
| 12005 |
ShellContext::~ShellContext() { |
| 12006 |
markObservers.reset(); |
| 12007 |
if (cx_) { |
| 12008 |
JS_SetContextPrivate(cx_, nullptr); |
| 12009 |
JS::SetHostCleanupFinalizationRegistryCallback(cx_, nullptr, nullptr); |
| 12010 |
JS_SetGrayGCRootsTracer(cx_, nullptr, nullptr); |
| 12011 |
JS_RemoveExtraGCRootsTracer(cx_, TraceBlackRoots, nullptr); |
| 12012 |
} |
| 12013 |
MOZ_ASSERT(offThreadJobs.empty()); |
| 12014 |
} |
| 12015 |
|
| 12016 |
static int Shell(JSContext* cx, OptionParser* op) { |
| 12017 |
#ifdef JS_STRUCTURED_SPEW |
| 12018 |
cx->spewer().enableSpewing(); |
| 12019 |
#endif |
| 12020 |
|
| 12021 |
auto exitShell = MakeScopeExit([&] { |
| 12022 |
#ifdef JS_STRUCTURED_SPEW |
| 12023 |
cx->spewer().disableSpewing(); |
| 12024 |
#endif |
| 12025 |
}); |
| 12026 |
|
| 12027 |
#ifdef MOZ_CODE_COVERAGE |
| 12028 |
InstallCoverageSignalHandlers(); |
| 12029 |
#endif |
| 12030 |
|
| 12031 |
Maybe<JS::AutoDisableGenerationalGC> noggc; |
| 12032 |
if (op->getBoolOption("no-ggc")) { |
| 12033 |
noggc.emplace(cx); |
| 12034 |
} |
| 12035 |
|
| 12036 |
Maybe<AutoDisableCompactingGC> nocgc; |
| 12037 |
if (op->getBoolOption("no-cgc")) { |
| 12038 |
nocgc.emplace(cx); |
| 12039 |
} |
| 12040 |
|
| 12041 |
#ifdef DEBUG |
| 12042 |
if (op->getBoolOption("differential-testing")) { |
| 12043 |
JS::SetSupportDifferentialTesting(true); |
| 12044 |
} |
| 12045 |
#endif |
| 12046 |
|
| 12047 |
if (op->getBoolOption("disable-oom-functions")) { |
| 12048 |
disableOOMFunctions = true; |
| 12049 |
} |
| 12050 |
|
| 12051 |
if (op->getBoolOption("more-compartments")) { |
| 12052 |
defaultToSameCompartment = false; |
| 12053 |
} |
| 12054 |
|
| 12055 |
bool reprl_mode = FuzzilliUseReprlMode(op); |
| 12056 |
|
| 12057 |
// Begin REPRL Loop |
| 12058 |
int result = EXIT_SUCCESS; |
| 12059 |
do { |
| 12060 |
JS::RealmOptions options; |
| 12061 |
SetStandardRealmOptions(options); |
| 12062 |
RootedObject glob( |
| 12063 |
cx, NewGlobalObject(cx, options, nullptr, ShellGlobalKind::WindowProxy, |
| 12064 |
/* immutablePrototype = */ true)); |
| 12065 |
if (!glob) { |
| 12066 |
return 1; |
| 12067 |
} |
| 12068 |
|
| 12069 |
JSAutoRealm ar(cx, glob); |
| 12070 |
|
| 12071 |
ShellContext* sc = GetShellContext(cx); |
| 12072 |
if (!sc->moduleLoader && !InitModuleLoader(cx, *op)) { |
| 12073 |
return EXIT_FAILURE; |
| 12074 |
} |
| 12075 |
|
| 12076 |
#ifdef FUZZING_INTERFACES |
| 12077 |
if (fuzzHaveModule) { |
| 12078 |
return FuzzJSRuntimeStart(cx, &sArgc, &sArgv); |
| 12079 |
} |
| 12080 |
#endif |
| 12081 |
|
| 12082 |
sc->exitCode = 0; |
| 12083 |
result = EXIT_SUCCESS; |
| 12084 |
{ |
| 12085 |
AutoReportException are(cx); |
| 12086 |
if (!ProcessArgs(cx, op) && !sc->quitting) { |
| 12087 |
result = EXITCODE_RUNTIME_ERROR; |
| 12088 |
} |
| 12089 |
} |
| 12090 |
|
| 12091 |
/* |
| 12092 |
* The job queue must be drained even on error to finish outstanding async |
| 12093 |
* tasks before the main thread JSRuntime is torn down. Drain after |
| 12094 |
* uncaught exceptions have been reported since draining runs callbacks. |
| 12095 |
*/ |
| 12096 |
RunShellJobs(cx); |
| 12097 |
|
| 12098 |
// Only if there's no other error, report unhandled rejections. |
| 12099 |
if (!result && !sc->exitCode) { |
| 12100 |
AutoReportException are(cx); |
| 12101 |
if (!ReportUnhandledRejections(cx)) { |
| 12102 |
FILE* fp = ErrorFilePointer(); |
| 12103 |
fputs("Error while printing unhandled rejection\n", fp); |
| 12104 |
} |
| 12105 |
} |
| 12106 |
|
| 12107 |
if (sc->exitCode) { |
| 12108 |
result = sc->exitCode; |
| 12109 |
} |
| 12110 |
|
| 12111 |
#ifdef FUZZING_JS_FUZZILLI |
| 12112 |
if (reprl_mode) { |
| 12113 |
fflush(stdout); |
| 12114 |
fflush(stderr); |
| 12115 |
// Send return code to parent and reset edge counters. |
| 12116 |
int status = (result & 0xff) << 8; |
| 12117 |
if (js::SupportDifferentialTesting()) { |
| 12118 |
struct { |
| 12119 |
int status; |
| 12120 |
uint32_t execHash; |
| 12121 |
uint32_t execHashInputs; |
| 12122 |
} s; |
| 12123 |
s.status = status; |
| 12124 |
s.execHash = cx->executionHash; |
| 12125 |
s.execHashInputs = cx->executionHashInputs; |
| 12126 |
MOZ_RELEASE_ASSERT(write(REPRL_CWFD, &s, 12) == 12); |
| 12127 |
} else { |
| 12128 |
MOZ_RELEASE_ASSERT(write(REPRL_CWFD, &status, 4) == 4); |
| 12129 |
} |
| 12130 |
__sanitizer_cov_reset_edgeguards(); |
| 12131 |
cx->executionHash = 1; |
| 12132 |
cx->executionHashInputs = 0; |
| 12133 |
} |
| 12134 |
#endif |
| 12135 |
|
| 12136 |
if (enableDisassemblyDumps) { |
| 12137 |
AutoReportException are(cx); |
| 12138 |
if (!js::DumpRealmPCCounts(cx)) { |
| 12139 |
result = EXITCODE_OUT_OF_MEMORY; |
| 12140 |
} |
| 12141 |
} |
| 12142 |
|
| 12143 |
// End REPRL loop |
| 12144 |
} while (reprl_mode); |
| 12145 |
|
| 12146 |
return result; |
| 12147 |
} |
| 12148 |
|
| 12149 |
// Used to allocate memory when jemalloc isn't yet initialized. |
| 12150 |
JS_DECLARE_NEW_METHODS(SystemAlloc_New, malloc, static) |
| 12151 |
|
| 12152 |
static void SetOutputFile(const char* const envVar, RCFile* defaultOut, |
| 12153 |
RCFile** outFileP) { |
| 12154 |
RCFile* outFile; |
| 12155 |
|
| 12156 |
const char* outPath = getenv(envVar); |
| 12157 |
FILE* newfp; |
| 12158 |
if (outPath && *outPath && (newfp = fopen(outPath, "w"))) { |
| 12159 |
outFile = SystemAlloc_New<RCFile>(newfp); |
| 12160 |
} else { |
| 12161 |
outFile = defaultOut; |
| 12162 |
} |
| 12163 |
|
| 12164 |
if (!outFile) { |
| 12165 |
MOZ_CRASH("Failed to allocate output file"); |
| 12166 |
} |
| 12167 |
|
| 12168 |
outFile->acquire(); |
| 12169 |
*outFileP = outFile; |
| 12170 |
} |
| 12171 |
|
| 12172 |
static void PreInit() { |
| 12173 |
#ifdef XP_WIN |
| 12174 |
const char* crash_option = getenv("XRE_NO_WINDOWS_CRASH_DIALOG"); |
| 12175 |
if (crash_option && crash_option[0] == '1') { |
| 12176 |
// Disable the segfault dialog. We want to fail the tests immediately |
| 12177 |
// instead of hanging automation. |
| 12178 |
UINT newMode = SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX; |
| 12179 |
UINT prevMode = SetErrorMode(newMode); |
| 12180 |
SetErrorMode(prevMode | newMode); |
| 12181 |
} |
| 12182 |
#endif |
| 12183 |
} |
| 12184 |
|
| 12185 |
#ifndef JS_WITHOUT_NSPR |
| 12186 |
class AutoLibraryLoader { |
| 12187 |
Vector<PRLibrary*, 4, SystemAllocPolicy> libraries; |
| 12188 |
|
| 12189 |
public: |
| 12190 |
~AutoLibraryLoader() { |
| 12191 |
for (auto dll : libraries) { |
| 12192 |
PR_UnloadLibrary(dll); |
| 12193 |
} |
| 12194 |
} |
| 12195 |
|
| 12196 |
PRLibrary* load(const char* path) { |
| 12197 |
PRLibSpec libSpec; |
| 12198 |
libSpec.type = PR_LibSpec_Pathname; |
| 12199 |
libSpec.value.pathname = path; |
| 12200 |
PRLibrary* dll = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW | PR_LD_GLOBAL); |
| 12201 |
if (!dll) { |
| 12202 |
fprintf(stderr, "LoadLibrary '%s' failed with code %d\n", path, |
| 12203 |
PR_GetError()); |
| 12204 |
MOZ_CRASH("Failed to load library"); |
| 12205 |
} |
| 12206 |
|
| 12207 |
MOZ_ALWAYS_TRUE(libraries.append(dll)); |
| 12208 |
return dll; |
| 12209 |
} |
| 12210 |
}; |
| 12211 |
#endif |
| 12212 |
|
| 12213 |
static bool ReadSelfHostedXDRFile(JSContext* cx, FileContents& buf) { |
| 12214 |
FILE* file = fopen(selfHostedXDRPath, "rb"); |
| 12215 |
if (!file) { |
| 12216 |
fprintf(stderr, "Can't open self-hosted stencil XDR file.\n"); |
| 12217 |
return false; |
| 12218 |
} |
| 12219 |
AutoCloseFile autoClose(file); |
| 12220 |
|
| 12221 |
struct stat st; |
| 12222 |
if (fstat(fileno(file), &st) < 0) { |
| 12223 |
fprintf(stderr, "Unable to stat self-hosted stencil XDR file.\n"); |
| 12224 |
return false; |
| 12225 |
} |
| 12226 |
|
| 12227 |
if (st.st_size >= INT32_MAX) { |
| 12228 |
fprintf(stderr, "self-hosted stencil XDR file too large.\n"); |
| 12229 |
return false; |
| 12230 |
} |
| 12231 |
uint32_t filesize = uint32_t(st.st_size); |
| 12232 |
|
| 12233 |
if (!buf.growBy(filesize)) { |
| 12234 |
return false; |
| 12235 |
} |
| 12236 |
size_t cc = fread(buf.begin(), 1, filesize, file); |
| 12237 |
if (cc != filesize) { |
| 12238 |
fprintf(stderr, "Short read on self-hosted stencil XDR file.\n"); |
| 12239 |
return false; |
| 12240 |
} |
| 12241 |
|
| 12242 |
return true; |
| 12243 |
} |
| 12244 |
|
| 12245 |
static bool WriteSelfHostedXDRFile(JSContext* cx, JS::SelfHostedCache buffer) { |
| 12246 |
FILE* file = fopen(selfHostedXDRPath, "wb"); |
| 12247 |
if (!file) { |
| 12248 |
JS_ReportErrorUTF8(cx, "Can't open self-hosted stencil XDR file."); |
| 12249 |
return false; |
| 12250 |
} |
| 12251 |
AutoCloseFile autoClose(file); |
| 12252 |
|
| 12253 |
size_t cc = fwrite(buffer.Elements(), 1, buffer.LengthBytes(), file); |
| 12254 |
if (cc != buffer.LengthBytes()) { |
| 12255 |
JS_ReportErrorUTF8(cx, "Short write on self-hosted stencil XDR file."); |
| 12256 |
return false; |
| 12257 |
} |
| 12258 |
|
| 12259 |
return true; |
| 12260 |
} |
| 12261 |
|
| 12262 |
static bool SetGCParameterFromArg(JSContext* cx, char* arg) { |
| 12263 |
char* c = strchr(arg, '='); |
| 12264 |
if (!c) { |
| 12265 |
fprintf(stderr, |
| 12266 |
"Error: --gc-param argument '%s' must be of the form " |
| 12267 |
"name=decimalValue\n", |
| 12268 |
arg); |
| 12269 |
return false; |
| 12270 |
} |
| 12271 |
|
| 12272 |
*c = '\0'; |
| 12273 |
const char* name = arg; |
| 12274 |
const char* valueStr = c + 1; |
| 12275 |
|
| 12276 |
JSGCParamKey key; |
| 12277 |
bool writable; |
| 12278 |
if (!GetGCParameterInfo(name, &key, &writable)) { |
| 12279 |
fprintf(stderr, "Error: Unknown GC parameter name '%s'\n", name); |
| 12280 |
fprintf(stderr, "Writable GC parameter names are:\n"); |
| 12281 |
#define PRINT_WRITABLE_PARAM_NAME(name, _, writable) \ |
| 12282 |
if (writable) { \ |
| 12283 |
fprintf(stderr, " %s\n", name); \ |
| 12284 |
} |
| 12285 |
FOR_EACH_GC_PARAM(PRINT_WRITABLE_PARAM_NAME) |
| 12286 |
#undef PRINT_WRITABLE_PARAM_NAME |
| 12287 |
return false; |
| 12288 |
} |
| 12289 |
|
| 12290 |
if (!writable) { |
| 12291 |
fprintf(stderr, "Error: GC parameter '%s' is not writable\n", name); |
| 12292 |
return false; |
| 12293 |
} |
| 12294 |
|
| 12295 |
char* end = nullptr; |
| 12296 |
unsigned long int value = strtoul(valueStr, &end, 10); |
| 12297 |
if (end == valueStr || *end) { |
| 12298 |
fprintf(stderr, |
| 12299 |
"Error: Could not parse '%s' as decimal for GC parameter '%s'\n", |
| 12300 |
valueStr, name); |
| 12301 |
return false; |
| 12302 |
} |
| 12303 |
|
| 12304 |
uint32_t paramValue = uint32_t(value); |
| 12305 |
if (value == ULONG_MAX || value != paramValue || |
| 12306 |
!cx->runtime()->gc.setParameter(cx, key, paramValue)) { |
| 12307 |
fprintf(stderr, "Error: Value %s is out of range for GC parameter '%s'\n", |
| 12308 |
valueStr, name); |
| 12309 |
return false; |
| 12310 |
} |
| 12311 |
|
| 12312 |
return true; |
| 12313 |
} |
| 12314 |
|
| 12315 |
int main(int argc, char** argv) { |
| 12316 |
PreInit(); |
| 12317 |
|
| 12318 |
sArgc = argc; |
| 12319 |
sArgv = argv; |
| 12320 |
|
| 12321 |
int result; |
| 12322 |
|
| 12323 |
setlocale(LC_ALL, ""); |
| 12324 |
|
| 12325 |
// Special-case stdout and stderr. We bump their refcounts to prevent them |
| 12326 |
// from getting closed and then having some printf fail somewhere. |
| 12327 |
RCFile rcStdout(stdout); |
| 12328 |
rcStdout.acquire(); |
| 12329 |
RCFile rcStderr(stderr); |
| 12330 |
rcStderr.acquire(); |
| 12331 |
|
| 12332 |
SetOutputFile("JS_STDOUT", &rcStdout, &gOutFile); |
| 12333 |
SetOutputFile("JS_STDERR", &rcStderr, &gErrFile); |
| 12334 |
|
| 12335 |
#ifdef MOZ_MEMORY |
| 12336 |
// Use a larger jemalloc page cache. This should match the value for browser |
| 12337 |
// foreground processes in ContentChild::RecvNotifyProcessPriorityChanged. |
| 12338 |
moz_set_max_dirty_page_modifier(4); |
| 12339 |
#endif |
| 12340 |
|
| 12341 |
OptionParser op("Usage: {progname} [options] [[script] scriptArgs*]"); |
| 12342 |
if (!InitOptionParser(op)) { |
| 12343 |
return EXIT_FAILURE; |
| 12344 |
} |
| 12345 |
|
| 12346 |
switch (op.parseArgs(argc, argv)) { |
| 12347 |
case OptionParser::EarlyExit: |
| 12348 |
return EXIT_SUCCESS; |
| 12349 |
case OptionParser::ParseError: |
| 12350 |
op.printHelp(argv[0]); |
| 12351 |
return EXIT_FAILURE; |
| 12352 |
case OptionParser::Fail: |
| 12353 |
return EXIT_FAILURE; |
| 12354 |
case OptionParser::Okay: |
| 12355 |
break; |
| 12356 |
} |
| 12357 |
|
| 12358 |
if (op.getHelpOption()) { |
| 12359 |
return EXIT_SUCCESS; |
| 12360 |
} |
| 12361 |
|
| 12362 |
if (!SetGlobalOptionsPreJSInit(op)) { |
| 12363 |
return EXIT_FAILURE; |
| 12364 |
} |
| 12365 |
|
| 12366 |
// Start the engine. |
| 12367 |
if (const char* message = JS_InitWithFailureDiagnostic()) { |
| 12368 |
fprintf(gErrFile->fp, "JS_Init failed: %s\n", message); |
| 12369 |
return 1; |
| 12370 |
} |
| 12371 |
|
| 12372 |
// `selfHostedXDRBuffer` contains XDR buffer of the self-hosted JS. |
| 12373 |
// A part of it is borrowed by ImmutableScriptData of the self-hosted scripts. |
| 12374 |
// |
| 12375 |
// This buffer should outlive JS_Shutdown. |
| 12376 |
Maybe<FileContents> selfHostedXDRBuffer; |
| 12377 |
|
| 12378 |
auto shutdownEngine = MakeScopeExit([] { JS_ShutDown(); }); |
| 12379 |
|
| 12380 |
if (!SetGlobalOptionsPostJSInit(op)) { |
| 12381 |
return EXIT_FAILURE; |
| 12382 |
} |
| 12383 |
|
| 12384 |
if (!InitSharedObjectMailbox()) { |
| 12385 |
return EXIT_FAILURE; |
| 12386 |
} |
| 12387 |
|
| 12388 |
JS::SetProcessBuildIdOp(ShellBuildId); |
| 12389 |
|
| 12390 |
/* Use the same parameters as the browser in xpcjsruntime.cpp. */ |
| 12391 |
JSContext* const cx = JS_NewContext(JS::DefaultHeapMaxBytes); |
| 12392 |
if (!cx) { |
| 12393 |
return 1; |
| 12394 |
} |
| 12395 |
|
| 12396 |
if (!JS::SetLoggingInterface(shellLoggingInterface)) { |
| 12397 |
return 1; |
| 12398 |
} |
| 12399 |
ParseLoggerOptions(); |
| 12400 |
|
| 12401 |
// Register telemetry callbacks. |
| 12402 |
JS_SetAccumulateTelemetryCallback(cx, AccumulateTelemetryDataCallback); |
| 12403 |
JS_SetSetUseCounterCallback(cx, SetUseCounterCallback); |
| 12404 |
|
| 12405 |
auto destroyCx = MakeScopeExit([cx] { JS_DestroyContext(cx); }); |
| 12406 |
|
| 12407 |
UniquePtr<ShellContext> sc = |
| 12408 |
MakeUnique<ShellContext>(cx, ShellContext::MainThread); |
| 12409 |
if (!sc || !sc->registerWithCx(cx)) { |
| 12410 |
return 1; |
| 12411 |
} |
| 12412 |
|
| 12413 |
if (!SetContextOptions(cx, op)) { |
| 12414 |
return 1; |
| 12415 |
} |
| 12416 |
|
| 12417 |
JS_SetTrustedPrincipals(cx, &ShellPrincipals::fullyTrusted); |
| 12418 |
JS_SetSecurityCallbacks(cx, &ShellPrincipals::securityCallbacks); |
| 12419 |
|
| 12420 |
JS_AddInterruptCallback(cx, ShellInterruptCallback); |
| 12421 |
|
| 12422 |
JS::SetGCSliceCallback(cx, GCSliceCallback); |
| 12423 |
|
| 12424 |
bufferStreamState = js_new<ExclusiveWaitableData<BufferStreamState>>( |
| 12425 |
mutexid::BufferStreamState); |
| 12426 |
if (!bufferStreamState) { |
| 12427 |
return 1; |
| 12428 |
} |
| 12429 |
auto shutdownBufferStreams = MakeScopeExit([] { |
| 12430 |
ShutdownBufferStreams(); |
| 12431 |
js_delete(bufferStreamState); |
| 12432 |
}); |
| 12433 |
JS::InitConsumeStreamCallback(cx, ConsumeBufferSource, ReportStreamError); |
| 12434 |
|
| 12435 |
JS::SetPromiseRejectionTrackerCallback( |
| 12436 |
cx, ForwardingPromiseRejectionTrackerCallback); |
| 12437 |
|
| 12438 |
JS::dbg::SetDebuggerMallocSizeOf(cx, moz_malloc_size_of); |
| 12439 |
|
| 12440 |
auto shutdownShellThreads = MakeScopeExit([cx] { |
| 12441 |
KillWatchdog(cx); |
| 12442 |
KillWorkerThreads(cx); |
| 12443 |
DestructSharedObjectMailbox(); |
| 12444 |
CancelOffThreadJobsForRuntime(cx); |
| 12445 |
}); |
| 12446 |
|
| 12447 |
// The file content should stay alive as long as Worker thread can be |
| 12448 |
// initialized. |
| 12449 |
JS::SelfHostedCache xdrSpan = nullptr; |
| 12450 |
JS::SelfHostedWriter xdrWriter = nullptr; |
| 12451 |
if (selfHostedXDRPath) { |
| 12452 |
if (encodeSelfHostedCode) { |
| 12453 |
xdrWriter = WriteSelfHostedXDRFile; |
| 12454 |
} else { |
| 12455 |
selfHostedXDRBuffer.emplace(cx); |
| 12456 |
if (ReadSelfHostedXDRFile(cx, *selfHostedXDRBuffer)) { |
| 12457 |
MOZ_ASSERT(selfHostedXDRBuffer->length() > 0); |
| 12458 |
JS::SelfHostedCache span(selfHostedXDRBuffer->begin(), |
| 12459 |
selfHostedXDRBuffer->end()); |
| 12460 |
xdrSpan = span; |
| 12461 |
} else { |
| 12462 |
fprintf(stderr, "Falling back on parsing source.\n"); |
| 12463 |
selfHostedXDRPath = nullptr; |
| 12464 |
} |
| 12465 |
} |
| 12466 |
} |
| 12467 |
|
| 12468 |
if (!JS::InitSelfHostedCode(cx, xdrSpan, xdrWriter)) { |
| 12469 |
return 1; |
| 12470 |
} |
| 12471 |
|
| 12472 |
EnvironmentPreparer environmentPreparer(cx); |
| 12473 |
|
| 12474 |
JS::SetProcessLargeAllocationFailureCallback(my_LargeAllocFailCallback); |
| 12475 |
|
| 12476 |
if (op.getBoolOption("wasm-compile-and-serialize")) { |
| 12477 |
#ifdef __wasi__ |
| 12478 |
MOZ_CRASH("WASI doesn't support wasm"); |
| 12479 |
#else |
| 12480 |
if (!WasmCompileAndSerialize(cx)) { |
| 12481 |
// Errors have been printed directly to stderr. |
| 12482 |
MOZ_ASSERT(!cx->isExceptionPending()); |
| 12483 |
return EXIT_FAILURE; |
| 12484 |
} |
| 12485 |
#endif |
| 12486 |
return EXIT_SUCCESS; |
| 12487 |
} |
| 12488 |
|
| 12489 |
result = Shell(cx, &op); |
| 12490 |
|
| 12491 |
#ifdef DEBUG |
| 12492 |
if (OOM_printAllocationCount) { |
| 12493 |
printf("OOM max count: %" PRIu64 "\n", js::oom::simulator.counter()); |
| 12494 |
} |
| 12495 |
#endif |
| 12496 |
|
| 12497 |
return result; |
| 12498 |
} |
| 12499 |
|
| 12500 |
bool InitOptionParser(OptionParser& op) { |
| 12501 |
op.setDescription( |
| 12502 |
"The SpiderMonkey shell provides a command line interface to the " |
| 12503 |
"JavaScript engine. Code and file options provided via the command line " |
| 12504 |
"are " |
| 12505 |
"run left to right. If provided, the optional script argument is run " |
| 12506 |
"after " |
| 12507 |
"all options have been processed. Just-In-Time compilation modes may be " |
| 12508 |
"enabled via " |
| 12509 |
"command line options."); |
| 12510 |
op.setDescriptionWidth(72); |
| 12511 |
op.setHelpWidth(80); |
| 12512 |
op.setVersion(JS_GetImplementationVersion()); |
| 12513 |
|
| 12514 |
if (!op.addMultiStringOption( |
| 12515 |
'f', "file", "PATH", |
| 12516 |
"File path to run, parsing file contents as UTF-8") || |
| 12517 |
!op.addMultiStringOption( |
| 12518 |
'u', "utf16-file", "PATH", |
| 12519 |
"File path to run, inflating the file's UTF-8 contents to UTF-16 and " |
| 12520 |
"then parsing that") || |
| 12521 |
!op.addMultiStringOption('m', "module", "PATH", "Module path to run") || |
| 12522 |
!op.addMultiStringOption('p', "prelude", "PATH", "Prelude path to run") || |
| 12523 |
!op.addMultiStringOption('e', "execute", "CODE", "Inline code to run") || |
| 12524 |
!op.addStringOption('\0', "selfhosted-xdr-path", "[filename]", |
| 12525 |
"Read/Write selfhosted script data from/to the given " |
| 12526 |
"XDR file") || |
| 12527 |
!op.addStringOption('\0', "selfhosted-xdr-mode", "(encode,decode,off)", |
| 12528 |
"Whether to encode/decode data of the file provided" |
| 12529 |
"with --selfhosted-xdr-path.") || |
| 12530 |
!op.addBoolOption('i', "shell", "Enter prompt after running code") || |
| 12531 |
!op.addBoolOption('c', "compileonly", |
| 12532 |
"Only compile, don't run (syntax checking mode)") || |
| 12533 |
!op.addBoolOption('w', "warnings", "Emit warnings") || |
| 12534 |
!op.addBoolOption('W', "nowarnings", "Don't emit warnings") || |
| 12535 |
!op.addBoolOption('D', "dump-bytecode", |
| 12536 |
"Dump bytecode with exec count for all scripts") || |
| 12537 |
!op.addBoolOption('b', "print-timing", |
| 12538 |
"Print sub-ms runtime for each file that's run") || |
| 12539 |
!op.addBoolOption('\0', "code-coverage", |
| 12540 |
"Enable code coverage instrumentation.") || |
| 12541 |
!op.addBoolOption( |
| 12542 |
'\0', "disable-parser-deferred-alloc", |
| 12543 |
"Disable deferred allocation of GC objects until after parser") || |
| 12544 |
#ifdef DEBUG |
| 12545 |
!op.addBoolOption('O', "print-alloc", |
| 12546 |
"Print the number of allocations at exit") || |
| 12547 |
#endif |
| 12548 |
!op.addOptionalStringArg("script", |
| 12549 |
"A script to execute (after all options)") || |
| 12550 |
!op.addOptionalMultiStringArg( |
| 12551 |
"scriptArgs", |
| 12552 |
"String arguments to bind as |scriptArgs| in the " |
| 12553 |
"shell's global") || |
| 12554 |
!op.addIntOption( |
| 12555 |
'\0', "cpu-count", "COUNT", |
| 12556 |
"Set the number of CPUs (hardware threads) to COUNT, the " |
| 12557 |
"default is the actual number of CPUs. The total number of " |
| 12558 |
"background helper threads is the CPU count plus some constant.", |
| 12559 |
-1) || |
| 12560 |
!op.addIntOption('\0', "thread-count", "COUNT", "Alias for --cpu-count.", |
| 12561 |
-1) || |
| 12562 |
!op.addBoolOption('\0', "ion", "Enable IonMonkey (default)") || |
| 12563 |
!op.addBoolOption('\0', "no-ion", "Disable IonMonkey") || |
| 12564 |
!op.addBoolOption('\0', "no-ion-for-main-context", |
| 12565 |
"Disable IonMonkey for the main context only") || |
| 12566 |
!op.addIntOption('\0', "inlining-entry-threshold", "COUNT", |
| 12567 |
"The minimum stub entry count before trial-inlining a" |
| 12568 |
" call", |
| 12569 |
-1) || |
| 12570 |
!op.addIntOption('\0', "small-function-length", "COUNT", |
| 12571 |
"The maximum bytecode length of a 'small function' for " |
| 12572 |
"the purpose of inlining.", |
| 12573 |
-1) || |
| 12574 |
!op.addBoolOption('\0', "only-inline-selfhosted", |
| 12575 |
"Only inline selfhosted functions") || |
| 12576 |
!op.addBoolOption('\0', "no-asmjs", "Disable asm.js compilation") || |
| 12577 |
!op.addStringOption( |
| 12578 |
'\0', "wasm-compiler", "[option]", |
| 12579 |
"Choose to enable a subset of the wasm compilers, valid options are " |
| 12580 |
"'none', 'baseline', 'ion', 'optimizing', " |
| 12581 |
"'baseline+ion', 'baseline+optimizing'.") || |
| 12582 |
!op.addBoolOption('\0', "wasm-verbose", |
| 12583 |
"Enable WebAssembly verbose logging") || |
| 12584 |
!op.addBoolOption('\0', "disable-wasm-huge-memory", |
| 12585 |
"Disable WebAssembly huge memory") || |
| 12586 |
!op.addBoolOption('\0', "test-wasm-await-tier2", |
| 12587 |
"Forcibly activate tiering and block " |
| 12588 |
"instantiation on completion of tier2") || |
| 12589 |
!op.addBoolOption('\0', "no-native-regexp", |
| 12590 |
"Disable native regexp compilation") || |
| 12591 |
!op.addIntOption( |
| 12592 |
'\0', "regexp-warmup-threshold", "COUNT", |
| 12593 |
"Wait for COUNT invocations before compiling regexps to native code " |
| 12594 |
"(default 10)", |
| 12595 |
-1) || |
| 12596 |
!op.addBoolOption('\0', "trace-regexp-parser", "Trace regexp parsing") || |
| 12597 |
!op.addBoolOption('\0', "trace-regexp-assembler", |
| 12598 |
"Trace regexp assembler") || |
| 12599 |
!op.addBoolOption('\0', "trace-regexp-interpreter", |
| 12600 |
"Trace regexp interpreter") || |
| 12601 |
!op.addBoolOption('\0', "trace-regexp-peephole", |
| 12602 |
"Trace regexp peephole optimization") || |
| 12603 |
!op.addBoolOption('\0', "less-debug-code", |
| 12604 |
"Emit less machine code for " |
| 12605 |
"checking assertions under DEBUG.") || |
| 12606 |
!op.addBoolOption('\0', "disable-tosource", "Disable toSource/uneval") || |
| 12607 |
!op.addBoolOption('\0', "disable-property-error-message-fix", |
| 12608 |
"Disable fix for the error message when accessing " |
| 12609 |
"property of null or undefined") || |
| 12610 |
!op.addBoolOption('\0', "enable-iterator-helpers", |
| 12611 |
"Enable iterator helpers") || |
| 12612 |
!op.addBoolOption('\0', "enable-async-iterator-helpers", |
| 12613 |
"Enable async iterator helpers") || |
| 12614 |
!op.addBoolOption('\0', "enable-json-parse-with-source", |
| 12615 |
"Enable JSON.parse with source") || |
| 12616 |
!op.addBoolOption('\0', "enable-shadow-realms", "Enable ShadowRealms") || |
| 12617 |
!op.addBoolOption('\0', "disable-array-grouping", |
| 12618 |
"Disable Object.groupBy and Map.groupBy") || |
| 12619 |
!op.addBoolOption('\0', "enable-symbols-as-weakmap-keys", |
| 12620 |
"Enable Symbols As WeakMap keys") || |
| 12621 |
!op.addBoolOption('\0', "enable-uint8array-base64", |
| 12622 |
"Enable Uint8Array base64/hex methods") || |
| 12623 |
!op.addBoolOption('\0', "enable-regexp-duplicate-named-groups", |
| 12624 |
"Enable Duplicate Named Capture Groups") || |
| 12625 |
!op.addBoolOption('\0', "enable-regexp-modifiers", |
| 12626 |
"Enable Pattern Modifiers") || |
| 12627 |
!op.addBoolOption('\0', "enable-regexp-escape", "Enable RegExp.escape") || |
| 12628 |
!op.addBoolOption('\0', "enable-top-level-await", |
| 12629 |
"Enable top-level await") || |
| 12630 |
!op.addBoolOption('\0', "enable-import-attributes", |
| 12631 |
"Enable import attributes") || |
| 12632 |
!op.addStringOption('\0', "shared-memory", "on/off", |
| 12633 |
"SharedArrayBuffer and Atomics " |
| 12634 |
#if SHARED_MEMORY_DEFAULT |
| 12635 |
"(default: on, off to disable)" |
| 12636 |
#else |
| 12637 |
"(default: off, on to enable)" |
| 12638 |
#endif |
| 12639 |
) || |
| 12640 |
!op.addStringOption('\0', "spectre-mitigations", "on/off", |
| 12641 |
"Whether Spectre mitigations are enabled (default: " |
| 12642 |
"off, on to enable)") || |
| 12643 |
!op.addStringOption('\0', "write-protect-code", "on/off", |
| 12644 |
"Whether the W^X policy is enforced to mark JIT code " |
| 12645 |
"pages as either writable or executable but never " |
| 12646 |
"both at the same time (default: on, off to " |
| 12647 |
"disable)") || |
| 12648 |
!op.addStringOption('\0', "cache-ir-stubs", "on/off/call", |
| 12649 |
"Use CacheIR stubs (default: on, off to disable, " |
| 12650 |
"call to enable work-in-progress call ICs)") || |
| 12651 |
!op.addStringOption('\0', "ion-shared-stubs", "on/off", |
| 12652 |
"Use shared stubs (default: on, off to disable)") || |
| 12653 |
!op.addStringOption('\0', "ion-scalar-replacement", "on/off", |
| 12654 |
"Scalar Replacement (default: on, off to disable)") || |
| 12655 |
!op.addStringOption('\0', "ion-gvn", "[mode]", |
| 12656 |
"Specify Ion global value numbering:\n" |
| 12657 |
" off: disable GVN\n" |
| 12658 |
" on: enable GVN (default)\n") || |
| 12659 |
!op.addStringOption( |
| 12660 |
'\0', "ion-licm", "on/off", |
| 12661 |
"Loop invariant code motion (default: on, off to disable)") || |
| 12662 |
!op.addStringOption('\0', "ion-edgecase-analysis", "on/off", |
| 12663 |
"Find edge cases where Ion can avoid bailouts " |
| 12664 |
"(default: on, off to disable)") || |
| 12665 |
!op.addStringOption('\0', "ion-pruning", "on/off", |
| 12666 |
"Branch pruning (default: on, off to disable)") || |
| 12667 |
!op.addStringOption('\0', "ion-range-analysis", "on/off", |
| 12668 |
"Range analysis (default: on, off to disable)") || |
| 12669 |
!op.addStringOption('\0', "ion-sink", "on/off", |
| 12670 |
"Sink code motion (default: off, on to enable)") || |
| 12671 |
!op.addStringOption( |
| 12672 |
'\0', "ion-instruction-reordering", "on/off", |
| 12673 |
"Instruction reordering (default: off, on to enable)") || |
| 12674 |
!op.addStringOption( |
| 12675 |
'\0', "ion-optimize-shapeguards", "on/off", |
| 12676 |
"Eliminate redundant shape guards (default: on, off to disable)") || |
| 12677 |
!op.addStringOption( |
| 12678 |
'\0', "ion-optimize-gcbarriers", "on/off", |
| 12679 |
"Eliminate redundant GC barriers (default: on, off to disable)") || |
| 12680 |
!op.addStringOption('\0', "ion-iterator-indices", "on/off", |
| 12681 |
"Optimize property access in for-in loops " |
| 12682 |
"(default: on, off to disable)") || |
| 12683 |
!op.addStringOption('\0', "ion-load-keys", "on/off", |
| 12684 |
"Atomize property loads used as keys " |
| 12685 |
"(default: on, off to disable)") || |
| 12686 |
!op.addBoolOption('\0', "ion-check-range-analysis", |
| 12687 |
"Range analysis checking") || |
| 12688 |
!op.addBoolOption('\0', "ion-extra-checks", |
| 12689 |
"Perform extra dynamic validation checks") || |
| 12690 |
!op.addStringOption( |
| 12691 |
'\0', "ion-inlining", "on/off", |
| 12692 |
"Inline methods where possible (default: on, off to disable)") || |
| 12693 |
!op.addStringOption( |
| 12694 |
'\0', "ion-osr", "on/off", |
| 12695 |
"On-Stack Replacement (default: on, off to disable)") || |
| 12696 |
!op.addBoolOption('\0', "disable-bailout-loop-check", |
| 12697 |
"Turn off bailout loop check") || |
| 12698 |
!op.addBoolOption('\0', "enable-ic-frame-pointers", |
| 12699 |
"Use frame pointers in all IC stubs") || |
| 12700 |
!op.addBoolOption('\0', "scalar-replace-arguments", |
| 12701 |
"Use scalar replacement to optimize ArgumentsObject") || |
| 12702 |
!op.addStringOption( |
| 12703 |
'\0', "ion-limit-script-size", "on/off", |
| 12704 |
"Don't compile very large scripts (default: on, off to disable)") || |
| 12705 |
!op.addIntOption('\0', "ion-warmup-threshold", "COUNT", |
| 12706 |
"Wait for COUNT calls or iterations before compiling " |
| 12707 |
"at the normal optimization level (default: 1000)", |
| 12708 |
-1) || |
| 12709 |
!op.addStringOption( |
| 12710 |
'\0', "ion-regalloc", "[mode]", |
| 12711 |
"Specify Ion register allocation:\n" |
| 12712 |
" backtracking: Priority based backtracking register allocation " |
| 12713 |
"(default)\n" |
| 12714 |
" simple: Simple register allocator optimized for compile time") || |
| 12715 |
!op.addBoolOption( |
| 12716 |
'\0', "ion-eager", |
| 12717 |
"Always ion-compile methods (implies --baseline-eager)") || |
| 12718 |
!op.addBoolOption('\0', "fast-warmup", |
| 12719 |
"Reduce warmup thresholds for each tier.") || |
| 12720 |
!op.addStringOption( |
| 12721 |
'\0', "baseline-offthread-compile", "on/off", |
| 12722 |
"Compile baseline scripts offthread (default: off)") || |
| 12723 |
!op.addStringOption( |
| 12724 |
'\0', "baseline-batching", "on/off", |
| 12725 |
"Batch baseline scripts before dispatching (default: off)") || |
| 12726 |
!op.addStringOption('\0', "ion-offthread-compile", "on/off", |
| 12727 |
"Compile Ion scripts offthread (default: on)") || |
| 12728 |
!op.addStringOption('\0', "ion-parallel-compile", "on/off", |
| 12729 |
"--ion-parallel compile is deprecated. Use " |
| 12730 |
"--ion-offthread-compile.") || |
| 12731 |
!op.addBoolOption('\0', "disable-main-thread-denormals", |
| 12732 |
"Disable Denormals on the main thread only, to " |
| 12733 |
"emulate WebAudio worklets.") || |
| 12734 |
!op.addBoolOption('\0', "baseline", |
| 12735 |
"Enable baseline compiler (default)") || |
| 12736 |
!op.addBoolOption('\0', "no-baseline", "Disable baseline compiler") || |
| 12737 |
!op.addBoolOption('\0', "baseline-eager", |
| 12738 |
"Always baseline-compile methods") || |
| 12739 |
#ifdef ENABLE_PORTABLE_BASELINE_INTERP |
| 12740 |
!op.addBoolOption('\0', "portable-baseline-eager", |
| 12741 |
"Always use the portable baseline interpreter") || |
| 12742 |
!op.addBoolOption('\0', "portable-baseline", |
| 12743 |
"Enable Portable Baseline Interpreter (default)") || |
| 12744 |
!op.addBoolOption('\0', "no-portable-baseline", |
| 12745 |
"Disable Portable Baseline Interpreter") || |
| 12746 |
#endif |
| 12747 |
#ifdef ENABLE_JS_AOT_ICS |
| 12748 |
!op.addBoolOption('\0', "aot-ics", "Enable ahead-of-time-known ICs") || |
| 12749 |
!op.addBoolOption( |
| 12750 |
'\0', "enforce-aot-ics", |
| 12751 |
"Enable enforcing only use of ahead-of-time-known ICs") || |
| 12752 |
#endif |
| 12753 |
!op.addIntOption( |
| 12754 |
'\0', "baseline-warmup-threshold", "COUNT", |
| 12755 |
"Wait for COUNT calls or iterations before baseline-compiling " |
| 12756 |
"(default: 10)", |
| 12757 |
-1) || |
| 12758 |
!op.addIntOption( |
| 12759 |
'\0', "baseline-queue-capacity", "CAPACITY", |
| 12760 |
"Wait for at most CAPACITY scripts to be added to baseline compile" |
| 12761 |
"queue before dispatching (default: 8)", |
| 12762 |
-1) || |
| 12763 |
!op.addBoolOption('\0', "blinterp", |
| 12764 |
"Enable Baseline Interpreter (default)") || |
| 12765 |
!op.addBoolOption('\0', "no-blinterp", "Disable Baseline Interpreter") || |
| 12766 |
!op.addBoolOption('\0', "disable-jithints", |
| 12767 |
"Disable caching eager baseline compilation hints.") || |
| 12768 |
!op.addBoolOption( |
| 12769 |
'\0', "emit-interpreter-entry", |
| 12770 |
"Emit Interpreter entry trampolines (default under --enable-perf)") || |
| 12771 |
!op.addBoolOption( |
| 12772 |
'\0', "no-emit-interpreter-entry", |
| 12773 |
"Do not emit Interpreter entry trampolines (default).") || |
| 12774 |
!op.addBoolOption('\0', "blinterp-eager", |
| 12775 |
"Always Baseline-interpret scripts") || |
| 12776 |
!op.addIntOption( |
| 12777 |
'\0', "blinterp-warmup-threshold", "COUNT", |
| 12778 |
"Wait for COUNT calls or iterations before Baseline-interpreting " |
| 12779 |
"(default: 10)", |
| 12780 |
-1) || |
| 12781 |
!op.addIntOption( |
| 12782 |
'\0', "trial-inlining-warmup-threshold", "COUNT", |
| 12783 |
"Wait for COUNT calls or iterations before trial-inlining " |
| 12784 |
"(default: 500)", |
| 12785 |
-1) || |
| 12786 |
!op.addStringOption( |
| 12787 |
'\0', "monomorphic-inlining", "default/always/never", |
| 12788 |
"Whether monomorphic inlining is used instead of trial inlining " |
| 12789 |
"always, never, or based on heuristics (default)") || |
| 12790 |
!op.addBoolOption( |
| 12791 |
'\0', "no-sse3", |
| 12792 |
"Pretend CPU does not support SSE3 instructions and above " |
| 12793 |
"to test JIT codegen (no-op on platforms other than x86 and x64).") || |
| 12794 |
!op.addBoolOption( |
| 12795 |
'\0', "no-ssse3", |
| 12796 |
"Pretend CPU does not support SSSE3 [sic] instructions and above " |
| 12797 |
"to test JIT codegen (no-op on platforms other than x86 and x64).") || |
| 12798 |
!op.addBoolOption( |
| 12799 |
'\0', "no-sse41", |
| 12800 |
"Pretend CPU does not support SSE4.1 instructions " |
| 12801 |
"to test JIT codegen (no-op on platforms other than x86 and x64).") || |
| 12802 |
!op.addBoolOption('\0', "no-sse4", "Alias for --no-sse41") || |
| 12803 |
!op.addBoolOption( |
| 12804 |
'\0', "no-sse42", |
| 12805 |
"Pretend CPU does not support SSE4.2 instructions " |
| 12806 |
"to test JIT codegen (no-op on platforms other than x86 and x64).") || |
| 12807 |
#ifdef ENABLE_WASM_AVX |
| 12808 |
!op.addBoolOption('\0', "enable-avx", |
| 12809 |
"No-op. AVX is enabled by default, if available.") || |
| 12810 |
!op.addBoolOption( |
| 12811 |
'\0', "no-avx", |
| 12812 |
"Pretend CPU does not support AVX or AVX2 instructions " |
| 12813 |
"to test JIT codegen (no-op on platforms other than x86 and x64).") || |
| 12814 |
#else |
| 12815 |
!op.addBoolOption('\0', "enable-avx", |
| 12816 |
"AVX is disabled by default. Enable AVX. " |
| 12817 |
"(no-op on platforms other than x86 and x64).") || |
| 12818 |
!op.addBoolOption('\0', "no-avx", |
| 12819 |
"No-op. AVX is currently disabled by default.") || |
| 12820 |
#endif |
| 12821 |
!op.addBoolOption('\0', "more-compartments", |
| 12822 |
"Make newGlobal default to creating a new " |
| 12823 |
"compartment.") || |
| 12824 |
!op.addBoolOption('\0', "fuzzing-safe", |
| 12825 |
"Don't expose functions that aren't safe for " |
| 12826 |
"fuzzers to call") || |
| 12827 |
#ifdef DEBUG |
| 12828 |
!op.addBoolOption('\0', "differential-testing", |
| 12829 |
"Avoid random/undefined behavior that disturbs " |
| 12830 |
"differential testing (correctness fuzzing)") || |
| 12831 |
#endif |
| 12832 |
!op.addBoolOption('\0', "disable-oom-functions", |
| 12833 |
"Disable functions that cause " |
| 12834 |
"artificial OOMs") || |
| 12835 |
!op.addBoolOption('\0', "no-threads", "Disable helper threads") || |
| 12836 |
!op.addBoolOption( |
| 12837 |
'\0', "no-jit-backend", |
| 12838 |
"Disable the JIT backend completely for this process") || |
| 12839 |
#ifdef DEBUG |
| 12840 |
!op.addBoolOption('\0', "dump-entrained-variables", |
| 12841 |
"Print variables which are " |
| 12842 |
"unnecessarily entrained by inner functions") || |
| 12843 |
#endif |
| 12844 |
!op.addBoolOption('\0', "no-ggc", "Disable Generational GC") || |
| 12845 |
!op.addBoolOption('\0', "no-cgc", "Disable Compacting GC") || |
| 12846 |
!op.addBoolOption('\0', "no-incremental-gc", "Disable Incremental GC") || |
| 12847 |
!op.addBoolOption('\0', "no-parallel-marking", |
| 12848 |
"Disable GC parallel marking") || |
| 12849 |
!op.addBoolOption('\0', "enable-parallel-marking", |
| 12850 |
"Enable GC parallel marking") || |
| 12851 |
!op.addStringOption('\0', "nursery-strings", "on/off", |
| 12852 |
"Allocate strings in the nursery") || |
| 12853 |
!op.addStringOption('\0', "nursery-bigints", "on/off", |
| 12854 |
"Allocate BigInts in the nursery") || |
| 12855 |
!op.addIntOption('\0', "available-memory", "SIZE", |
| 12856 |
"Select GC settings based on available memory (MB)", |
| 12857 |
0) || |
| 12858 |
!op.addBoolOption('\0', "disable-decommit", |
| 12859 |
"Disable decommitting unsued GC memory") || |
| 12860 |
!op.addStringOption('\0', "arm-hwcap", "[features]", |
| 12861 |
"Specify ARM code generation features, or 'help' to " |
| 12862 |
"list all features.") || |
| 12863 |
!op.addIntOption('\0', "arm-asm-nop-fill", "SIZE", |
| 12864 |
"Insert the given number of NOP instructions at all " |
| 12865 |
"possible pool locations.", |
| 12866 |
0) || |
| 12867 |
!op.addIntOption('\0', "asm-pool-max-offset", "OFFSET", |
| 12868 |
"The maximum pc relative OFFSET permitted in pool " |
| 12869 |
"reference instructions.", |
| 12870 |
1024) || |
| 12871 |
!op.addBoolOption('\0', "arm-sim-icache-checks", |
| 12872 |
"Enable icache flush checks in the ARM " |
| 12873 |
"simulator.") || |
| 12874 |
!op.addIntOption('\0', "arm-sim-stop-at", "NUMBER", |
| 12875 |
"Stop the ARM simulator after the given " |
| 12876 |
"NUMBER of instructions.", |
| 12877 |
-1) || |
| 12878 |
!op.addBoolOption('\0', "mips-sim-icache-checks", |
| 12879 |
"Enable icache flush checks in the MIPS " |
| 12880 |
"simulator.") || |
| 12881 |
!op.addIntOption('\0', "mips-sim-stop-at", "NUMBER", |
| 12882 |
"Stop the MIPS simulator after the given " |
| 12883 |
"NUMBER of instructions.", |
| 12884 |
-1) || |
| 12885 |
!op.addBoolOption('\0', "loong64-sim-icache-checks", |
| 12886 |
"Enable icache flush checks in the LoongArch64 " |
| 12887 |
"simulator.") || |
| 12888 |
!op.addIntOption('\0', "loong64-sim-stop-at", "NUMBER", |
| 12889 |
"Stop the LoongArch64 simulator after the given " |
| 12890 |
"NUMBER of instructions.", |
| 12891 |
-1) || |
| 12892 |
#ifdef JS_CODEGEN_RISCV64 |
| 12893 |
!op.addBoolOption('\0', "riscv-debug", "debug print riscv info.") || |
| 12894 |
#endif |
| 12895 |
#ifdef JS_SIMULATOR_RISCV64 |
| 12896 |
!op.addBoolOption('\0', "trace-sim", "print simulator info.") || |
| 12897 |
!op.addBoolOption('\0', "debug-sim", "debug simulator.") || |
| 12898 |
!op.addBoolOption('\0', "riscv-trap-to-simulator-debugger", |
| 12899 |
"trap into simulator debuggger.") || |
| 12900 |
!op.addIntOption('\0', "riscv-sim-stop-at", "NUMBER", |
| 12901 |
"Stop the riscv simulator after the given " |
| 12902 |
"NUMBER of instructions.", |
| 12903 |
-1) || |
| 12904 |
#endif |
| 12905 |
!op.addIntOption('\0', "nursery-size", "SIZE-MB", |
| 12906 |
"Set the maximum nursery size in MB", |
| 12907 |
JS::DefaultNurseryMaxBytes / 1024 / 1024) || |
| 12908 |
#ifdef JS_GC_ZEAL |
| 12909 |
!op.addStringOption('z', "gc-zeal", "LEVEL(;LEVEL)*[,N]", |
| 12910 |
gc::ZealModeHelpText) || |
| 12911 |
#else |
| 12912 |
!op.addStringOption('z', "gc-zeal", "LEVEL(;LEVEL)*[,N]", |
| 12913 |
"option ignored in non-gc-zeal builds") || |
| 12914 |
#endif |
| 12915 |
!op.addMultiStringOption('\0', "gc-param", "NAME=VALUE", |
| 12916 |
"Set a named GC parameter") || |
| 12917 |
!op.addStringOption('\0', "module-load-path", "DIR", |
| 12918 |
"Set directory to load modules from") || |
| 12919 |
!op.addBoolOption('\0', "no-source-pragmas", |
| 12920 |
"Disable source(Mapping)URL pragma parsing") || |
| 12921 |
!op.addBoolOption('\0', "no-async-stacks", "Disable async stacks") || |
| 12922 |
!op.addBoolOption('\0', "async-stacks-capture-debuggee-only", |
| 12923 |
"Limit async stack capture to only debuggees") || |
| 12924 |
!op.addMultiStringOption('\0', "dll", "LIBRARY", |
| 12925 |
"Dynamically load LIBRARY") || |
| 12926 |
!op.addBoolOption('\0', "suppress-minidump", |
| 12927 |
"Suppress crash minidumps") || |
| 12928 |
!op.addStringOption( |
| 12929 |
'\0', "delazification-mode", "[option]", |
| 12930 |
"Select one of the delazification mode for scripts given on the " |
| 12931 |
"command line, valid options are: " |
| 12932 |
"'on-demand', 'concurrent-df', 'eager', 'concurrent-df+on-demand'. " |
| 12933 |
"Choosing 'concurrent-df+on-demand' will run both concurrent-df and " |
| 12934 |
"on-demand delazification mode, and compare compilation outcome. ") || |
| 12935 |
!op.addBoolOption('\0', "wasm-compile-and-serialize", |
| 12936 |
"Compile the wasm bytecode from stdin and serialize " |
| 12937 |
"the results to stdout") || |
| 12938 |
#ifdef FUZZING_JS_FUZZILLI |
| 12939 |
!op.addBoolOption('\0', "reprl", "Enable REPRL mode for fuzzing") || |
| 12940 |
#endif |
| 12941 |
!op.addMultiStringOption('P', "setpref", "name[=val]", |
| 12942 |
"Set the value of a JS pref. The value may " |
| 12943 |
"be omitted for boolean prefs, in which case " |
| 12944 |
"they default to true. Use --list-prefs " |
| 12945 |
"to print all pref names.") || |
| 12946 |
!op.addBoolOption( |
| 12947 |
'\0', "list-prefs", |
| 12948 |
"Print list of prefs that can be set with --setpref.") || |
| 12949 |
!op.addBoolOption('\0', "use-fdlibm-for-sin-cos-tan", |
| 12950 |
"Use fdlibm for Math.sin, Math.cos, and Math.tan") || |
| 12951 |
!op.addBoolOption('\0', "wasm-gc", "Enable WebAssembly gc proposal.") || |
| 12952 |
!op.addBoolOption('\0', "wasm-relaxed-simd", |
| 12953 |
"Enable WebAssembly relaxed-simd proposal.") || |
| 12954 |
!op.addBoolOption('\0', "wasm-multi-memory", |
| 12955 |
"Enable WebAssembly multi-memory proposal.") || |
| 12956 |
!op.addBoolOption('\0', "wasm-memory-control", |
| 12957 |
"Enable WebAssembly memory-control proposal.") || |
| 12958 |
!op.addBoolOption('\0', "wasm-memory64", |
| 12959 |
"Enable WebAssembly memory64 proposal.") || |
| 12960 |
!op.addBoolOption('\0', "wasm-tail-calls", |
| 12961 |
"Enable WebAssembly tail-calls proposal.") || |
| 12962 |
!op.addBoolOption('\0', "wasm-js-string-builtins", |
| 12963 |
"Enable WebAssembly js-string-builtins proposal.") || |
| 12964 |
!op.addBoolOption('\0', "enable-promise-try", "Enable Promise.try") || |
| 12965 |
!op.addBoolOption('\0', "enable-iterator-sequencing", |
| 12966 |
"Enable Iterator Sequencing") || |
| 12967 |
!op.addBoolOption('\0', "enable-math-sumprecise", |
| 12968 |
"Enable Math.sumPrecise") || |
| 12969 |
!op.addBoolOption('\0', "enable-error-iserror", "Enable Error.isError") || |
| 12970 |
!op.addBoolOption('\0', "enable-iterator-range", |
| 12971 |
"Enable Iterator.range") || |
| 12972 |
!op.addBoolOption('\0', "enable-joint-iteration", |
| 12973 |
"Enable Joint Iteration") || |
| 12974 |
!op.addBoolOption('\0', "enable-atomics-pause", "Enable Atomics pause") || |
| 12975 |
!op.addBoolOption('\0', "enable-explicit-resource-management", |
| 12976 |
"Enable Explicit Resource Management") || |
| 12977 |
!op.addBoolOption('\0', "disable-explicit-resource-management", |
| 12978 |
"Disable Explicit Resource Management") || |
| 12979 |
!op.addBoolOption('\0', "enable-temporal", "Enable Temporal") || |
| 12980 |
!op.addBoolOption('\0', "enable-upsert", "Enable Upsert proposal")) { |
| 12981 |
return false; |
| 12982 |
} |
| 12983 |
|
| 12984 |
op.setArgTerminatesOptions("script", true); |
| 12985 |
op.setArgCapturesRest("scriptArgs"); |
| 12986 |
|
| 12987 |
// If --fuzzing-safe is used, print a warning for unknown shell flags instead |
| 12988 |
// of aborting execution. |
| 12989 |
op.setIgnoresUnknownOptions("fuzzing-safe", true); |
| 12990 |
|
| 12991 |
return true; |
| 12992 |
} |
| 12993 |
|
| 12994 |
bool SetGlobalOptionsPreJSInit(const OptionParser& op) { |
| 12995 |
if (op.getBoolOption("fuzzing-safe")) { |
| 12996 |
fuzzingSafe = true; |
| 12997 |
} else { |
| 12998 |
fuzzingSafe = |
| 12999 |
(getenv("MOZ_FUZZING_SAFE") && getenv("MOZ_FUZZING_SAFE")[0] != '0'); |
| 13000 |
} |
| 13001 |
|
| 13002 |
for (MultiStringRange args = op.getMultiStringOption("setpref"); |
| 13003 |
!args.empty(); args.popFront()) { |
| 13004 |
if (!SetPref(args.front())) { |
| 13005 |
return false; |
| 13006 |
} |
| 13007 |
} |
| 13008 |
|
| 13009 |
// Override pref values for prefs that have a custom shell flag. |
| 13010 |
// If you're adding a new feature, consider using --setpref instead. |
| 13011 |
if (op.getBoolOption("enable-shadow-realms")) { |
| 13012 |
JS::Prefs::set_experimental_shadow_realms(true); |
| 13013 |
} |
| 13014 |
if (op.getBoolOption("enable-regexp-duplicate-named-groups")) { |
| 13015 |
JS::Prefs::setAtStartup_experimental_regexp_duplicate_named_groups(true); |
| 13016 |
} |
| 13017 |
if (op.getBoolOption("enable-regexp-modifiers")) { |
| 13018 |
JS::Prefs::setAtStartup_experimental_regexp_modifiers(true); |
| 13019 |
} |
| 13020 |
if (op.getBoolOption("enable-uint8array-base64")) { |
| 13021 |
JS::Prefs::setAtStartup_experimental_uint8array_base64(true); |
| 13022 |
} |
| 13023 |
if (op.getBoolOption("enable-promise-try")) { |
| 13024 |
JS::Prefs::setAtStartup_experimental_promise_try(true); |
| 13025 |
} |
| 13026 |
if (op.getBoolOption("enable-math-sumprecise")) { |
| 13027 |
JS::Prefs::setAtStartup_experimental_math_sumprecise(true); |
| 13028 |
} |
| 13029 |
if (op.getBoolOption("enable-atomics-pause")) { |
| 13030 |
JS::Prefs::setAtStartup_experimental_atomics_pause(true); |
| 13031 |
} |
| 13032 |
if (op.getBoolOption("enable-error-iserror")) { |
| 13033 |
JS::Prefs::set_experimental_error_iserror(true); |
| 13034 |
} |
| 13035 |
#ifdef NIGHTLY_BUILD |
| 13036 |
if (op.getBoolOption("enable-async-iterator-helpers")) { |
| 13037 |
JS::Prefs::setAtStartup_experimental_async_iterator_helpers(true); |
| 13038 |
} |
| 13039 |
if (op.getBoolOption("enable-symbols-as-weakmap-keys")) { |
| 13040 |
JS::Prefs::setAtStartup_experimental_symbols_as_weakmap_keys(true); |
| 13041 |
} |
| 13042 |
if (op.getBoolOption("enable-iterator-sequencing")) { |
| 13043 |
JS::Prefs::setAtStartup_experimental_iterator_sequencing(true); |
| 13044 |
} |
| 13045 |
if (op.getBoolOption("enable-iterator-range")) { |
| 13046 |
JS::Prefs::setAtStartup_experimental_iterator_range(true); |
| 13047 |
} |
| 13048 |
if (op.getBoolOption("enable-joint-iteration")) { |
| 13049 |
JS::Prefs::setAtStartup_experimental_joint_iteration(true); |
| 13050 |
} |
| 13051 |
if (op.getBoolOption("enable-upsert")) { |
| 13052 |
JS::Prefs::setAtStartup_experimental_upsert(true); |
| 13053 |
} |
| 13054 |
#endif |
| 13055 |
#ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT |
| 13056 |
if (op.getBoolOption("enable-explicit-resource-management")) { |
| 13057 |
JS::Prefs::set_experimental_explicit_resource_management(true); |
| 13058 |
} |
| 13059 |
if (op.getBoolOption("disable-explicit-resource-management")) { |
| 13060 |
JS::Prefs::set_experimental_explicit_resource_management(false); |
| 13061 |
} |
| 13062 |
#endif |
| 13063 |
#ifdef JS_HAS_INTL_API |
| 13064 |
if (op.getBoolOption("enable-temporal")) { |
| 13065 |
JS::Prefs::setAtStartup_experimental_temporal(true); |
| 13066 |
} |
| 13067 |
#endif |
| 13068 |
if (op.getBoolOption("enable-json-parse-with-source")) { |
| 13069 |
JS::Prefs::set_experimental_json_parse_with_source(true); |
| 13070 |
} |
| 13071 |
|
| 13072 |
JS::Prefs::setAtStartup_experimental_weakrefs_expose_cleanupSome(true); |
| 13073 |
|
| 13074 |
if (op.getBoolOption("disable-property-error-message-fix")) { |
| 13075 |
JS::Prefs::setAtStartup_property_error_message_fix(false); |
| 13076 |
} |
| 13077 |
|
| 13078 |
JS::Prefs::set_use_fdlibm_for_sin_cos_tan( |
| 13079 |
op.getBoolOption("use-fdlibm-for-sin-cos-tan")); |
| 13080 |
|
| 13081 |
if (const char* str = op.getStringOption("ion-regalloc")) { |
| 13082 |
auto allocator = jit::LookupRegisterAllocator(str); |
| 13083 |
if (allocator.isNothing()) { |
| 13084 |
return OptionFailure("ion-regalloc", str); |
| 13085 |
} |
| 13086 |
switch (*allocator) { |
| 13087 |
case jit::RegisterAllocator_Backtracking: |
| 13088 |
JS::Prefs::setAtStartup_ion_regalloc(1); |
| 13089 |
break; |
| 13090 |
case jit::RegisterAllocator_Simple: |
| 13091 |
JS::Prefs::setAtStartup_ion_regalloc(2); |
| 13092 |
break; |
| 13093 |
} |
| 13094 |
} |
| 13095 |
|
| 13096 |
if (op.getBoolOption("wasm-gc") || op.getBoolOption("wasm-relaxed-simd") || |
| 13097 |
op.getBoolOption("wasm-multi-memory") || |
| 13098 |
op.getBoolOption("wasm-memory-control") || |
| 13099 |
op.getBoolOption("wasm-memory64") || |
| 13100 |
op.getBoolOption("wasm-tail-calls") || |
| 13101 |
op.getBoolOption("wasm-js-string-builtins")) { |
| 13102 |
fprintf( |
| 13103 |
stderr, |
| 13104 |
"Wasm shell flags are now using prefs, use -P wasm_feature instead.\n"); |
| 13105 |
return false; |
| 13106 |
} |
| 13107 |
|
| 13108 |
if (op.getBoolOption("list-prefs")) { |
| 13109 |
ListPrefs(); |
| 13110 |
return false; |
| 13111 |
} |
| 13112 |
|
| 13113 |
// Note: DisableJitBackend must be called before JS_InitWithFailureDiagnostic. |
| 13114 |
if (op.getBoolOption("no-jit-backend")) { |
| 13115 |
JS::DisableJitBackend(); |
| 13116 |
} |
| 13117 |
|
| 13118 |
#if defined(JS_CODEGEN_ARM) |
| 13119 |
if (const char* str = op.getStringOption("arm-hwcap")) { |
| 13120 |
jit::SetARMHwCapFlagsString(str); |
| 13121 |
} |
| 13122 |
|
| 13123 |
int32_t fill = op.getIntOption("arm-asm-nop-fill"); |
| 13124 |
if (fill >= 0) { |
| 13125 |
jit::Assembler::NopFill = fill; |
| 13126 |
} |
| 13127 |
|
| 13128 |
int32_t poolMaxOffset = op.getIntOption("asm-pool-max-offset"); |
| 13129 |
if (poolMaxOffset >= 5 && poolMaxOffset <= 1024) { |
| 13130 |
jit::Assembler::AsmPoolMaxOffset = poolMaxOffset; |
| 13131 |
} |
| 13132 |
#endif |
| 13133 |
|
| 13134 |
// Fish around in `op` for various important compiler-configuration flags |
| 13135 |
// and make sure they get handed on to any child processes we might create. |
| 13136 |
// See bug 1700900. Semantically speaking, this is all rather dubious: |
| 13137 |
// |
| 13138 |
// * What set of flags need to be propagated in order to guarantee that the |
| 13139 |
// child produces code that is "compatible" (in whatever sense) with that |
| 13140 |
// produced by the parent? This isn't always easy to determine. |
| 13141 |
// |
| 13142 |
// * There's nothing that ensures that flags given to the child are |
| 13143 |
// presented in the same order that they exist in the parent's `argv[]`. |
| 13144 |
// That could be a problem in the case where two flags with contradictory |
| 13145 |
// meanings are given, and they are presented to the child in the opposite |
| 13146 |
// order. For example: --wasm-compiler=optimizing --wasm-compiler=baseline. |
| 13147 |
|
| 13148 |
#if defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64) |
| 13149 |
MOZ_ASSERT(!js::jit::CPUFlagsHaveBeenComputed()); |
| 13150 |
|
| 13151 |
if (op.getBoolOption("no-avx")) { |
| 13152 |
js::jit::CPUInfo::SetAVXDisabled(); |
| 13153 |
if (!sCompilerProcessFlags.append("--no-avx")) { |
| 13154 |
return false; |
| 13155 |
} |
| 13156 |
} |
| 13157 |
if (op.getBoolOption("enable-avx")) { |
| 13158 |
js::jit::CPUInfo::SetAVXEnabled(); |
| 13159 |
if (!sCompilerProcessFlags.append("--enable-avx")) { |
| 13160 |
return false; |
| 13161 |
} |
| 13162 |
} |
| 13163 |
if (op.getBoolOption("no-sse3")) { |
| 13164 |
js::jit::CPUInfo::SetSSE3Disabled(); |
| 13165 |
if (!sCompilerProcessFlags.append("--no-sse3")) { |
| 13166 |
return false; |
| 13167 |
} |
| 13168 |
} |
| 13169 |
if (op.getBoolOption("no-ssse3")) { |
| 13170 |
js::jit::CPUInfo::SetSSSE3Disabled(); |
| 13171 |
if (!sCompilerProcessFlags.append("--no-ssse3")) { |
| 13172 |
return false; |
| 13173 |
} |
| 13174 |
} |
| 13175 |
if (op.getBoolOption("no-sse4") || op.getBoolOption("no-sse41")) { |
| 13176 |
js::jit::CPUInfo::SetSSE41Disabled(); |
| 13177 |
if (!sCompilerProcessFlags.append("--no-sse41")) { |
| 13178 |
return false; |
| 13179 |
} |
| 13180 |
} |
| 13181 |
if (op.getBoolOption("no-sse42")) { |
| 13182 |
js::jit::CPUInfo::SetSSE42Disabled(); |
| 13183 |
if (!sCompilerProcessFlags.append("--no-sse42")) { |
| 13184 |
return false; |
| 13185 |
} |
| 13186 |
} |
| 13187 |
#endif |
| 13188 |
#ifndef __wasi__ |
| 13189 |
if (op.getBoolOption("disable-wasm-huge-memory")) { |
| 13190 |
JS::Prefs::setAtStartup_wasm_disable_huge_memory(true); |
| 13191 |
if (!sCompilerProcessFlags.append("--disable-wasm-huge-memory")) { |
| 13192 |
return false; |
| 13193 |
} |
| 13194 |
} |
| 13195 |
#endif |
| 13196 |
|
| 13197 |
if (op.getBoolOption("disable-decommit")) { |
| 13198 |
gc::DisableDecommit(); |
| 13199 |
} |
| 13200 |
|
| 13201 |
return true; |
| 13202 |
} |
| 13203 |
|
| 13204 |
bool SetGlobalOptionsPostJSInit(const OptionParser& op) { |
| 13205 |
// Allow dumping on Linux with the fuzzing flag set, even when running with |
| 13206 |
// the suid/sgid flag set on the shell. |
| 13207 |
#ifdef XP_LINUX |
| 13208 |
if (op.getBoolOption("fuzzing-safe")) { |
| 13209 |
prctl(PR_SET_DUMPABLE, 1); |
| 13210 |
} |
| 13211 |
#endif |
| 13212 |
|
| 13213 |
#ifdef DEBUG |
| 13214 |
/* |
| 13215 |
* Process OOM options as early as possible so that we can observe as many |
| 13216 |
* allocations as possible. |
| 13217 |
*/ |
| 13218 |
OOM_printAllocationCount = op.getBoolOption('O'); |
| 13219 |
#endif |
| 13220 |
|
| 13221 |
if (op.getBoolOption("no-threads")) { |
| 13222 |
js::DisableExtraThreads(); |
| 13223 |
} |
| 13224 |
|
| 13225 |
enableCodeCoverage = op.getBoolOption("code-coverage"); |
| 13226 |
if (enableCodeCoverage) { |
| 13227 |
js::EnableCodeCoverage(); |
| 13228 |
} |
| 13229 |
|
| 13230 |
// If LCov is enabled, then the default delazification mode should be changed |
| 13231 |
// to parse everything eagerly, such that we know the location of every |
| 13232 |
// instruction, to report them in the LCov summary, even if there is no uses |
| 13233 |
// of these instructions. |
| 13234 |
// |
| 13235 |
// Note: code coverage can be enabled either using the --code-coverage command |
| 13236 |
// line, or the JS_CODE_COVERAGE_OUTPUT_DIR environment variable, which is |
| 13237 |
// processed by JS_InitWithFailureDiagnostic. |
| 13238 |
if (coverage::IsLCovEnabled()) { |
| 13239 |
defaultDelazificationMode = |
| 13240 |
JS::DelazificationOption::ParseEverythingEagerly; |
| 13241 |
} |
| 13242 |
|
| 13243 |
if (const char* xdr = op.getStringOption("selfhosted-xdr-path")) { |
| 13244 |
shell::selfHostedXDRPath = xdr; |
| 13245 |
} |
| 13246 |
if (const char* opt = op.getStringOption("selfhosted-xdr-mode")) { |
| 13247 |
if (strcmp(opt, "encode") == 0) { |
| 13248 |
shell::encodeSelfHostedCode = true; |
| 13249 |
} else if (strcmp(opt, "decode") == 0) { |
| 13250 |
shell::encodeSelfHostedCode = false; |
| 13251 |
} else if (strcmp(opt, "off") == 0) { |
| 13252 |
shell::selfHostedXDRPath = nullptr; |
| 13253 |
} else { |
| 13254 |
MOZ_CRASH( |
| 13255 |
"invalid option value for --selfhosted-xdr-mode, must be " |
| 13256 |
"encode/decode"); |
| 13257 |
} |
| 13258 |
} |
| 13259 |
|
| 13260 |
#ifdef JS_WITHOUT_NSPR |
| 13261 |
if (!op.getMultiStringOption("dll").empty()) { |
| 13262 |
fprintf(stderr, "Error: --dll requires NSPR support!\n"); |
| 13263 |
return false; |
| 13264 |
} |
| 13265 |
#else |
| 13266 |
AutoLibraryLoader loader; |
| 13267 |
MultiStringRange dllPaths = op.getMultiStringOption("dll"); |
| 13268 |
while (!dllPaths.empty()) { |
| 13269 |
char* path = dllPaths.front(); |
| 13270 |
loader.load(path); |
| 13271 |
dllPaths.popFront(); |
| 13272 |
} |
| 13273 |
#endif |
| 13274 |
|
| 13275 |
if (op.getBoolOption("suppress-minidump")) { |
| 13276 |
js::NoteIntentionalCrash(); |
| 13277 |
} |
| 13278 |
|
| 13279 |
// The fake CPU count must be set before initializing the Runtime, |
| 13280 |
// which spins up the thread pool. |
| 13281 |
int32_t cpuCount = op.getIntOption("cpu-count"); // What we're really setting |
| 13282 |
if (cpuCount < 0) { |
| 13283 |
cpuCount = op.getIntOption("thread-count"); // Legacy name |
| 13284 |
} |
| 13285 |
if (cpuCount >= 0 && !SetFakeCPUCount(cpuCount)) { |
| 13286 |
return false; |
| 13287 |
} |
| 13288 |
|
| 13289 |
return true; |
| 13290 |
} |
| 13291 |
|
| 13292 |
bool SetContextOptions(JSContext* cx, const OptionParser& op) { |
| 13293 |
if (!SetContextWasmOptions(cx, op) || !SetContextJITOptions(cx, op) || |
| 13294 |
!SetContextGCOptions(cx, op)) { |
| 13295 |
return false; |
| 13296 |
} |
| 13297 |
|
| 13298 |
enableSourcePragmas = !op.getBoolOption("no-source-pragmas"); |
| 13299 |
enableAsyncStacks = !op.getBoolOption("no-async-stacks"); |
| 13300 |
enableAsyncStackCaptureDebuggeeOnly = |
| 13301 |
op.getBoolOption("async-stacks-capture-debuggee-only"); |
| 13302 |
enableToSource = !op.getBoolOption("disable-tosource"); |
| 13303 |
enableImportAttributes = op.getBoolOption("enable-import-attributes"); |
| 13304 |
JS::ContextOptionsRef(cx) |
| 13305 |
.setSourcePragmas(enableSourcePragmas) |
| 13306 |
.setAsyncStack(enableAsyncStacks) |
| 13307 |
.setAsyncStackCaptureDebuggeeOnly(enableAsyncStackCaptureDebuggeeOnly) |
| 13308 |
.setImportAttributes(enableImportAttributes); |
| 13309 |
|
| 13310 |
if (const char* str = op.getStringOption("shared-memory")) { |
| 13311 |
if (strcmp(str, "off") == 0) { |
| 13312 |
enableSharedMemory = false; |
| 13313 |
} else if (strcmp(str, "on") == 0) { |
| 13314 |
enableSharedMemory = true; |
| 13315 |
} else { |
| 13316 |
return OptionFailure("shared-memory", str); |
| 13317 |
} |
| 13318 |
} |
| 13319 |
|
| 13320 |
reportWarnings = op.getBoolOption('w'); |
| 13321 |
compileOnly = op.getBoolOption('c'); |
| 13322 |
printTiming = op.getBoolOption('b'); |
| 13323 |
enableDisassemblyDumps = op.getBoolOption('D'); |
| 13324 |
cx->runtime()->profilingScripts = |
| 13325 |
enableCodeCoverage || enableDisassemblyDumps; |
| 13326 |
|
| 13327 |
if (const char* mode = op.getStringOption("delazification-mode")) { |
| 13328 |
if (strcmp(mode, "on-demand") == 0) { |
| 13329 |
defaultDelazificationMode = JS::DelazificationOption::OnDemandOnly; |
| 13330 |
} else if (strcmp(mode, "concurrent-df") == 0) { |
| 13331 |
defaultDelazificationMode = |
| 13332 |
JS::DelazificationOption::ConcurrentDepthFirst; |
| 13333 |
} else if (strcmp(mode, "eager") == 0) { |
| 13334 |
defaultDelazificationMode = |
| 13335 |
JS::DelazificationOption::ParseEverythingEagerly; |
| 13336 |
} else if (strcmp(mode, "concurrent-df+on-demand") == 0 || |
| 13337 |
strcmp(mode, "on-demand+concurrent-df") == 0) { |
| 13338 |
defaultDelazificationMode = |
| 13339 |
JS::DelazificationOption::CheckConcurrentWithOnDemand; |
| 13340 |
} else { |
| 13341 |
return OptionFailure("delazification-mode", mode); |
| 13342 |
} |
| 13343 |
} |
| 13344 |
|
| 13345 |
return true; |
| 13346 |
} |
| 13347 |
|
| 13348 |
bool SetContextWasmOptions(JSContext* cx, const OptionParser& op) { |
| 13349 |
enableAsmJS = !op.getBoolOption("no-asmjs"); |
| 13350 |
|
| 13351 |
enableWasm = true; |
| 13352 |
enableWasmBaseline = true; |
| 13353 |
enableWasmOptimizing = true; |
| 13354 |
|
| 13355 |
if (const char* str = op.getStringOption("wasm-compiler")) { |
| 13356 |
if (strcmp(str, "none") == 0) { |
| 13357 |
enableWasm = false; |
| 13358 |
} else if (strcmp(str, "baseline") == 0) { |
| 13359 |
MOZ_ASSERT(enableWasmBaseline); |
| 13360 |
enableWasmOptimizing = false; |
| 13361 |
} else if (strcmp(str, "optimizing") == 0 || |
| 13362 |
strcmp(str, "optimized") == 0) { |
| 13363 |
enableWasmBaseline = false; |
| 13364 |
MOZ_ASSERT(enableWasmOptimizing); |
| 13365 |
} else if (strcmp(str, "baseline+optimizing") == 0 || |
| 13366 |
strcmp(str, "baseline+optimized") == 0) { |
| 13367 |
MOZ_ASSERT(enableWasmBaseline); |
| 13368 |
MOZ_ASSERT(enableWasmOptimizing); |
| 13369 |
} else if (strcmp(str, "ion") == 0) { |
| 13370 |
enableWasmBaseline = false; |
| 13371 |
enableWasmOptimizing = true; |
| 13372 |
} else if (strcmp(str, "baseline+ion") == 0) { |
| 13373 |
MOZ_ASSERT(enableWasmBaseline); |
| 13374 |
enableWasmOptimizing = true; |
| 13375 |
} else { |
| 13376 |
return OptionFailure("wasm-compiler", str); |
| 13377 |
} |
| 13378 |
} |
| 13379 |
|
| 13380 |
enableTestWasmAwaitTier2 = op.getBoolOption("test-wasm-await-tier2"); |
| 13381 |
|
| 13382 |
JS::ContextOptionsRef(cx) |
| 13383 |
.setAsmJS(enableAsmJS) |
| 13384 |
.setWasm(enableWasm) |
| 13385 |
.setWasmForTrustedPrinciples(enableWasm) |
| 13386 |
.setWasmBaseline(enableWasmBaseline) |
| 13387 |
.setWasmIon(enableWasmOptimizing) |
| 13388 |
.setTestWasmAwaitTier2(enableTestWasmAwaitTier2); |
| 13389 |
|
| 13390 |
#ifndef __wasi__ |
| 13391 |
// Also the following are to be propagated. |
| 13392 |
const char* to_propagate[] = { |
| 13393 |
// Compiler selection options |
| 13394 |
"--test-wasm-await-tier2", |
| 13395 |
}; |
| 13396 |
for (const char* p : to_propagate) { |
| 13397 |
if (op.getBoolOption(p + 2 /* 2 => skip the leading '--' */)) { |
| 13398 |
if (!sCompilerProcessFlags.append(p)) { |
| 13399 |
return false; |
| 13400 |
} |
| 13401 |
} |
| 13402 |
} |
| 13403 |
|
| 13404 |
// Also --wasm-compiler= is to be propagated. This is tricky because it is |
| 13405 |
// necessary to reconstitute the --wasm-compiler=<whatever> string from its |
| 13406 |
// pieces, without causing a leak. Hence it is copied into a static buffer. |
| 13407 |
// This is thread-unsafe, but we're in `main()` and on the process' root |
| 13408 |
// thread. Also, we do this only once -- it wouldn't work properly if we |
| 13409 |
// handled multiple --wasm-compiler= flags in a loop. |
| 13410 |
const char* wasm_compiler = op.getStringOption("wasm-compiler"); |
| 13411 |
if (wasm_compiler) { |
| 13412 |
size_t n_needed = |
| 13413 |
2 + strlen("wasm-compiler") + 1 + strlen(wasm_compiler) + 1; |
| 13414 |
const size_t n_avail = 128; |
| 13415 |
static char buf[n_avail]; |
| 13416 |
// `n_needed` depends on the compiler name specified. However, it can't |
| 13417 |
// be arbitrarily long, since previous flag-checking should have limited |
| 13418 |
// it to a set of known possibilities: "baseline", "ion", |
| 13419 |
// "baseline+ion", Still, assert this for safety. |
| 13420 |
MOZ_RELEASE_ASSERT(n_needed < n_avail); |
| 13421 |
memset(buf, 0, sizeof(buf)); |
| 13422 |
SprintfBuf(buf, n_avail, "--%s=%s", "wasm-compiler", wasm_compiler); |
| 13423 |
if (!sCompilerProcessFlags.append(buf)) { |
| 13424 |
return false; |
| 13425 |
} |
| 13426 |
} |
| 13427 |
#endif // __wasi__ |
| 13428 |
|
| 13429 |
return true; |
| 13430 |
} |
| 13431 |
|
| 13432 |
bool SetContextJITOptions(JSContext* cx, const OptionParser& op) { |
| 13433 |
// Check --fast-warmup first because it sets default warm-up thresholds. These |
| 13434 |
// thresholds can then be overridden below by --ion-eager and other flags. |
| 13435 |
if (op.getBoolOption("fast-warmup")) { |
| 13436 |
jit::JitOptions.setFastWarmUp(); |
| 13437 |
} |
| 13438 |
|
| 13439 |
if (op.getBoolOption("no-ion-for-main-context")) { |
| 13440 |
JS::ContextOptionsRef(cx).setDisableIon(); |
| 13441 |
} |
| 13442 |
|
| 13443 |
if (const char* str = op.getStringOption("cache-ir-stubs")) { |
| 13444 |
if (strcmp(str, "on") == 0) { |
| 13445 |
jit::JitOptions.disableCacheIR = false; |
| 13446 |
} else if (strcmp(str, "off") == 0) { |
| 13447 |
jit::JitOptions.disableCacheIR = true; |
| 13448 |
} else { |
| 13449 |
return OptionFailure("cache-ir-stubs", str); |
| 13450 |
} |
| 13451 |
} |
| 13452 |
|
| 13453 |
if (const char* str = op.getStringOption("spectre-mitigations")) { |
| 13454 |
if (strcmp(str, "on") == 0) { |
| 13455 |
jit::JitOptions.spectreIndexMasking = true; |
| 13456 |
jit::JitOptions.spectreObjectMitigations = true; |
| 13457 |
jit::JitOptions.spectreStringMitigations = true; |
| 13458 |
jit::JitOptions.spectreValueMasking = true; |
| 13459 |
jit::JitOptions.spectreJitToCxxCalls = true; |
| 13460 |
} else if (strcmp(str, "off") == 0) { |
| 13461 |
jit::JitOptions.spectreIndexMasking = false; |
| 13462 |
jit::JitOptions.spectreObjectMitigations = false; |
| 13463 |
jit::JitOptions.spectreStringMitigations = false; |
| 13464 |
jit::JitOptions.spectreValueMasking = false; |
| 13465 |
jit::JitOptions.spectreJitToCxxCalls = false; |
| 13466 |
} else { |
| 13467 |
return OptionFailure("spectre-mitigations", str); |
| 13468 |
} |
| 13469 |
} |
| 13470 |
|
| 13471 |
if (const char* str = op.getStringOption("write-protect-code")) { |
| 13472 |
if (strcmp(str, "on") == 0) { |
| 13473 |
jit::JitOptions.maybeSetWriteProtectCode(true); |
| 13474 |
} else if (strcmp(str, "off") == 0) { |
| 13475 |
jit::JitOptions.maybeSetWriteProtectCode(false); |
| 13476 |
} else { |
| 13477 |
return OptionFailure("write-protect-code", str); |
| 13478 |
} |
| 13479 |
} |
| 13480 |
|
| 13481 |
if (const char* str = op.getStringOption("monomorphic-inlining")) { |
| 13482 |
if (strcmp(str, "default") == 0) { |
| 13483 |
jit::JitOptions.monomorphicInlining = |
| 13484 |
jit::UseMonomorphicInlining::Default; |
| 13485 |
} else if (strcmp(str, "always") == 0) { |
| 13486 |
jit::JitOptions.monomorphicInlining = jit::UseMonomorphicInlining::Always; |
| 13487 |
} else if (strcmp(str, "never") == 0) { |
| 13488 |
jit::JitOptions.monomorphicInlining = jit::UseMonomorphicInlining::Never; |
| 13489 |
} else { |
| 13490 |
return OptionFailure("monomorphic-inlining", str); |
| 13491 |
} |
| 13492 |
} |
| 13493 |
|
| 13494 |
if (const char* str = op.getStringOption("ion-scalar-replacement")) { |
| 13495 |
if (strcmp(str, "on") == 0) { |
| 13496 |
jit::JitOptions.disableScalarReplacement = false; |
| 13497 |
} else if (strcmp(str, "off") == 0) { |
| 13498 |
jit::JitOptions.disableScalarReplacement = true; |
| 13499 |
} else { |
| 13500 |
return OptionFailure("ion-scalar-replacement", str); |
| 13501 |
} |
| 13502 |
} |
| 13503 |
|
| 13504 |
if (op.getStringOption("ion-shared-stubs")) { |
| 13505 |
// Dead option, preserved for now for potential fuzzer interaction. |
| 13506 |
} |
| 13507 |
|
| 13508 |
if (const char* str = op.getStringOption("ion-gvn")) { |
| 13509 |
if (strcmp(str, "off") == 0) { |
| 13510 |
jit::JitOptions.disableGvn = true; |
| 13511 |
} else if (strcmp(str, "on") != 0 && strcmp(str, "optimistic") != 0 && |
| 13512 |
strcmp(str, "pessimistic") != 0) { |
| 13513 |
// We accept "pessimistic" and "optimistic" as synonyms for "on" |
| 13514 |
// for backwards compatibility. |
| 13515 |
return OptionFailure("ion-gvn", str); |
| 13516 |
} |
| 13517 |
} |
| 13518 |
|
| 13519 |
if (const char* str = op.getStringOption("ion-licm")) { |
| 13520 |
if (strcmp(str, "on") == 0) { |
| 13521 |
jit::JitOptions.disableLicm = false; |
| 13522 |
} else if (strcmp(str, "off") == 0) { |
| 13523 |
jit::JitOptions.disableLicm = true; |
| 13524 |
} else { |
| 13525 |
return OptionFailure("ion-licm", str); |
| 13526 |
} |
| 13527 |
} |
| 13528 |
|
| 13529 |
if (const char* str = op.getStringOption("ion-edgecase-analysis")) { |
| 13530 |
if (strcmp(str, "on") == 0) { |
| 13531 |
jit::JitOptions.disableEdgeCaseAnalysis = false; |
| 13532 |
} else if (strcmp(str, "off") == 0) { |
| 13533 |
jit::JitOptions.disableEdgeCaseAnalysis = true; |
| 13534 |
} else { |
| 13535 |
return OptionFailure("ion-edgecase-analysis", str); |
| 13536 |
} |
| 13537 |
} |
| 13538 |
|
| 13539 |
if (const char* str = op.getStringOption("ion-pruning")) { |
| 13540 |
if (strcmp(str, "on") == 0) { |
| 13541 |
jit::JitOptions.disablePruning = false; |
| 13542 |
} else if (strcmp(str, "off") == 0) { |
| 13543 |
jit::JitOptions.disablePruning = true; |
| 13544 |
} else { |
| 13545 |
return OptionFailure("ion-pruning", str); |
| 13546 |
} |
| 13547 |
} |
| 13548 |
|
| 13549 |
if (const char* str = op.getStringOption("ion-range-analysis")) { |
| 13550 |
if (strcmp(str, "on") == 0) { |
| 13551 |
jit::JitOptions.disableRangeAnalysis = false; |
| 13552 |
} else if (strcmp(str, "off") == 0) { |
| 13553 |
jit::JitOptions.disableRangeAnalysis = true; |
| 13554 |
} else { |
| 13555 |
return OptionFailure("ion-range-analysis", str); |
| 13556 |
} |
| 13557 |
} |
| 13558 |
|
| 13559 |
if (const char* str = op.getStringOption("ion-sink")) { |
| 13560 |
if (strcmp(str, "on") == 0) { |
| 13561 |
jit::JitOptions.disableSink = false; |
| 13562 |
} else if (strcmp(str, "off") == 0) { |
| 13563 |
jit::JitOptions.disableSink = true; |
| 13564 |
} else { |
| 13565 |
return OptionFailure("ion-sink", str); |
| 13566 |
} |
| 13567 |
} |
| 13568 |
|
| 13569 |
if (const char* str = op.getStringOption("ion-optimize-shapeguards")) { |
| 13570 |
if (strcmp(str, "on") == 0) { |
| 13571 |
jit::JitOptions.disableRedundantShapeGuards = false; |
| 13572 |
} else if (strcmp(str, "off") == 0) { |
| 13573 |
jit::JitOptions.disableRedundantShapeGuards = true; |
| 13574 |
} else { |
| 13575 |
return OptionFailure("ion-optimize-shapeguards", str); |
| 13576 |
} |
| 13577 |
} |
| 13578 |
|
| 13579 |
if (const char* str = op.getStringOption("ion-optimize-gcbarriers")) { |
| 13580 |
if (strcmp(str, "on") == 0) { |
| 13581 |
jit::JitOptions.disableRedundantGCBarriers = false; |
| 13582 |
} else if (strcmp(str, "off") == 0) { |
| 13583 |
jit::JitOptions.disableRedundantGCBarriers = true; |
| 13584 |
} else { |
| 13585 |
return OptionFailure("ion-optimize-gcbarriers", str); |
| 13586 |
} |
| 13587 |
} |
| 13588 |
|
| 13589 |
if (const char* str = op.getStringOption("ion-instruction-reordering")) { |
| 13590 |
if (strcmp(str, "on") == 0) { |
| 13591 |
jit::JitOptions.disableInstructionReordering = false; |
| 13592 |
} else if (strcmp(str, "off") == 0) { |
| 13593 |
jit::JitOptions.disableInstructionReordering = true; |
| 13594 |
} else { |
| 13595 |
return OptionFailure("ion-instruction-reordering", str); |
| 13596 |
} |
| 13597 |
} |
| 13598 |
|
| 13599 |
if (op.getBoolOption("ion-check-range-analysis")) { |
| 13600 |
jit::JitOptions.checkRangeAnalysis = true; |
| 13601 |
} |
| 13602 |
|
| 13603 |
if (op.getBoolOption("ion-extra-checks")) { |
| 13604 |
jit::JitOptions.runExtraChecks = true; |
| 13605 |
} |
| 13606 |
|
| 13607 |
if (const char* str = op.getStringOption("ion-inlining")) { |
| 13608 |
if (strcmp(str, "on") == 0) { |
| 13609 |
jit::JitOptions.disableInlining = false; |
| 13610 |
} else if (strcmp(str, "off") == 0) { |
| 13611 |
jit::JitOptions.disableInlining = true; |
| 13612 |
} else { |
| 13613 |
return OptionFailure("ion-inlining", str); |
| 13614 |
} |
| 13615 |
} |
| 13616 |
|
| 13617 |
if (const char* str = op.getStringOption("ion-osr")) { |
| 13618 |
if (strcmp(str, "on") == 0) { |
| 13619 |
jit::JitOptions.osr = true; |
| 13620 |
} else if (strcmp(str, "off") == 0) { |
| 13621 |
jit::JitOptions.osr = false; |
| 13622 |
} else { |
| 13623 |
return OptionFailure("ion-osr", str); |
| 13624 |
} |
| 13625 |
} |
| 13626 |
|
| 13627 |
if (const char* str = op.getStringOption("ion-limit-script-size")) { |
| 13628 |
if (strcmp(str, "on") == 0) { |
| 13629 |
jit::JitOptions.limitScriptSize = true; |
| 13630 |
} else if (strcmp(str, "off") == 0) { |
| 13631 |
jit::JitOptions.limitScriptSize = false; |
| 13632 |
} else { |
| 13633 |
return OptionFailure("ion-limit-script-size", str); |
| 13634 |
} |
| 13635 |
} |
| 13636 |
|
| 13637 |
if (op.getBoolOption("disable-main-thread-denormals")) { |
| 13638 |
// This is a simplified version of WebAudio code, which is good enough for |
| 13639 |
// fuzzing purposes. |
| 13640 |
// |
| 13641 |
// See dom/media/webaudio/blink/DenormalDisabler.h#124 |
| 13642 |
#if defined(__GNUC__) && defined(__SSE__) && defined(__x86_64__) |
| 13643 |
int savedCSR; |
| 13644 |
asm volatile("stmxcsr %0" : "=m"(savedCSR)); |
| 13645 |
int newCSR = savedCSR | 0x8040; |
| 13646 |
asm volatile("ldmxcsr %0" : : "m"(newCSR)); |
| 13647 |
#elif defined(__arm__) |
| 13648 |
int savedCSR; |
| 13649 |
asm volatile("vmrs %[result], FPSCR" : [result] "=r"(savedCSR)); |
| 13650 |
// Bit 24 is the flush-to-zero mode control bit. Setting it to 1 flushes |
| 13651 |
// denormals to 0. |
| 13652 |
int newCSR = savedCSR | (1 << 24); |
| 13653 |
asm volatile("vmsr FPSCR, %[src]" : : [src] "r"(newCSR)); |
| 13654 |
#elif defined(__aarch64__) |
| 13655 |
int savedCSR; |
| 13656 |
asm volatile("mrs %x[result], FPCR" : [result] "=r"(savedCSR)); |
| 13657 |
// Bit 24 is the flush-to-zero mode control bit. Setting it to 1 flushes |
| 13658 |
// denormals to 0. |
| 13659 |
int newCSR = savedCSR | (1 << 24); |
| 13660 |
asm volatile("msr FPCR, %x[src]" : : [src] "r"(newCSR)); |
| 13661 |
#else |
| 13662 |
// Do nothing on other architecture. |
| 13663 |
#endif |
| 13664 |
} |
| 13665 |
|
| 13666 |
int32_t warmUpThreshold = op.getIntOption("ion-warmup-threshold"); |
| 13667 |
if (warmUpThreshold >= 0) { |
| 13668 |
jit::JitOptions.setNormalIonWarmUpThreshold(warmUpThreshold); |
| 13669 |
} |
| 13670 |
|
| 13671 |
warmUpThreshold = op.getIntOption("baseline-warmup-threshold"); |
| 13672 |
if (warmUpThreshold >= 0) { |
| 13673 |
jit::JitOptions.baselineJitWarmUpThreshold = warmUpThreshold; |
| 13674 |
} |
| 13675 |
|
| 13676 |
warmUpThreshold = op.getIntOption("trial-inlining-warmup-threshold"); |
| 13677 |
if (warmUpThreshold >= 0) { |
| 13678 |
jit::JitOptions.trialInliningWarmUpThreshold = warmUpThreshold; |
| 13679 |
} |
| 13680 |
|
| 13681 |
warmUpThreshold = op.getIntOption("regexp-warmup-threshold"); |
| 13682 |
if (warmUpThreshold >= 0) { |
| 13683 |
jit::JitOptions.regexpWarmUpThreshold = warmUpThreshold; |
| 13684 |
} |
| 13685 |
|
| 13686 |
if (op.getBoolOption("baseline-eager")) { |
| 13687 |
jit::JitOptions.setEagerBaselineCompilation(); |
| 13688 |
} |
| 13689 |
|
| 13690 |
#ifdef ENABLE_PORTABLE_BASELINE_INTERP |
| 13691 |
if (op.getBoolOption("portable-baseline-eager")) { |
| 13692 |
jit::JitOptions.setEagerPortableBaselineInterpreter(); |
| 13693 |
} |
| 13694 |
if (op.getBoolOption("portable-baseline")) { |
| 13695 |
jit::JitOptions.portableBaselineInterpreter = true; |
| 13696 |
} |
| 13697 |
if (op.getBoolOption("no-portable-baseline")) { |
| 13698 |
jit::JitOptions.portableBaselineInterpreter = false; |
| 13699 |
} |
| 13700 |
#endif |
| 13701 |
|
| 13702 |
#ifdef ENABLE_JS_AOT_ICS |
| 13703 |
if (op.getBoolOption("aot-ics")) { |
| 13704 |
jit::JitOptions.enableAOTICs = true; |
| 13705 |
} |
| 13706 |
if (op.getBoolOption("enforce-aot-ics")) { |
| 13707 |
jit::JitOptions.enableAOTICEnforce = true; |
| 13708 |
} |
| 13709 |
#endif |
| 13710 |
|
| 13711 |
if (op.getBoolOption("blinterp")) { |
| 13712 |
jit::JitOptions.baselineInterpreter = true; |
| 13713 |
} |
| 13714 |
|
| 13715 |
if (op.getBoolOption("no-blinterp")) { |
| 13716 |
jit::JitOptions.baselineInterpreter = false; |
| 13717 |
} |
| 13718 |
|
| 13719 |
if (op.getBoolOption("disable-jithints")) { |
| 13720 |
jit::JitOptions.disableJitHints = true; |
| 13721 |
} |
| 13722 |
|
| 13723 |
if (op.getBoolOption("emit-interpreter-entry")) { |
| 13724 |
jit::JitOptions.emitInterpreterEntryTrampoline = true; |
| 13725 |
} |
| 13726 |
|
| 13727 |
if (op.getBoolOption("no-emit-interpreter-entry")) { |
| 13728 |
jit::JitOptions.emitInterpreterEntryTrampoline = false; |
| 13729 |
} |
| 13730 |
|
| 13731 |
warmUpThreshold = op.getIntOption("blinterp-warmup-threshold"); |
| 13732 |
if (warmUpThreshold >= 0) { |
| 13733 |
jit::JitOptions.baselineInterpreterWarmUpThreshold = warmUpThreshold; |
| 13734 |
} |
| 13735 |
|
| 13736 |
if (op.getBoolOption("blinterp-eager")) { |
| 13737 |
jit::JitOptions.baselineInterpreterWarmUpThreshold = 0; |
| 13738 |
} |
| 13739 |
|
| 13740 |
if (op.getBoolOption("no-baseline")) { |
| 13741 |
jit::JitOptions.baselineJit = false; |
| 13742 |
} |
| 13743 |
|
| 13744 |
if (op.getBoolOption("no-ion")) { |
| 13745 |
jit::JitOptions.ion = false; |
| 13746 |
} |
| 13747 |
|
| 13748 |
if (op.getBoolOption("no-native-regexp")) { |
| 13749 |
jit::JitOptions.nativeRegExp = false; |
| 13750 |
} |
| 13751 |
|
| 13752 |
if (op.getBoolOption("trace-regexp-parser")) { |
| 13753 |
jit::JitOptions.trace_regexp_parser = true; |
| 13754 |
} |
| 13755 |
if (op.getBoolOption("trace-regexp-assembler")) { |
| 13756 |
jit::JitOptions.trace_regexp_assembler = true; |
| 13757 |
} |
| 13758 |
if (op.getBoolOption("trace-regexp-interpreter")) { |
| 13759 |
jit::JitOptions.trace_regexp_bytecodes = true; |
| 13760 |
} |
| 13761 |
if (op.getBoolOption("trace-regexp-peephole")) { |
| 13762 |
jit::JitOptions.trace_regexp_peephole_optimization = true; |
| 13763 |
} |
| 13764 |
|
| 13765 |
if (op.getBoolOption("less-debug-code")) { |
| 13766 |
jit::JitOptions.lessDebugCode = true; |
| 13767 |
} |
| 13768 |
|
| 13769 |
int32_t inliningEntryThreshold = op.getIntOption("inlining-entry-threshold"); |
| 13770 |
if (inliningEntryThreshold > 0) { |
| 13771 |
jit::JitOptions.inliningEntryThreshold = inliningEntryThreshold; |
| 13772 |
} |
| 13773 |
|
| 13774 |
int32_t smallFunctionLength = op.getIntOption("small-function-length"); |
| 13775 |
if (smallFunctionLength > 0) { |
| 13776 |
jit::JitOptions.smallFunctionMaxBytecodeLength = smallFunctionLength; |
| 13777 |
} |
| 13778 |
|
| 13779 |
if (op.getBoolOption("ion-eager")) { |
| 13780 |
jit::JitOptions.setEagerIonCompilation(); |
| 13781 |
} |
| 13782 |
|
| 13783 |
offthreadBaselineCompilation = false; |
| 13784 |
if (const char* str = op.getStringOption("baseline-offthread-compile")) { |
| 13785 |
if (strcmp(str, "on") == 0) { |
| 13786 |
offthreadBaselineCompilation = true; |
| 13787 |
} else if (strcmp(str, "off") != 0) { |
| 13788 |
return OptionFailure("baseline-offthread-compile", str); |
| 13789 |
} |
| 13790 |
} |
| 13791 |
cx->runtime()->setOffthreadBaselineCompilationEnabled( |
| 13792 |
offthreadBaselineCompilation); |
| 13793 |
|
| 13794 |
if (const char* str = op.getStringOption("baseline-batching")) { |
| 13795 |
if (strcmp(str, "on") == 0) { |
| 13796 |
jit::JitOptions.baselineBatching = true; |
| 13797 |
} else if (strcmp(str, "off") == 0) { |
| 13798 |
jit::JitOptions.baselineBatching = false; |
| 13799 |
} else { |
| 13800 |
return OptionFailure("baseline-batching", str); |
| 13801 |
} |
| 13802 |
} |
| 13803 |
|
| 13804 |
int32_t queueCapacity = op.getIntOption("baseline-queue-capacity"); |
| 13805 |
if (queueCapacity == 0) { |
| 13806 |
fprintf(stderr, "baseline-queue-capacity must be positive\n"); |
| 13807 |
return false; |
| 13808 |
} |
| 13809 |
if (queueCapacity > 0) { |
| 13810 |
jit::JitOptions.baselineQueueCapacity = std::min( |
| 13811 |
uint32_t(queueCapacity), js::jit::BaselineCompileQueue::MaxCapacity); |
| 13812 |
} |
| 13813 |
|
| 13814 |
offthreadIonCompilation = true; |
| 13815 |
if (const char* str = op.getStringOption("ion-offthread-compile")) { |
| 13816 |
if (strcmp(str, "off") == 0) { |
| 13817 |
offthreadIonCompilation = false; |
| 13818 |
} else if (strcmp(str, "on") != 0) { |
| 13819 |
return OptionFailure("ion-offthread-compile", str); |
| 13820 |
} |
| 13821 |
} |
| 13822 |
cx->runtime()->setOffthreadIonCompilationEnabled(offthreadIonCompilation); |
| 13823 |
|
| 13824 |
if (op.getStringOption("ion-parallel-compile")) { |
| 13825 |
fprintf(stderr, |
| 13826 |
"--ion-parallel-compile is deprecated. Please use " |
| 13827 |
"--ion-offthread-compile instead.\n"); |
| 13828 |
return false; |
| 13829 |
} |
| 13830 |
|
| 13831 |
if (op.getBoolOption("disable-bailout-loop-check")) { |
| 13832 |
jit::JitOptions.disableBailoutLoopCheck = true; |
| 13833 |
} |
| 13834 |
|
| 13835 |
if (op.getBoolOption("only-inline-selfhosted")) { |
| 13836 |
jit::JitOptions.onlyInlineSelfHosted = true; |
| 13837 |
} |
| 13838 |
|
| 13839 |
if (op.getBoolOption("enable-ic-frame-pointers")) { |
| 13840 |
jit::JitOptions.enableICFramePointers = true; |
| 13841 |
} |
| 13842 |
|
| 13843 |
if (const char* str = op.getStringOption("ion-iterator-indices")) { |
| 13844 |
if (strcmp(str, "on") == 0) { |
| 13845 |
jit::JitOptions.disableIteratorIndices = false; |
| 13846 |
} else if (strcmp(str, "off") == 0) { |
| 13847 |
jit::JitOptions.disableIteratorIndices = true; |
| 13848 |
} else { |
| 13849 |
return OptionFailure("ion-iterator-indices", str); |
| 13850 |
} |
| 13851 |
} |
| 13852 |
|
| 13853 |
if (const char* str = op.getStringOption("ion-load-keys")) { |
| 13854 |
if (strcmp(str, "on") == 0) { |
| 13855 |
jit::JitOptions.disableMarkLoadsUsedAsPropertyKeys = false; |
| 13856 |
} else if (strcmp(str, "off") == 0) { |
| 13857 |
jit::JitOptions.disableMarkLoadsUsedAsPropertyKeys = true; |
| 13858 |
} else { |
| 13859 |
return OptionFailure("ion-load-keys", str); |
| 13860 |
} |
| 13861 |
} |
| 13862 |
|
| 13863 |
#if defined(JS_SIMULATOR_ARM) |
| 13864 |
if (op.getBoolOption("arm-sim-icache-checks")) { |
| 13865 |
jit::SimulatorProcess::ICacheCheckingDisableCount = 0; |
| 13866 |
} |
| 13867 |
|
| 13868 |
int32_t stopAt = op.getIntOption("arm-sim-stop-at"); |
| 13869 |
if (stopAt >= 0) { |
| 13870 |
jit::Simulator::StopSimAt = stopAt; |
| 13871 |
} |
| 13872 |
#elif defined(JS_SIMULATOR_MIPS64) |
| 13873 |
if (op.getBoolOption("mips-sim-icache-checks")) { |
| 13874 |
jit::SimulatorProcess::ICacheCheckingDisableCount = 0; |
| 13875 |
} |
| 13876 |
|
| 13877 |
int32_t stopAt = op.getIntOption("mips-sim-stop-at"); |
| 13878 |
if (stopAt >= 0) { |
| 13879 |
jit::Simulator::StopSimAt = stopAt; |
| 13880 |
} |
| 13881 |
#elif defined(JS_SIMULATOR_LOONG64) |
| 13882 |
if (op.getBoolOption("loong64-sim-icache-checks")) { |
| 13883 |
jit::SimulatorProcess::ICacheCheckingDisableCount = 0; |
| 13884 |
} |
| 13885 |
|
| 13886 |
int32_t stopAt = op.getIntOption("loong64-sim-stop-at"); |
| 13887 |
if (stopAt >= 0) { |
| 13888 |
jit::Simulator::StopSimAt = stopAt; |
| 13889 |
} |
| 13890 |
#endif |
| 13891 |
|
| 13892 |
#ifdef DEBUG |
| 13893 |
# ifdef JS_CODEGEN_RISCV64 |
| 13894 |
if (op.getBoolOption("riscv-debug")) { |
| 13895 |
jit::Assembler::FLAG_riscv_debug = true; |
| 13896 |
} |
| 13897 |
# endif |
| 13898 |
# ifdef JS_SIMULATOR_RISCV64 |
| 13899 |
if (op.getBoolOption("trace-sim")) { |
| 13900 |
jit::Simulator::FLAG_trace_sim = true; |
| 13901 |
} |
| 13902 |
if (op.getBoolOption("debug-sim")) { |
| 13903 |
jit::Simulator::FLAG_debug_sim = true; |
| 13904 |
} |
| 13905 |
if (op.getBoolOption("riscv-trap-to-simulator-debugger")) { |
| 13906 |
jit::Simulator::FLAG_riscv_trap_to_simulator_debugger = true; |
| 13907 |
} |
| 13908 |
int32_t stopAt = op.getIntOption("riscv-sim-stop-at"); |
| 13909 |
if (stopAt >= 0) { |
| 13910 |
jit::Simulator::StopSimAt = stopAt; |
| 13911 |
} |
| 13912 |
# endif |
| 13913 |
#endif |
| 13914 |
|
| 13915 |
if (op.getBoolOption("enable-regexp-duplicate-named-groups")) { |
| 13916 |
jit::JitOptions.js_regexp_duplicate_named_groups = true; |
| 13917 |
} |
| 13918 |
|
| 13919 |
if (op.getBoolOption("enable-regexp-modifiers")) { |
| 13920 |
jit::JitOptions.js_regexp_modifiers = true; |
| 13921 |
} |
| 13922 |
|
| 13923 |
return true; |
| 13924 |
} |
| 13925 |
|
| 13926 |
bool SetContextGCOptions(JSContext* cx, const OptionParser& op) { |
| 13927 |
JS_SetGCParameter(cx, JSGC_MAX_BYTES, 0xffffffff); |
| 13928 |
|
| 13929 |
size_t nurseryBytes = op.getIntOption("nursery-size") * 1024L * 1024L; |
| 13930 |
if (nurseryBytes == 0) { |
| 13931 |
fprintf(stderr, "Error: --nursery-size parameter must be non-zero.\n"); |
| 13932 |
fprintf(stderr, |
| 13933 |
"The nursery can be disabled by passing the --no-ggc option.\n"); |
| 13934 |
return false; |
| 13935 |
} |
| 13936 |
JS_SetGCParameter(cx, JSGC_MAX_NURSERY_BYTES, nurseryBytes); |
| 13937 |
|
| 13938 |
size_t availMemMB = op.getIntOption("available-memory"); |
| 13939 |
if (availMemMB > 0) { |
| 13940 |
JS_SetGCParametersBasedOnAvailableMemory(cx, availMemMB); |
| 13941 |
} |
| 13942 |
|
| 13943 |
if (const char* opt = op.getStringOption("nursery-strings")) { |
| 13944 |
if (strcmp(opt, "on") == 0) { |
| 13945 |
cx->runtime()->gc.nursery().enableStrings(); |
| 13946 |
} else if (strcmp(opt, "off") == 0) { |
| 13947 |
cx->runtime()->gc.nursery().disableStrings(); |
| 13948 |
} else { |
| 13949 |
MOZ_CRASH("invalid option value for --nursery-strings, must be on/off"); |
| 13950 |
} |
| 13951 |
} |
| 13952 |
|
| 13953 |
if (const char* opt = op.getStringOption("nursery-bigints")) { |
| 13954 |
if (strcmp(opt, "on") == 0) { |
| 13955 |
cx->runtime()->gc.nursery().enableBigInts(); |
| 13956 |
} else if (strcmp(opt, "off") == 0) { |
| 13957 |
cx->runtime()->gc.nursery().disableBigInts(); |
| 13958 |
} else { |
| 13959 |
MOZ_CRASH("invalid option value for --nursery-bigints, must be on/off"); |
| 13960 |
} |
| 13961 |
} |
| 13962 |
|
| 13963 |
bool incrementalGC = !op.getBoolOption("no-incremental-gc"); |
| 13964 |
JS_SetGCParameter(cx, JSGC_INCREMENTAL_GC_ENABLED, incrementalGC); |
| 13965 |
|
| 13966 |
#ifndef ANDROID |
| 13967 |
bool parallelMarking = true; |
| 13968 |
#else |
| 13969 |
bool parallelMarking = false; |
| 13970 |
#endif |
| 13971 |
if (op.getBoolOption("enable-parallel-marking")) { |
| 13972 |
parallelMarking = true; |
| 13973 |
} |
| 13974 |
if (op.getBoolOption("no-parallel-marking")) { |
| 13975 |
parallelMarking = false; |
| 13976 |
} |
| 13977 |
JS_SetGCParameter(cx, JSGC_PARALLEL_MARKING_ENABLED, parallelMarking); |
| 13978 |
|
| 13979 |
JS_SetGCParameter(cx, JSGC_SLICE_TIME_BUDGET_MS, 5); |
| 13980 |
|
| 13981 |
JS_SetGCParameter(cx, JSGC_PER_ZONE_GC_ENABLED, true); |
| 13982 |
|
| 13983 |
for (MultiStringRange args = op.getMultiStringOption("gc-param"); |
| 13984 |
!args.empty(); args.popFront()) { |
| 13985 |
if (!SetGCParameterFromArg(cx, args.front())) { |
| 13986 |
return false; |
| 13987 |
} |
| 13988 |
} |
| 13989 |
|
| 13990 |
#ifdef DEBUG |
| 13991 |
dumpEntrainedVariables = op.getBoolOption("dump-entrained-variables"); |
| 13992 |
#endif |
| 13993 |
|
| 13994 |
#ifdef JS_GC_ZEAL |
| 13995 |
const char* zealStr = op.getStringOption("gc-zeal"); |
| 13996 |
if (zealStr) { |
| 13997 |
if (!cx->runtime()->gc.parseAndSetZeal(zealStr)) { |
| 13998 |
return false; |
| 13999 |
} |
| 14000 |
uint32_t nextScheduled; |
| 14001 |
cx->runtime()->gc.getZealBits(&gZealBits, &gZealFrequency, &nextScheduled); |
| 14002 |
} |
| 14003 |
#endif |
| 14004 |
|
| 14005 |
return true; |
| 14006 |
} |
| 14007 |
|
| 14008 |
bool InitModuleLoader(JSContext* cx, const OptionParser& op) { |
| 14009 |
RootedString moduleLoadPath(cx); |
| 14010 |
if (const char* option = op.getStringOption("module-load-path")) { |
| 14011 |
UniqueChars pathUtf8 = JS::EncodeNarrowToUtf8(cx, option); |
| 14012 |
if (!pathUtf8) { |
| 14013 |
return false; |
| 14014 |
} |
| 14015 |
|
| 14016 |
Rooted<JSString*> jspath(cx, NewStringCopyUTF8(cx, pathUtf8.get())); |
| 14017 |
if (!jspath) { |
| 14018 |
return false; |
| 14019 |
} |
| 14020 |
|
| 14021 |
moduleLoadPath = js::shell::ResolvePath(cx, jspath, RootRelative); |
| 14022 |
|
| 14023 |
processWideModuleLoadPath = JS_EncodeStringToUTF8(cx, moduleLoadPath); |
| 14024 |
if (!processWideModuleLoadPath) { |
| 14025 |
return false; |
| 14026 |
} |
| 14027 |
} else { |
| 14028 |
processWideModuleLoadPath = js::shell::GetCWD(cx); |
| 14029 |
if (!processWideModuleLoadPath) { |
| 14030 |
return false; |
| 14031 |
} |
| 14032 |
|
| 14033 |
moduleLoadPath = NewStringCopyUTF8(cx, processWideModuleLoadPath.get()); |
| 14034 |
if (!moduleLoadPath) { |
| 14035 |
return false; |
| 14036 |
} |
| 14037 |
} |
| 14038 |
|
| 14039 |
ShellContext* sc = GetShellContext(cx); |
| 14040 |
sc->moduleLoader = js::MakeUnique<ModuleLoader>(); |
| 14041 |
if (!sc->moduleLoader || !sc->moduleLoader->init(cx, moduleLoadPath)) { |
| 14042 |
return false; |
| 14043 |
} |
| 14044 |
|
| 14045 |
return true; |
| 14046 |
} |