Debian Codegraph @

js/src/vm/ErrorObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sw=2 et tw=80:
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7
8 #include "vm/ErrorObject-inl.h"
9
10 #include "mozilla/Assertions.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/DebugOnly.h"
13 #include "mozilla/Maybe.h"
14
15 #include <utility>
16
17 #include "jsexn.h"
18 #include "jspubtd.h"
19 #include "NamespaceImports.h"
20
21 #include "gc/AllocKind.h"
22 #include "gc/GCContext.h"
23 #include "js/CallArgs.h"
24 #include "js/CallNonGenericMethod.h"
25 #include "js/CharacterEncoding.h" // JS::ConstUTF8CharsZ
26 #include "js/Class.h"
27 #include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin
28 #include "js/Conversions.h"
29 #include "js/ErrorReport.h"
30 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
31 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
32 #include "js/PropertySpec.h"
33 #include "js/RootingAPI.h"
34 #include "js/Stack.h"
35 #include "js/TypeDecls.h"
36 #include "js/Utility.h"
37 #include "js/Value.h"
38 #include "js/Wrapper.h"
39 #include "util/StringBuilder.h"
40 #include "vm/ErrorReporting.h"
41 #include "vm/GlobalObject.h"
42 #include "vm/Iteration.h"
43 #include "vm/JSAtomUtils.h" // ClassName
44 #include "vm/JSFunction.h"
45 #include "vm/JSObject.h"
46 #include "vm/NativeObject.h"
47 #include "vm/ObjectOperations.h"
48 #include "vm/SavedStacks.h"
49 #include "vm/SelfHosting.h"
50 #include "vm/Shape.h"
51 #include "vm/Stack.h"
52 #include "vm/StringType.h"
53 #include "vm/ToSource.h" // js::ValueToSource
54
55 #include "vm/JSContext-inl.h"
56 #include "vm/JSObject-inl.h"
57 #include "vm/ObjectOperations-inl.h"
58 #include "vm/Realm-inl.h"
59 #include "vm/SavedStacks-inl.h"
60 #include "vm/Shape-inl.h"
61
62 using namespace js;
63
64 #define IMPLEMENT_ERROR_PROTO_CLASS(name) \
65 {#name ".prototype", JSCLASS_HAS_CACHED_PROTO(JSProto_##name), \
66 JS_NULL_CLASS_OPS, \
67 &ErrorObject::classSpecs[JSProto_##name - JSProto_Error]}
68
69 const JSClass ErrorObject::protoClasses[JSEXN_ERROR_LIMIT] = {
70 IMPLEMENT_ERROR_PROTO_CLASS(Error),
71
72 IMPLEMENT_ERROR_PROTO_CLASS(InternalError),
73 IMPLEMENT_ERROR_PROTO_CLASS(AggregateError),
74 IMPLEMENT_ERROR_PROTO_CLASS(EvalError),
75 IMPLEMENT_ERROR_PROTO_CLASS(RangeError),
76 IMPLEMENT_ERROR_PROTO_CLASS(ReferenceError),
77 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
78 IMPLEMENT_ERROR_PROTO_CLASS(SuppressedError),
79 #endif
80 IMPLEMENT_ERROR_PROTO_CLASS(SyntaxError),
81 IMPLEMENT_ERROR_PROTO_CLASS(TypeError),
82 IMPLEMENT_ERROR_PROTO_CLASS(URIError),
83
84 IMPLEMENT_ERROR_PROTO_CLASS(DebuggeeWouldRun),
85 IMPLEMENT_ERROR_PROTO_CLASS(CompileError),
86 IMPLEMENT_ERROR_PROTO_CLASS(LinkError),
87 IMPLEMENT_ERROR_PROTO_CLASS(RuntimeError),
88 #ifdef ENABLE_WASM_JSPI
89 IMPLEMENT_ERROR_PROTO_CLASS(SuspendError),
90 #endif
91 };
92
93 static bool exn_toSource(JSContext* cx, unsigned argc, Value* vp);
94
95 static const JSFunctionSpec error_methods[] = {
96 JS_FN("toSource", exn_toSource, 0, 0),
97 JS_SELF_HOSTED_FN("toString", "ErrorToString", 0, 0),
98 JS_FS_END,
99 };
100
101 static bool exn_isError(JSContext* cx, unsigned argc, Value* vp);
102
103 static bool exn_captureStackTrace(JSContext* cx, unsigned argc, Value* vp);
104
105 static const JSFunctionSpec error_static_methods[] = {
106 JS_FN("isError", exn_isError, 1, 0),
107 JS_FN("captureStackTrace", exn_captureStackTrace, 2, 0),
108 JS_FS_END,
109 };
110
111 // Error.prototype and NativeError.prototype have own .message and .name
112 // properties.
113 #define COMMON_ERROR_PROPERTIES(name) \
114 JS_STRING_PS("message", "", 0), JS_STRING_PS("name", #name, 0)
115
116 static const JSPropertySpec error_properties[] = {
117 COMMON_ERROR_PROPERTIES(Error),
118 // Only Error.prototype has .stack!
119 JS_PSGS("stack", ErrorObject::getStack, ErrorObject::setStack, 0),
120 JS_PS_END,
121 };
122
123 #define IMPLEMENT_NATIVE_ERROR_PROPERTIES(name) \
124 static const JSPropertySpec name##_properties[] = { \
125 COMMON_ERROR_PROPERTIES(name), JS_PS_END};
126
127 IMPLEMENT_NATIVE_ERROR_PROPERTIES(InternalError)
128 IMPLEMENT_NATIVE_ERROR_PROPERTIES(AggregateError)
129 IMPLEMENT_NATIVE_ERROR_PROPERTIES(EvalError)
130 IMPLEMENT_NATIVE_ERROR_PROPERTIES(RangeError)
131 IMPLEMENT_NATIVE_ERROR_PROPERTIES(ReferenceError)
132 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
133 IMPLEMENT_NATIVE_ERROR_PROPERTIES(SuppressedError)
134 #endif
135 IMPLEMENT_NATIVE_ERROR_PROPERTIES(SyntaxError)
136 IMPLEMENT_NATIVE_ERROR_PROPERTIES(TypeError)
137 IMPLEMENT_NATIVE_ERROR_PROPERTIES(URIError)
138 IMPLEMENT_NATIVE_ERROR_PROPERTIES(DebuggeeWouldRun)
139 IMPLEMENT_NATIVE_ERROR_PROPERTIES(CompileError)
140 IMPLEMENT_NATIVE_ERROR_PROPERTIES(LinkError)
141 IMPLEMENT_NATIVE_ERROR_PROPERTIES(RuntimeError)
142 #ifdef ENABLE_WASM_JSPI
143 IMPLEMENT_NATIVE_ERROR_PROPERTIES(SuspendError)
144 #endif
145
146 #define IMPLEMENT_NATIVE_ERROR_SPEC(name) \
147 {ErrorObject::createConstructor, \
148 ErrorObject::createProto, \
149 nullptr, \
150 nullptr, \
151 nullptr, \
152 name##_properties, \
153 nullptr, \
154 JSProto_Error}
155
156 #define IMPLEMENT_NONGLOBAL_ERROR_SPEC(name) \
157 {ErrorObject::createConstructor, \
158 ErrorObject::createProto, \
159 nullptr, \
160 nullptr, \
161 nullptr, \
162 name##_properties, \
163 nullptr, \
164 JSProto_Error | ClassSpec::DontDefineConstructor}
165
166 const ClassSpec ErrorObject::classSpecs[JSEXN_ERROR_LIMIT] = {
167 {ErrorObject::createConstructor, ErrorObject::createProto,
168 error_static_methods, nullptr, error_methods, error_properties},
169
170 IMPLEMENT_NATIVE_ERROR_SPEC(InternalError),
171 IMPLEMENT_NATIVE_ERROR_SPEC(AggregateError),
172 IMPLEMENT_NATIVE_ERROR_SPEC(EvalError),
173 IMPLEMENT_NATIVE_ERROR_SPEC(RangeError),
174 IMPLEMENT_NATIVE_ERROR_SPEC(ReferenceError),
175 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
176 IMPLEMENT_NATIVE_ERROR_SPEC(SuppressedError),
177 #endif
178 IMPLEMENT_NATIVE_ERROR_SPEC(SyntaxError),
179 IMPLEMENT_NATIVE_ERROR_SPEC(TypeError),
180 IMPLEMENT_NATIVE_ERROR_SPEC(URIError),
181
182 IMPLEMENT_NONGLOBAL_ERROR_SPEC(DebuggeeWouldRun),
183 IMPLEMENT_NONGLOBAL_ERROR_SPEC(CompileError),
184 IMPLEMENT_NONGLOBAL_ERROR_SPEC(LinkError),
185 IMPLEMENT_NONGLOBAL_ERROR_SPEC(RuntimeError),
186 #ifdef ENABLE_WASM_JSPI
187 IMPLEMENT_NONGLOBAL_ERROR_SPEC(SuspendError),
188 #endif
189 };
190
191 #define IMPLEMENT_ERROR_CLASS_CORE(name, reserved_slots) \
192 {#name, \
193 JSCLASS_HAS_CACHED_PROTO(JSProto_##name) | \
194 JSCLASS_HAS_RESERVED_SLOTS(reserved_slots) | \
195 JSCLASS_BACKGROUND_FINALIZE, \
196 &ErrorObjectClassOps, \
197 &ErrorObject::classSpecs[JSProto_##name - JSProto_Error]}
198
199 #define IMPLEMENT_ERROR_CLASS(name) \
200 IMPLEMENT_ERROR_CLASS_CORE(name, ErrorObject::RESERVED_SLOTS)
201
202 // Only used for classes that could be a Wasm trap. Classes that use this
203 // macro should be kept in sync with the exception types that mightBeWasmTrap()
204 // will return true for.
205 #define IMPLEMENT_ERROR_CLASS_MAYBE_WASM_TRAP(name) \
206 IMPLEMENT_ERROR_CLASS_CORE(name, ErrorObject::RESERVED_SLOTS_MAYBE_WASM_TRAP)
207
208 static void exn_finalize(JS::GCContext* gcx, JSObject* obj);
209
210 static const JSClassOps ErrorObjectClassOps = {
211 nullptr, // addProperty
212 nullptr, // delProperty
213 nullptr, // enumerate
214 nullptr, // newEnumerate
215 nullptr, // resolve
216 nullptr, // mayResolve
217 exn_finalize, // finalize
218 nullptr, // call
219 nullptr, // construct
220 nullptr, // trace
221 };
222
223 const JSClass ErrorObject::classes[JSEXN_ERROR_LIMIT] = {
224 IMPLEMENT_ERROR_CLASS(Error),
225 IMPLEMENT_ERROR_CLASS_MAYBE_WASM_TRAP(InternalError),
226 IMPLEMENT_ERROR_CLASS(AggregateError),
227 IMPLEMENT_ERROR_CLASS(EvalError),
228 IMPLEMENT_ERROR_CLASS(RangeError),
229 IMPLEMENT_ERROR_CLASS(ReferenceError),
230 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
231 IMPLEMENT_ERROR_CLASS(SuppressedError),
232 #endif
233 IMPLEMENT_ERROR_CLASS(SyntaxError),
234 IMPLEMENT_ERROR_CLASS(TypeError),
235 IMPLEMENT_ERROR_CLASS(URIError),
236 // These Error subclasses are not accessible via the global object:
237 IMPLEMENT_ERROR_CLASS(DebuggeeWouldRun),
238 IMPLEMENT_ERROR_CLASS(CompileError),
239 IMPLEMENT_ERROR_CLASS(LinkError),
240 IMPLEMENT_ERROR_CLASS_MAYBE_WASM_TRAP(RuntimeError),
241 #ifdef ENABLE_WASM_JSPI
242 IMPLEMENT_ERROR_CLASS(SuspendError),
243 #endif
244 };
245
246 static void exn_finalize(JS::GCContext* gcx, JSObject* obj) {
247 if (JSErrorReport* report = obj->as<ErrorObject>().getErrorReport()) {
248 // Bug 1560019: This allocation is not currently tracked.
249 gcx->deleteUntracked(report);
250 }
251 }
252
253 static ErrorObject* CreateErrorObject(JSContext* cx, const CallArgs& args,
254 unsigned messageArg, JSExnType exnType,
255 HandleObject proto) {
256 // Compute the error message, if any.
257 RootedString message(cx, nullptr);
258 if (args.hasDefined(messageArg)) {
259 message = ToString<CanGC>(cx, args[messageArg]);
260 if (!message) {
261 return nullptr;
262 }
263 }
264
265 // Don't interpret the two parameters following the message parameter as the
266 // non-standard fileName and lineNumber arguments when we have an options
267 // object argument.
268 bool hasOptions = args.get(messageArg + 1).isObject();
269
270 Rooted<mozilla::Maybe<Value>> cause(cx, mozilla::Nothing());
271 if (hasOptions) {
272 RootedObject options(cx, &args[messageArg + 1].toObject());
273
274 bool hasCause = false;
275 if (!HasProperty(cx, options, cx->names().cause, &hasCause)) {
276 return nullptr;
277 }
278
279 if (hasCause) {
280 RootedValue causeValue(cx);
281 if (!GetProperty(cx, options, options, cx->names().cause, &causeValue)) {
282 return nullptr;
283 }
284 cause = mozilla::Some(causeValue.get());
285 }
286 }
287
288 // Find the scripted caller, but only ones we're allowed to know about.
289 NonBuiltinFrameIter iter(cx, cx->realm()->principals());
290
291 RootedString fileName(cx);
292 uint32_t sourceId = 0;
293 if (!hasOptions && args.length() > messageArg + 1) {
294 fileName = ToString<CanGC>(cx, args[messageArg + 1]);
295 } else {
296 fileName = cx->runtime()->emptyString;
297 if (!iter.done()) {
298 if (const char* cfilename = iter.filename()) {
299 fileName = JS_NewStringCopyUTF8Z(
300 cx, JS::ConstUTF8CharsZ(cfilename, strlen(cfilename)));
301 }
302 if (iter.hasScript()) {
303 sourceId = iter.script()->scriptSource()->id();
304 }
305 }
306 }
307 if (!fileName) {
308 return nullptr;
309 }
310
311 uint32_t lineNumber;
312 JS::ColumnNumberOneOrigin columnNumber;
313 if (!hasOptions && args.length() > messageArg + 2) {
314 if (!ToUint32(cx, args[messageArg + 2], &lineNumber)) {
315 return nullptr;
316 }
317 } else {
318 JS::TaggedColumnNumberOneOrigin tmp;
319 lineNumber = iter.done() ? 0 : iter.computeLine(&tmp);
320 columnNumber = JS::ColumnNumberOneOrigin(tmp.oneOriginValue());
321 }
322
323 RootedObject stack(cx);
324 if (!CaptureStack(cx, &stack)) {
325 return nullptr;
326 }
327
328 return ErrorObject::create(cx, exnType, stack, fileName, sourceId, lineNumber,
329 columnNumber, nullptr, message, cause, proto);
330 }
331
332 static bool Error(JSContext* cx, unsigned argc, Value* vp) {
333 CallArgs args = CallArgsFromVp(argc, vp);
334
335 // ECMA ed. 3, 15.11.1 requires Error, etc., to construct even when
336 // called as functions, without operator new. But as we do not give
337 // each constructor a distinct JSClass, we must get the exception type
338 // ourselves.
339 JSExnType exnType =
340 JSExnType(args.callee().as<JSFunction>().getExtendedSlot(0).toInt32());
341
342 MOZ_ASSERT(exnType != JSEXN_AGGREGATEERR,
343 "AggregateError has its own constructor function");
344
345 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
346 MOZ_ASSERT(exnType != JSEXN_SUPPRESSEDERR,
347 "SuppressedError has its own constuctor function");
348 #endif
349
350 JSProtoKey protoKey =
351 JSCLASS_CACHED_PROTO_KEY(&ErrorObject::classes[exnType]);
352
353 // ES6 19.5.1.1 mandates the .prototype lookup happens before the toString
354 RootedObject proto(cx);
355 if (!GetPrototypeFromBuiltinConstructor(cx, args, protoKey, &proto)) {
356 return false;
357 }
358
359 auto* obj = CreateErrorObject(cx, args, 0, exnType, proto);
360 if (!obj) {
361 return false;
362 }
363
364 args.rval().setObject(*obj);
365 return true;
366 }
367
368 // AggregateError ( errors, message )
369 static bool AggregateError(JSContext* cx, unsigned argc, Value* vp) {
370 CallArgs args = CallArgsFromVp(argc, vp);
371
372 mozilla::DebugOnly<JSExnType> exnType =
373 JSExnType(args.callee().as<JSFunction>().getExtendedSlot(0).toInt32());
374
375 MOZ_ASSERT(exnType == JSEXN_AGGREGATEERR);
376
377 // Steps 1-2. (9.1.13 OrdinaryCreateFromConstructor, steps 1-2).
378 RootedObject proto(cx);
379 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_AggregateError,
380 &proto)) {
381 return false;
382 }
383
384 // TypeError anyway, but this gives a better error message.
385 if (!args.requireAtLeast(cx, "AggregateError", 1)) {
386 return false;
387 }
388
389 // 9.1.13 OrdinaryCreateFromConstructor, step 3.
390 // Step 3.
391 Rooted<ErrorObject*> obj(
392 cx, CreateErrorObject(cx, args, 1, JSEXN_AGGREGATEERR, proto));
393 if (!obj) {
394 return false;
395 }
396
397 // Step 4.
398
399 Rooted<ArrayObject*> errorsList(cx);
400 if (!IterableToArray(cx, args.get(0), &errorsList)) {
401 return false;
402 }
403
404 // Step 5.
405 RootedValue errorsVal(cx, JS::ObjectValue(*errorsList));
406 if (!NativeDefineDataProperty(cx, obj, cx->names().errors, errorsVal, 0)) {
407 return false;
408 }
409
410 // Step 6.
411 args.rval().setObject(*obj);
412 return true;
413 }
414
415 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
416 // Explicit Resource Management Proposal
417 // SuppressedError ( error, suppressed, message )
418 // https://arai-a.github.io/ecma262-compare/?pr=3000&id=sec-suppressederror
419 static bool SuppressedError(JSContext* cx, unsigned argc, Value* vp) {
420 CallArgs args = CallArgsFromVp(argc, vp);
421
422 mozilla::DebugOnly<JSExnType> exnType =
423 JSExnType(args.callee().as<JSFunction>().getExtendedSlot(0).toInt32());
424
425 MOZ_ASSERT(exnType == JSEXN_SUPPRESSEDERR);
426
427 // Step 1. If NewTarget is undefined, let newTarget be the active function
428 // object; else let newTarget be NewTarget.
429 // Step 2. Let O be ? OrdinaryCreateFromConstructor(newTarget,
430 // "%SuppressedError.prototype%", « [[ErrorData]] »).
431 JS::Rooted<JSObject*> proto(cx);
432
433 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_SuppressedError,
434 &proto)) {
435 return false;
436 }
437
438 // Step 3. If message is not undefined, then
439 // Step 3.a. Let messageString be ? ToString(message).
440 // Step 3.b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message",
441 // messageString).
442 JS::Rooted<ErrorObject*> obj(
443 cx, CreateErrorObject(cx, args, 2, JSEXN_SUPPRESSEDERR, proto));
444
445 if (!obj) {
446 return false;
447 }
448
449 // Step 4. Perform CreateNonEnumerableDataPropertyOrThrow(O, "error", error).
450 JS::Rooted<JS::Value> errorVal(cx, args.get(0));
451 if (!NativeDefineDataProperty(cx, obj, cx->names().error, errorVal, 0)) {
452 return false;
453 }
454
455 // Step 5. Perform CreateNonEnumerableDataPropertyOrThrow(O, "suppressed",
456 // suppressed).
457 JS::Rooted<JS::Value> suppressedVal(cx, args.get(1));
458 if (!NativeDefineDataProperty(cx, obj, cx->names().suppressed, suppressedVal,
459 0)) {
460 return false;
461 }
462
463 // Step 6. Return O.
464 args.rval().setObject(*obj);
465 return true;
466 }
467 #endif
468
469 /* static */
470 JSObject* ErrorObject::createProto(JSContext* cx, JSProtoKey key) {
471 JSExnType type = ExnTypeFromProtoKey(key);
472
473 if (type == JSEXN_ERR) {
474 return GlobalObject::createBlankPrototype(
475 cx, cx->global(), &ErrorObject::protoClasses[JSEXN_ERR]);
476 }
477
478 RootedObject protoProto(
479 cx, GlobalObject::getOrCreateErrorPrototype(cx, cx->global()));
480 if (!protoProto) {
481 return nullptr;
482 }
483
484 return GlobalObject::createBlankPrototypeInheriting(
485 cx, &ErrorObject::protoClasses[type], protoProto);
486 }
487
488 /* static */
489 JSObject* ErrorObject::createConstructor(JSContext* cx, JSProtoKey key) {
490 JSExnType type = ExnTypeFromProtoKey(key);
491 RootedObject ctor(cx);
492
493 if (type == JSEXN_ERR) {
494 ctor = GenericCreateConstructor<Error, 1, gc::AllocKind::FUNCTION_EXTENDED>(
495 cx, key);
496 } else {
497 RootedFunction proto(
498 cx, GlobalObject::getOrCreateErrorConstructor(cx, cx->global()));
499 if (!proto) {
500 return nullptr;
501 }
502
503 Native native;
504 unsigned nargs;
505 if (type == JSEXN_AGGREGATEERR) {
506 native = AggregateError;
507 nargs = 2;
508 }
509 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
510 else if (type == JSEXN_SUPPRESSEDERR) {
511 native = SuppressedError;
512 nargs = 3;
513 }
514 #endif
515 else {
516 native = Error;
517 nargs = 1;
518 }
519
520 ctor =
521 NewFunctionWithProto(cx, native, nargs, FunctionFlags::NATIVE_CTOR,
522 nullptr, ClassName(key, cx), proto,
523 gc::AllocKind::FUNCTION_EXTENDED, TenuredObject);
524 }
525
526 if (!ctor) {
527 return nullptr;
528 }
529
530 ctor->as<JSFunction>().setExtendedSlot(0, Int32Value(type));
531 return ctor;
532 }
533
534 /* static */
535 SharedShape* js::ErrorObject::assignInitialShape(JSContext* cx,
536 Handle<ErrorObject*> obj) {
537 MOZ_ASSERT(obj->empty());
538
539 constexpr PropertyFlags propFlags = {PropertyFlag::Configurable,
540 PropertyFlag::Writable};
541
542 if (!NativeObject::addPropertyInReservedSlot(cx, obj, cx->names().fileName,
543 FILENAME_SLOT, propFlags)) {
544 return nullptr;
545 }
546
547 if (!NativeObject::addPropertyInReservedSlot(cx, obj, cx->names().lineNumber,
548 LINENUMBER_SLOT, propFlags)) {
549 return nullptr;
550 }
551
552 if (!NativeObject::addPropertyInReservedSlot(
553 cx, obj, cx->names().columnNumber, COLUMNNUMBER_SLOT, propFlags)) {
554 return nullptr;
555 }
556
557 return obj->sharedShape();
558 }
559
560 /* static */
561 bool js::ErrorObject::init(JSContext* cx, Handle<ErrorObject*> obj,
562 JSExnType type, UniquePtr<JSErrorReport> errorReport,
563 HandleString fileName, HandleObject stack,
564 uint32_t sourceId, uint32_t lineNumber,
565 JS::ColumnNumberOneOrigin columnNumber,
566 HandleString message,
567 Handle<mozilla::Maybe<JS::Value>> cause) {
568 MOZ_ASSERT(JSEXN_ERR <= type && type < JSEXN_ERROR_LIMIT);
569 AssertObjectIsSavedFrameOrWrapper(cx, stack);
570 cx->check(obj, stack);
571
572 // Null out early in case of error, for exn_finalize's sake.
573 obj->initReservedSlot(ERROR_REPORT_SLOT, PrivateValue(nullptr));
574
575 if (!SharedShape::ensureInitialCustomShape<ErrorObject>(cx, obj)) {
576 return false;
577 }
578
579 // The .message property isn't part of the initial shape because it's
580 // present in some error objects -- |Error.prototype|, |new Error("f")|,
581 // |new Error("")| -- but not in others -- |new Error(undefined)|,
582 // |new Error()|.
583 if (message) {
584 constexpr PropertyFlags propFlags = {PropertyFlag::Configurable,
585 PropertyFlag::Writable};
586 if (!NativeObject::addPropertyInReservedSlot(cx, obj, cx->names().message,
587 MESSAGE_SLOT, propFlags)) {
588 return false;
589 }
590 }
591
592 // Similar to the .message property, .cause is present only in some error
593 // objects -- |new Error("f", {cause: cause})| -- but not in other --
594 // |Error.prototype|, |new Error()|, |new Error("f")|.
595 if (cause.isSome()) {
596 constexpr PropertyFlags propFlags = {PropertyFlag::Configurable,
597 PropertyFlag::Writable};
598 if (!NativeObject::addPropertyInReservedSlot(cx, obj, cx->names().cause,
599 CAUSE_SLOT, propFlags)) {
600 return false;
601 }
602 }
603
604 MOZ_ASSERT(obj->lookupPure(NameToId(cx->names().fileName))->slot() ==
605 FILENAME_SLOT);
606 MOZ_ASSERT(obj->lookupPure(NameToId(cx->names().lineNumber))->slot() ==
607 LINENUMBER_SLOT);
608 MOZ_ASSERT(obj->lookupPure(NameToId(cx->names().columnNumber))->slot() ==
609 COLUMNNUMBER_SLOT);
610 MOZ_ASSERT_IF(
611 message,
612 obj->lookupPure(NameToId(cx->names().message))->slot() == MESSAGE_SLOT);
613 MOZ_ASSERT_IF(
614 cause.isSome(),
615 obj->lookupPure(NameToId(cx->names().cause))->slot() == CAUSE_SLOT);
616
617 JSErrorReport* report = errorReport.release();
618 obj->initReservedSlot(STACK_SLOT, ObjectOrNullValue(stack));
619 obj->setReservedSlot(ERROR_REPORT_SLOT, PrivateValue(report));
620 obj->initReservedSlot(FILENAME_SLOT, StringValue(fileName));
621 obj->initReservedSlot(LINENUMBER_SLOT, Int32Value(lineNumber));
622 obj->initReservedSlot(COLUMNNUMBER_SLOT,
623 Int32Value(columnNumber.oneOriginValue()));
624 if (message) {
625 obj->initReservedSlot(MESSAGE_SLOT, StringValue(message));
626 }
627 if (cause.isSome()) {
628 obj->initReservedSlot(CAUSE_SLOT, *cause.get());
629 } else {
630 obj->initReservedSlot(CAUSE_SLOT, MagicValue(JS_ERROR_WITHOUT_CAUSE));
631 }
632 obj->initReservedSlot(SOURCEID_SLOT, Int32Value(sourceId));
633 if (obj->mightBeWasmTrap()) {
634 MOZ_ASSERT(JSCLASS_RESERVED_SLOTS(obj->getClass()) > WASM_TRAP_SLOT);
635 obj->initReservedSlot(WASM_TRAP_SLOT, BooleanValue(false));
636 }
637
638 return true;
639 }
640
641 /* static */
642 ErrorObject* js::ErrorObject::create(JSContext* cx, JSExnType errorType,
643 HandleObject stack, HandleString fileName,
644 uint32_t sourceId, uint32_t lineNumber,
645 JS::ColumnNumberOneOrigin columnNumber,
646 UniquePtr<JSErrorReport> report,
647 HandleString message,
648 Handle<mozilla::Maybe<JS::Value>> cause,
649 HandleObject protoArg /* = nullptr */) {
650 AssertObjectIsSavedFrameOrWrapper(cx, stack);
651
652 RootedObject proto(cx, protoArg);
653 if (!proto) {
654 proto = GlobalObject::getOrCreateCustomErrorPrototype(cx, cx->global(),
655 errorType);
656 if (!proto) {
657 return nullptr;
658 }
659 }
660
661 Rooted<ErrorObject*> errObject(cx);
662 {
663 const JSClass* clasp = ErrorObject::classForType(errorType);
664 JSObject* obj = NewObjectWithGivenProto(cx, clasp, proto);
665 if (!obj) {
666 return nullptr;
667 }
668 errObject = &obj->as<ErrorObject>();
669 }
670
671 if (!ErrorObject::init(cx, errObject, errorType, std::move(report), fileName,
672 stack, sourceId, lineNumber, columnNumber, message,
673 cause)) {
674 return nullptr;
675 }
676
677 return errObject;
678 }
679
680 JSErrorReport* js::ErrorObject::getOrCreateErrorReport(JSContext* cx) {
681 if (JSErrorReport* r = getErrorReport()) {
682 return r;
683 }
684
685 // We build an error report on the stack and then use CopyErrorReport to do
686 // the nitty-gritty malloc stuff.
687 JSErrorReport report;
688
689 // Type.
690 JSExnType type_ = type();
691 report.exnType = type_;
692
693 // Filename.
694 RootedString filename(cx, fileName(cx));
695 UniqueChars filenameStr = JS_EncodeStringToUTF8(cx, filename);
696 if (!filenameStr) {
697 return nullptr;
698 }
699 report.filename = JS::ConstUTF8CharsZ(filenameStr.get());
700
701 // Coordinates.
702 report.sourceId = sourceId();
703 report.lineno = lineNumber();
704 report.column = columnNumber();
705
706 // Message. Note that |new Error()| will result in an undefined |message|
707 // slot, so we need to explicitly substitute the empty string in that case.
708 RootedString message(cx, getMessage());
709 if (!message) {
710 message = cx->runtime()->emptyString;
711 }
712
713 UniqueChars utf8 = StringToNewUTF8CharsZ(cx, *message);
714 if (!utf8) {
715 return nullptr;
716 }
717 report.initOwnedMessage(utf8.release());
718
719 // Cache and return.
720 UniquePtr<JSErrorReport> copy = CopyErrorReport(cx, &report);
721 if (!copy) {
722 return nullptr;
723 }
724 setReservedSlot(ERROR_REPORT_SLOT, PrivateValue(copy.get()));
725 return copy.release();
726 }
727
728 static bool FindErrorInstanceOrPrototype(JSContext* cx, HandleObject obj,
729 MutableHandleObject result) {
730 // Walk up the prototype chain until we find an error object instance or
731 // prototype object. This allows code like:
732 // Object.create(Error.prototype).stack
733 // or
734 // function NYI() { }
735 // NYI.prototype = new Error;
736 // (new NYI).stack
737 // to continue returning stacks that are useless, but at least don't throw.
738
739 RootedObject curr(cx, obj);
740 RootedObject target(cx);
741 do {
742 target = CheckedUnwrapStatic(curr);
743 if (!target) {
744 ReportAccessDenied(cx);
745 return false;
746 }
747 if (IsErrorProtoKey(StandardProtoKeyOrNull(target))) {
748 result.set(target);
749 return true;
750 }
751
752 if (!GetPrototype(cx, curr, &curr)) {
753 return false;
754 }
755 } while (curr);
756
757 // We walked the whole prototype chain and did not find an Error
758 // object.
759 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
760 JSMSG_INCOMPATIBLE_PROTO, "Error", "(get stack)",
761 obj->getClass()->name);
762 return false;
763 }
764
765 static MOZ_ALWAYS_INLINE bool IsObject(HandleValue v) { return v.isObject(); }
766
767 // This is a helper method for telemetry to provide feedback for
768 // proposal-error-stack-accessor and can be removed (Bug 1943623).
769 // It is based upon the implementation of exn_isError.
770 static bool HasErrorDataSlot(JSContext* cx, HandleObject obj) {
771 JSObject* unwrappedObject = CheckedUnwrapStatic(obj);
772 if (!unwrappedObject) {
773 return false;
774 }
775
776 if (JS_IsDeadWrapper(unwrappedObject)) {
777 return false;
778 }
779
780 if (unwrappedObject->is<ErrorObject>()) {
781 return true;
782 }
783 if (unwrappedObject->getClass()->isDOMClass()) {
784 return cx->runtime()->DOMcallbacks->instanceClassIsError(
785 unwrappedObject->getClass());
786 }
787
788 return false;
789 }
790
791 /* static */
792 bool js::ErrorObject::getStack(JSContext* cx, unsigned argc, Value* vp) {
793 CallArgs args = CallArgsFromVp(argc, vp);
794 // We accept any object here, because of poor-man's subclassing of Error.
795 return CallNonGenericMethod<IsObject, getStack_impl>(cx, args);
796 }
797
798 /* static */
799 bool js::ErrorObject::getStack_impl(JSContext* cx, const CallArgs& args) {
800 RootedObject thisObj(cx, &args.thisv().toObject());
801
802 // This telemetry to provide feedback for proposal-error-stack-accessor and
803 // can later be removed (Bug 1943623).
804 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::ERRORSTACK_GETTER);
805 if (!HasErrorDataSlot(cx, thisObj)) {
806 cx->runtime()->setUseCounter(cx->global(),
807 JSUseCounter::ERRORSTACK_GETTER_NO_ERRORDATA);
808 }
809
810 RootedObject obj(cx);
811 if (!FindErrorInstanceOrPrototype(cx, thisObj, &obj)) {
812 return false;
813 }
814
815 if (!obj->is<ErrorObject>()) {
816 args.rval().setString(cx->runtime()->emptyString);
817 return true;
818 }
819
820 // Do frame filtering based on the ErrorObject's principals. This ensures we
821 // don't see chrome frames when chrome code accesses .stack over Xrays.
822 JSPrincipals* principals = obj->as<ErrorObject>().realm()->principals();
823
824 RootedObject savedFrameObj(cx, obj->as<ErrorObject>().stack());
825 RootedString stackString(cx);
826 if (!BuildStackString(cx, principals, savedFrameObj, &stackString)) {
827 return false;
828 }
829
830 if (cx->runtime()->stackFormat() == js::StackFormat::V8) {
831 // When emulating V8 stack frames, we also need to prepend the
832 // stringified Error to the stack string.
833 Handle<PropertyName*> name = cx->names().ErrorToStringWithTrailingNewline;
834 FixedInvokeArgs<0> args2(cx);
835 RootedValue rval(cx);
836 if (!CallSelfHostedFunction(cx, name, args.thisv(), args2, &rval)) {
837 return false;
838 }
839
840 if (!rval.isString()) {
841 args.rval().setString(cx->runtime()->emptyString);
842 return true;
843 }
844
845 RootedString stringified(cx, rval.toString());
846 stackString = ConcatStrings<CanGC>(cx, stringified, stackString);
847 }
848
849 args.rval().setString(stackString);
850 return true;
851 }
852
853 /* static */
854 bool js::ErrorObject::setStack(JSContext* cx, unsigned argc, Value* vp) {
855 CallArgs args = CallArgsFromVp(argc, vp);
856 // We accept any object here, because of poor-man's subclassing of Error.
857 return CallNonGenericMethod<IsObject, setStack_impl>(cx, args);
858 }
859
860 /* static */
861 bool js::ErrorObject::setStack_impl(JSContext* cx, const CallArgs& args) {
862 RootedObject thisObj(cx, &args.thisv().toObject());
863
864 if (!args.requireAtLeast(cx, "(set stack)", 1)) {
865 return false;
866 }
867 RootedValue val(cx, args[0]);
868
869 // This telemetry to provide feedback for proposal-error-stack-accessor and
870 // can later be removed (Bug 1943623).
871 cx->runtime()->setUseCounter(cx->global(), JSUseCounter::ERRORSTACK_SETTER);
872 if (!val.isString()) {
873 cx->runtime()->setUseCounter(cx->global(),
874 JSUseCounter::ERRORSTACK_SETTER_NONSTRING);
875 }
876 if (!HasErrorDataSlot(cx, thisObj)) {
877 cx->runtime()->setUseCounter(cx->global(),
878 JSUseCounter::ERRORSTACK_SETTER_NO_ERRORDATA);
879 }
880 return DefineDataProperty(cx, thisObj, cx->names().stack, val);
881 }
882
883 void js::ErrorObject::setFromWasmTrap() {
884 MOZ_ASSERT(mightBeWasmTrap());
885 MOZ_ASSERT(JSCLASS_RESERVED_SLOTS(getClass()) > WASM_TRAP_SLOT);
886 setReservedSlot(WASM_TRAP_SLOT, BooleanValue(true));
887 }
888
889 JSString* js::ErrorToSource(JSContext* cx, HandleObject obj) {
890 AutoCycleDetector detector(cx, obj);
891 if (!detector.init()) {
892 return nullptr;
893 }
894 if (detector.foundCycle()) {
895 return NewStringCopyZ<CanGC>(cx, "{}");
896 }
897
898 RootedValue nameVal(cx);
899 RootedString name(cx);
900 if (!GetProperty(cx, obj, obj, cx->names().name, &nameVal) ||
901 !(name = ToString<CanGC>(cx, nameVal))) {
902 return nullptr;
903 }
904
905 RootedValue messageVal(cx);
906 RootedString message(cx);
907 if (!GetProperty(cx, obj, obj, cx->names().message, &messageVal) ||
908 !(message = ValueToSource(cx, messageVal))) {
909 return nullptr;
910 }
911
912 RootedValue filenameVal(cx);
913 RootedString filename(cx);
914 if (!GetProperty(cx, obj, obj, cx->names().fileName, &filenameVal) ||
915 !(filename = ValueToSource(cx, filenameVal))) {
916 return nullptr;
917 }
918
919 RootedValue errorsVal(cx);
920 RootedString errors(cx);
921 bool isAggregateError = obj->is<ErrorObject>() &&
922 obj->as<ErrorObject>().type() == JSEXN_AGGREGATEERR;
923 if (isAggregateError) {
924 if (!GetProperty(cx, obj, obj, cx->names().errors, &errorsVal) ||
925 !(errors = ValueToSource(cx, errorsVal))) {
926 return nullptr;
927 }
928 }
929
930 RootedValue linenoVal(cx);
931 uint32_t lineno;
932 if (!GetProperty(cx, obj, obj, cx->names().lineNumber, &linenoVal) ||
933 !ToUint32(cx, linenoVal, &lineno)) {
934 return nullptr;
935 }
936
937 JSStringBuilder sb(cx);
938 if (!sb.append("(new ") || !sb.append(name) || !sb.append("(")) {
939 return nullptr;
940 }
941
942 if (isAggregateError) {
943 if (!sb.append(errors) || !sb.append(", ")) {
944 return nullptr;
945 }
946 }
947
948 if (!sb.append(message)) {
949 return nullptr;
950 }
951
952 if (!filename->empty()) {
953 if (!sb.append(", ") || !sb.append(filename)) {
954 return nullptr;
955 }
956 }
957 if (lineno != 0) {
958 /* We have a line, but no filename, add empty string */
959 if (filename->empty() && !sb.append(", \"\"")) {
960 return nullptr;
961 }
962
963 JSString* linenumber = ToString<CanGC>(cx, linenoVal);
964 if (!linenumber) {
965 return nullptr;
966 }
967 if (!sb.append(", ") || !sb.append(linenumber)) {
968 return nullptr;
969 }
970 }
971
972 if (!sb.append("))")) {
973 return nullptr;
974 }
975
976 return sb.finishString();
977 }
978
979 /*
980 * Return a string that may eval to something similar to the original object.
981 */
982 static bool exn_toSource(JSContext* cx, unsigned argc, Value* vp) {
983 AutoCheckRecursionLimit recursion(cx);
984 if (!recursion.check(cx)) {
985 return false;
986 }
987 CallArgs args = CallArgsFromVp(argc, vp);
988
989 RootedObject obj(cx, ToObject(cx, args.thisv()));
990 if (!obj) {
991 return false;
992 }
993
994 JSString* str = ErrorToSource(cx, obj);
995 if (!str) {
996 return false;
997 }
998
999 args.rval().setString(str);
1000 return true;
1001 }
1002
1003 /**
1004 * Error.isError Proposal
1005 * Error.isError ( arg )
1006 * https://tc39.es/proposal-is-error/#sec-error.iserror
1007 * IsError ( argument )
1008 * https://tc39.es/proposal-is-error/#sec-iserror
1009 */
1010 static bool exn_isError(JSContext* cx, unsigned argc, Value* vp) {
1011 CallArgs args = CallArgsFromVp(argc, vp);
1012
1013 // Error.isError ( arg )
1014 // Step 1. Return IsError(arg).
1015
1016 // IsError ( argument )
1017 // Step 1. If argument is not an Object, return false.
1018 if (!args.get(0).isObject()) {
1019 args.rval().setBoolean(false);
1020 return true;
1021 }
1022
1023 JSObject* unwrappedObject = CheckedUnwrapStatic(&args.get(0).toObject());
1024 if (!unwrappedObject) {
1025 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1026 JSMSG_OBJECT_ACCESS_DENIED);
1027 return false;
1028 }
1029
1030 if (JS_IsDeadWrapper(unwrappedObject)) {
1031 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT);
1032 return false;
1033 }
1034
1035 // Step 2. If argument has an [[ErrorData]] internal slot, return true.
1036 if (unwrappedObject->is<ErrorObject>()) {
1037 args.rval().setBoolean(true);
1038 return true;
1039 }
1040 if (unwrappedObject->getClass()->isDOMClass()) {
1041 args.rval().setBoolean(cx->runtime()->DOMcallbacks->instanceClassIsError(
1042 unwrappedObject->getClass()));
1043 return true;
1044 }
1045
1046 // Step 3. Return false
1047 args.rval().setBoolean(false);
1048 return true;
1049 }
1050
1051 // The below is the "documentation" from https://v8.dev/docs/stack-trace-api
1052 //
1053 // ## Stack trace collection for custom exceptions
1054 //
1055 // The stack trace mechanism used for built-in errors is implemented using a
1056 // general stack trace collection API that is also available to user scripts.
1057 // The function
1058 //
1059 // Error.captureStackTrace(error, constructorOpt)
1060 //
1061 // adds a stack property to the given error object that yields the stack trace
1062 // at the time captureStackTrace was called. Stack traces collected through
1063 // Error.captureStackTrace are immediately collected, formatted, and attached
1064 // to the given error object.
1065 //
1066 // The optional constructorOpt parameter allows you to pass in a function
1067 // value. When collecting the stack trace all frames above the topmost call to
1068 // this function, including that call, are left out of the stack trace. This
1069 // can be useful to hide implementation details that won’t be useful to the
1070 // user. The usual way of defining a custom error that captures a stack trace
1071 // would be:
1072 //
1073 // function MyError() {
1074 // Error.captureStackTrace(this, MyError);
1075 // // Any other initialization goes here.
1076 // }
1077 //
1078 // Passing in MyError as a second argument means that the constructor call to
1079 // MyError won’t show up in the stack trace.
1080
1081 static bool exn_captureStackTrace(JSContext* cx, unsigned argc, Value* vp) {
1082 CallArgs args = CallArgsFromVp(argc, vp);
1083 const char* callerName = "Error.captureStackTrace";
1084
1085 if (!args.requireAtLeast(cx, callerName, 1)) {
1086 return false;
1087 }
1088
1089 Rooted<JSObject*> obj(cx,
1090 RequireObjectArg(cx, "`target`", callerName, args[0]));
1091 if (!obj) {
1092 return false;
1093 }
1094
1095 Rooted<JSObject*> caller(cx, nullptr);
1096 if (args.length() > 1 && args[1].isObject() &&
1097 args[1].toObject().isCallable()) {
1098 caller = CheckedUnwrapStatic(&args[1].toObject());
1099 if (!caller) {
1100 ReportAccessDenied(cx);
1101 return false;
1102 }
1103 }
1104
1105 RootedObject stack(cx);
1106 if (!CaptureCurrentStack(
1107 cx, &stack, JS::StackCapture(JS::MaxFrames(MAX_REPORTED_STACK_DEPTH)),
1108 caller)) {
1109 return false;
1110 }
1111
1112 RootedString stackString(cx);
1113
1114 // Do frame filtering based on the current realm, to filter out any
1115 // chrome frames which could exist on the stack.
1116 JSPrincipals* principals = cx->realm()->principals();
1117 if (!BuildStackString(cx, principals, stack, &stackString)) {
1118 return false;
1119 }
1120
1121 // V8 installs a non-enumerable, configurable getter-setter on the object.
1122 // JSC installs a non-enumerable, configurable, writable value on the
1123 // object. We are following JSC here, not V8.
1124 RootedValue string(cx, StringValue(stackString));
1125 if (!DefineDataProperty(cx, obj, cx->names().stack, string, 0)) {
1126 return false;
1127 }
1128
1129 args.rval().setUndefined();
1130 return true;
1131 }