| 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 |
/* |
| 8 |
* JS standard exception implementation. |
| 9 |
*/ |
| 10 |
|
| 11 |
#include "jsexn.h" |
| 12 |
|
| 13 |
#include "mozilla/Assertions.h" |
| 14 |
#include "mozilla/Maybe.h" |
| 15 |
#include "mozilla/ScopeExit.h" |
| 16 |
|
| 17 |
#include <new> |
| 18 |
#include <stdarg.h> |
| 19 |
#include <stdint.h> |
| 20 |
#include <stdio.h> |
| 21 |
#include <string.h> |
| 22 |
#include <utility> |
| 23 |
|
| 24 |
#include "jsapi.h" |
| 25 |
#include "jsfriendapi.h" |
| 26 |
#include "jstypes.h" |
| 27 |
|
| 28 |
#include "frontend/FrontendContext.h" // AutoReportFrontendContext |
| 29 |
#include "js/CharacterEncoding.h" // JS::UTF8Chars, JS::ConstUTF8CharsZ |
| 30 |
#include "js/Class.h" |
| 31 |
#include "js/ColumnNumber.h" // JS::ColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin |
| 32 |
#include "js/Conversions.h" |
| 33 |
#include "js/ErrorReport.h" // JS::PrintError |
| 34 |
#include "js/Exception.h" // JS::ExceptionStack |
| 35 |
#include "js/experimental/TypedData.h" // JS_IsArrayBufferViewObject |
| 36 |
#include "js/friend/ErrorMessages.h" // JSErrNum, js::GetErrorMessage, JSMSG_* |
| 37 |
#include "js/Object.h" // JS::GetBuiltinClass |
| 38 |
#include "js/PropertyAndElement.h" // JS_GetProperty, JS_HasProperty |
| 39 |
#include "js/SavedFrameAPI.h" |
| 40 |
#include "js/Stack.h" |
| 41 |
#include "js/UniquePtr.h" |
| 42 |
#include "js/Value.h" |
| 43 |
#include "js/Warnings.h" // JS::{,Set}WarningReporter |
| 44 |
#include "js/Wrapper.h" |
| 45 |
#include "util/Memory.h" |
| 46 |
#include "util/StringBuilder.h" |
| 47 |
#include "vm/Compartment.h" |
| 48 |
#include "vm/ErrorObject.h" |
| 49 |
#include "vm/FrameIter.h" // js::NonBuiltinFrameIter |
| 50 |
#include "vm/JSAtomUtils.h" // ClassName |
| 51 |
#include "vm/JSContext.h" |
| 52 |
#include "vm/JSObject.h" |
| 53 |
#include "vm/JSScript.h" |
| 54 |
#include "vm/Realm.h" |
| 55 |
#include "vm/SavedFrame.h" |
| 56 |
#include "vm/SavedStacks.h" |
| 57 |
#include "vm/SelfHosting.h" |
| 58 |
#include "vm/Stack.h" |
| 59 |
#include "vm/StringType.h" |
| 60 |
#include "vm/SymbolType.h" |
| 61 |
#include "wasm/WasmJS.h" // WasmExceptionObject |
| 62 |
|
| 63 |
#include "vm/Compartment-inl.h" |
| 64 |
#include "vm/ErrorObject-inl.h" |
| 65 |
#include "vm/JSContext-inl.h" |
| 66 |
#include "vm/JSObject-inl.h" |
| 67 |
#include "vm/ObjectOperations-inl.h" // js::GetProperty |
| 68 |
#include "vm/SavedStacks-inl.h" |
| 69 |
|
| 70 |
using namespace js; |
| 71 |
|
| 72 |
using JS::SavedFrameSelfHosted; |
| 73 |
|
| 74 |
size_t ExtraMallocSize(JSErrorReport* report) { |
| 75 |
if (report->linebuf()) { |
| 76 |
/* |
| 77 |
* Count with null terminator and alignment. |
| 78 |
* See CopyExtraData for the details about alignment. |
| 79 |
*/ |
| 80 |
return (report->linebufLength() + 1) * sizeof(char16_t) + 1; |
| 81 |
} |
| 82 |
|
| 83 |
return 0; |
| 84 |
} |
| 85 |
|
| 86 |
size_t ExtraMallocSize(JSErrorNotes::Note* note) { return 0; } |
| 87 |
|
| 88 |
bool CopyExtraData(JSContext* cx, uint8_t** cursor, JSErrorReport* copy, |
| 89 |
JSErrorReport* report) { |
| 90 |
if (report->linebuf()) { |
| 91 |
/* |
| 92 |
* Make sure cursor is properly aligned for char16_t for platforms |
| 93 |
* which need it and it's at the end of the buffer on exit. |
| 94 |
*/ |
| 95 |
size_t alignment_backlog = 0; |
| 96 |
if (size_t(*cursor) % 2) { |
| 97 |
(*cursor)++; |
| 98 |
} else { |
| 99 |
alignment_backlog = 1; |
| 100 |
} |
| 101 |
|
| 102 |
size_t linebufSize = (report->linebufLength() + 1) * sizeof(char16_t); |
| 103 |
const char16_t* linebufCopy = (const char16_t*)(*cursor); |
| 104 |
js_memcpy(*cursor, report->linebuf(), linebufSize); |
| 105 |
*cursor += linebufSize + alignment_backlog; |
| 106 |
copy->initBorrowedLinebuf(linebufCopy, report->linebufLength(), |
| 107 |
report->tokenOffset()); |
| 108 |
} |
| 109 |
|
| 110 |
/* Copy non-pointer members. */ |
| 111 |
copy->isMuted = report->isMuted; |
| 112 |
copy->exnType = report->exnType; |
| 113 |
copy->isWarning_ = report->isWarning_; |
| 114 |
|
| 115 |
/* Deep copy notes. */ |
| 116 |
if (report->notes) { |
| 117 |
auto copiedNotes = report->notes->copy(cx); |
| 118 |
if (!copiedNotes) { |
| 119 |
return false; |
| 120 |
} |
| 121 |
copy->notes = std::move(copiedNotes); |
| 122 |
} else { |
| 123 |
copy->notes.reset(nullptr); |
| 124 |
} |
| 125 |
|
| 126 |
return true; |
| 127 |
} |
| 128 |
|
| 129 |
bool CopyExtraData(JSContext* cx, uint8_t** cursor, JSErrorNotes::Note* copy, |
| 130 |
JSErrorNotes::Note* report) { |
| 131 |
return true; |
| 132 |
} |
| 133 |
|
| 134 |
template <typename T> |
| 135 |
static UniquePtr<T> CopyErrorHelper(JSContext* cx, T* report) { |
| 136 |
/* |
| 137 |
* We use a single malloc block to make a deep copy of JSErrorReport or |
| 138 |
* JSErrorNotes::Note, except JSErrorNotes linked from JSErrorReport with |
| 139 |
* the following layout: |
| 140 |
* JSErrorReport or JSErrorNotes::Note |
| 141 |
* char array with characters for message_ |
| 142 |
* char array with characters for filename |
| 143 |
* char16_t array with characters for linebuf (only for JSErrorReport) |
| 144 |
* Such layout together with the properties enforced by the following |
| 145 |
* asserts does not need any extra alignment padding. |
| 146 |
*/ |
| 147 |
static_assert(sizeof(T) % sizeof(const char*) == 0); |
| 148 |
static_assert(sizeof(const char*) % sizeof(char16_t) == 0); |
| 149 |
|
| 150 |
size_t filenameSize = |
| 151 |
report->filename ? strlen(report->filename.c_str()) + 1 : 0; |
| 152 |
size_t messageSize = 0; |
| 153 |
if (report->message()) { |
| 154 |
messageSize = strlen(report->message().c_str()) + 1; |
| 155 |
} |
| 156 |
|
| 157 |
/* |
| 158 |
* The mallocSize can not overflow since it represents the sum of the |
| 159 |
* sizes of already allocated objects. |
| 160 |
*/ |
| 161 |
size_t mallocSize = |
| 162 |
sizeof(T) + messageSize + filenameSize + ExtraMallocSize(report); |
| 163 |
uint8_t* cursor = cx->pod_calloc<uint8_t>(mallocSize); |
| 164 |
if (!cursor) { |
| 165 |
return nullptr; |
| 166 |
} |
| 167 |
|
| 168 |
UniquePtr<T> copy(new (cursor) T()); |
| 169 |
cursor += sizeof(T); |
| 170 |
|
| 171 |
if (report->message()) { |
| 172 |
copy->initBorrowedMessage((const char*)cursor); |
| 173 |
js_memcpy(cursor, report->message().c_str(), messageSize); |
| 174 |
cursor += messageSize; |
| 175 |
} |
| 176 |
|
| 177 |
if (report->filename) { |
| 178 |
copy->filename = JS::ConstUTF8CharsZ((const char*)cursor); |
| 179 |
js_memcpy(cursor, report->filename.c_str(), filenameSize); |
| 180 |
cursor += filenameSize; |
| 181 |
} |
| 182 |
|
| 183 |
if (!CopyExtraData(cx, &cursor, copy.get(), report)) { |
| 184 |
return nullptr; |
| 185 |
} |
| 186 |
|
| 187 |
MOZ_ASSERT(cursor == (uint8_t*)copy.get() + mallocSize); |
| 188 |
|
| 189 |
// errorMessageName should be static. |
| 190 |
copy->errorMessageName = report->errorMessageName; |
| 191 |
|
| 192 |
/* Copy non-pointer members. */ |
| 193 |
copy->sourceId = report->sourceId; |
| 194 |
copy->lineno = report->lineno; |
| 195 |
copy->column = report->column; |
| 196 |
copy->errorNumber = report->errorNumber; |
| 197 |
|
| 198 |
return copy; |
| 199 |
} |
| 200 |
|
| 201 |
UniquePtr<JSErrorNotes::Note> js::CopyErrorNote(JSContext* cx, |
| 202 |
JSErrorNotes::Note* note) { |
| 203 |
return CopyErrorHelper(cx, note); |
| 204 |
} |
| 205 |
|
| 206 |
UniquePtr<JSErrorReport> js::CopyErrorReport(JSContext* cx, |
| 207 |
JSErrorReport* report) { |
| 208 |
return CopyErrorHelper(cx, report); |
| 209 |
} |
| 210 |
|
| 211 |
struct SuppressErrorsGuard { |
| 212 |
JSContext* cx; |
| 213 |
JS::WarningReporter prevReporter; |
| 214 |
JS::AutoSaveExceptionState prevState; |
| 215 |
|
| 216 |
explicit SuppressErrorsGuard(JSContext* cx) |
| 217 |
: cx(cx), |
| 218 |
prevReporter(JS::SetWarningReporter(cx, nullptr)), |
| 219 |
prevState(cx) {} |
| 220 |
|
| 221 |
~SuppressErrorsGuard() { JS::SetWarningReporter(cx, prevReporter); } |
| 222 |
}; |
| 223 |
|
| 224 |
bool js::CaptureStack(JSContext* cx, MutableHandleObject stack) { |
| 225 |
return CaptureCurrentStack( |
| 226 |
cx, stack, JS::StackCapture(JS::MaxFrames(MAX_REPORTED_STACK_DEPTH))); |
| 227 |
} |
| 228 |
|
| 229 |
JSString* js::ComputeStackString(JSContext* cx) { |
| 230 |
SuppressErrorsGuard seg(cx); |
| 231 |
|
| 232 |
RootedObject stack(cx); |
| 233 |
if (!CaptureStack(cx, &stack)) { |
| 234 |
return nullptr; |
| 235 |
} |
| 236 |
|
| 237 |
RootedString str(cx); |
| 238 |
if (!BuildStackString(cx, cx->realm()->principals(), stack, &str)) { |
| 239 |
return nullptr; |
| 240 |
} |
| 241 |
|
| 242 |
return str.get(); |
| 243 |
} |
| 244 |
|
| 245 |
JSErrorReport* js::ErrorFromException(JSContext* cx, HandleObject objArg) { |
| 246 |
// It's ok to UncheckedUnwrap here, since all we do is get the |
| 247 |
// JSErrorReport, and consumers are careful with the information they get |
| 248 |
// from that anyway. Anyone doing things that would expose anything in the |
| 249 |
// JSErrorReport to page script either does a security check on the |
| 250 |
// JSErrorReport's principal or also tries to do toString on our object and |
| 251 |
// will fail if they can't unwrap it. |
| 252 |
RootedObject obj(cx, UncheckedUnwrap(objArg)); |
| 253 |
if (!obj->is<ErrorObject>()) { |
| 254 |
return nullptr; |
| 255 |
} |
| 256 |
|
| 257 |
JSErrorReport* report = obj->as<ErrorObject>().getOrCreateErrorReport(cx); |
| 258 |
if (!report) { |
| 259 |
MOZ_ASSERT(cx->isThrowingOutOfMemory()); |
| 260 |
cx->recoverFromOutOfMemory(); |
| 261 |
} |
| 262 |
|
| 263 |
return report; |
| 264 |
} |
| 265 |
|
| 266 |
JS_PUBLIC_API JSObject* JS::ExceptionStackOrNull(HandleObject objArg) { |
| 267 |
ErrorObject* errorObject = objArg->maybeUnwrapIf<ErrorObject>(); |
| 268 |
if (errorObject) { |
| 269 |
return errorObject->stack(); |
| 270 |
} |
| 271 |
|
| 272 |
WasmExceptionObject* wasmObject = |
| 273 |
objArg->maybeUnwrapIf<WasmExceptionObject>(); |
| 274 |
if (wasmObject) { |
| 275 |
return wasmObject->stack(); |
| 276 |
} |
| 277 |
|
| 278 |
return nullptr; |
| 279 |
} |
| 280 |
|
| 281 |
JS_PUBLIC_API JSLinearString* js::GetErrorTypeName(JSContext* cx, |
| 282 |
int16_t exnType) { |
| 283 |
/* |
| 284 |
* JSEXN_INTERNALERR returns null to prevent that "InternalError: " |
| 285 |
* is prepended before "uncaught exception: " |
| 286 |
*/ |
| 287 |
if (exnType < 0 || exnType >= JSEXN_LIMIT || exnType == JSEXN_INTERNALERR || |
| 288 |
exnType == JSEXN_WARN || exnType == JSEXN_NOTE) { |
| 289 |
return nullptr; |
| 290 |
} |
| 291 |
JSProtoKey key = GetExceptionProtoKey(JSExnType(exnType)); |
| 292 |
return ClassName(key, cx); |
| 293 |
} |
| 294 |
|
| 295 |
bool js::ErrorToException(JSContext* cx, JSErrorReport* reportp, |
| 296 |
JSErrorCallback callback, void* userRef) { |
| 297 |
MOZ_ASSERT(!reportp->isWarning()); |
| 298 |
|
| 299 |
// Find the exception index associated with this error. |
| 300 |
JSErrNum errorNumber = static_cast<JSErrNum>(reportp->errorNumber); |
| 301 |
if (!callback) { |
| 302 |
callback = GetErrorMessage; |
| 303 |
} |
| 304 |
const JSErrorFormatString* errorString = callback(userRef, errorNumber); |
| 305 |
JSExnType exnType = |
| 306 |
errorString ? static_cast<JSExnType>(errorString->exnType) : JSEXN_ERR; |
| 307 |
MOZ_ASSERT(exnType < JSEXN_ERROR_LIMIT); |
| 308 |
|
| 309 |
// Prevent infinite recursion. |
| 310 |
if (cx->generatingError) { |
| 311 |
return false; |
| 312 |
} |
| 313 |
|
| 314 |
cx->generatingError = true; |
| 315 |
auto restore = mozilla::MakeScopeExit([cx] { cx->generatingError = false; }); |
| 316 |
|
| 317 |
// Create an exception object. |
| 318 |
RootedString messageStr(cx, reportp->newMessageString(cx)); |
| 319 |
if (!messageStr) { |
| 320 |
return false; |
| 321 |
} |
| 322 |
|
| 323 |
Rooted<JSString*> fileName(cx); |
| 324 |
if (const char* filename = reportp->filename.c_str()) { |
| 325 |
fileName = |
| 326 |
JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(filename, strlen(filename))); |
| 327 |
if (!fileName) { |
| 328 |
return false; |
| 329 |
} |
| 330 |
} else { |
| 331 |
fileName = cx->emptyString(); |
| 332 |
} |
| 333 |
|
| 334 |
uint32_t sourceId = reportp->sourceId; |
| 335 |
uint32_t lineNumber = reportp->lineno; |
| 336 |
JS::ColumnNumberOneOrigin columnNumber = reportp->column; |
| 337 |
|
| 338 |
// Error reports don't provide a |cause|, so we default to |Nothing| here. |
| 339 |
auto cause = JS::NothingHandleValue; |
| 340 |
|
| 341 |
RootedObject stack(cx); |
| 342 |
if (!CaptureStack(cx, &stack)) { |
| 343 |
return false; |
| 344 |
} |
| 345 |
|
| 346 |
UniquePtr<JSErrorReport> report = CopyErrorReport(cx, reportp); |
| 347 |
if (!report) { |
| 348 |
return false; |
| 349 |
} |
| 350 |
|
| 351 |
ErrorObject* errObject = |
| 352 |
ErrorObject::create(cx, exnType, stack, fileName, sourceId, lineNumber, |
| 353 |
columnNumber, std::move(report), messageStr, cause); |
| 354 |
if (!errObject) { |
| 355 |
return false; |
| 356 |
} |
| 357 |
|
| 358 |
// Throw it. |
| 359 |
RootedValue errValue(cx, ObjectValue(*errObject)); |
| 360 |
Rooted<SavedFrame*> nstack(cx); |
| 361 |
if (stack) { |
| 362 |
nstack = &stack->as<SavedFrame>(); |
| 363 |
} |
| 364 |
cx->setPendingException(errValue, nstack); |
| 365 |
return true; |
| 366 |
} |
| 367 |
|
| 368 |
using SniffingBehavior = JS::ErrorReportBuilder::SniffingBehavior; |
| 369 |
|
| 370 |
static bool IsDuckTypedErrorObject(JSContext* cx, HandleObject exnObject, |
| 371 |
const char** filename_strp) { |
| 372 |
/* |
| 373 |
* This function is called from ErrorReport::init and so should not generate |
| 374 |
* any new exceptions. |
| 375 |
*/ |
| 376 |
AutoClearPendingException acpe(cx); |
| 377 |
|
| 378 |
bool found; |
| 379 |
if (!JS_HasProperty(cx, exnObject, "message", &found) || !found) { |
| 380 |
return false; |
| 381 |
} |
| 382 |
|
| 383 |
// First try "filename". |
| 384 |
const char* filename_str = *filename_strp; |
| 385 |
if (!JS_HasProperty(cx, exnObject, filename_str, &found)) { |
| 386 |
return false; |
| 387 |
} |
| 388 |
if (!found) { |
| 389 |
// If that doesn't work, try "fileName". |
| 390 |
filename_str = "fileName"; |
| 391 |
if (!JS_HasProperty(cx, exnObject, filename_str, &found) || !found) { |
| 392 |
return false; |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
if (!JS_HasProperty(cx, exnObject, "lineNumber", &found) || !found) { |
| 397 |
return false; |
| 398 |
} |
| 399 |
|
| 400 |
*filename_strp = filename_str; |
| 401 |
return true; |
| 402 |
} |
| 403 |
|
| 404 |
static bool GetPropertyNoException(JSContext* cx, HandleObject obj, |
| 405 |
SniffingBehavior behavior, |
| 406 |
Handle<PropertyName*> name, |
| 407 |
MutableHandleValue vp) { |
| 408 |
// This function has no side-effects so always use it. |
| 409 |
if (GetPropertyPure(cx, obj, NameToId(name), vp.address())) { |
| 410 |
return true; |
| 411 |
} |
| 412 |
|
| 413 |
if (behavior == SniffingBehavior::WithSideEffects) { |
| 414 |
AutoClearPendingException acpe(cx); |
| 415 |
return GetProperty(cx, obj, obj, name, vp); |
| 416 |
} |
| 417 |
|
| 418 |
return false; |
| 419 |
} |
| 420 |
|
| 421 |
// Create a new error message similar to what Error.prototype.toString would |
| 422 |
// produce when called on an object with those property values for name and |
| 423 |
// message. |
| 424 |
static JSString* FormatErrorMessage(JSContext* cx, HandleString name, |
| 425 |
HandleString message) { |
| 426 |
if (name && message) { |
| 427 |
AutoClearPendingException acpe(cx); |
| 428 |
JSStringBuilder sb(cx); |
| 429 |
|
| 430 |
// Prefix the message with the error type, if it exists. |
| 431 |
if (!sb.append(name) || !sb.append(": ") || !sb.append(message)) { |
| 432 |
return nullptr; |
| 433 |
} |
| 434 |
|
| 435 |
return sb.finishString(); |
| 436 |
} |
| 437 |
|
| 438 |
return name ? name : message; |
| 439 |
} |
| 440 |
|
| 441 |
static JSString* ErrorReportToString(JSContext* cx, HandleObject exn, |
| 442 |
JSErrorReport* reportp, |
| 443 |
SniffingBehavior behavior) { |
| 444 |
// The error object might have custom `name` overwriting the exnType in the |
| 445 |
// error report. Try getting that property and use the exnType as a fallback. |
| 446 |
RootedString name(cx); |
| 447 |
RootedValue nameV(cx); |
| 448 |
if (GetPropertyNoException(cx, exn, behavior, cx->names().name, &nameV) && |
| 449 |
nameV.isString()) { |
| 450 |
name = nameV.toString(); |
| 451 |
} |
| 452 |
|
| 453 |
// We do NOT want to use GetErrorTypeName() here because it will not do the |
| 454 |
// "right thing" for JSEXN_INTERNALERR. That is, the caller of this API |
| 455 |
// expects that "InternalError: " will be prepended but GetErrorTypeName |
| 456 |
// goes out of its way to avoid this. |
| 457 |
if (!name) { |
| 458 |
JSExnType type = static_cast<JSExnType>(reportp->exnType); |
| 459 |
if (type != JSEXN_WARN && type != JSEXN_NOTE) { |
| 460 |
name = ClassName(GetExceptionProtoKey(type), cx); |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
RootedString message(cx); |
| 465 |
RootedValue messageV(cx); |
| 466 |
if (GetPropertyNoException(cx, exn, behavior, cx->names().message, |
| 467 |
&messageV) && |
| 468 |
messageV.isString()) { |
| 469 |
message = messageV.toString(); |
| 470 |
} |
| 471 |
|
| 472 |
if (!message) { |
| 473 |
message = reportp->newMessageString(cx); |
| 474 |
if (!message) { |
| 475 |
return nullptr; |
| 476 |
} |
| 477 |
} |
| 478 |
|
| 479 |
return FormatErrorMessage(cx, name, message); |
| 480 |
} |
| 481 |
|
| 482 |
JS::ErrorReportBuilder::ErrorReportBuilder(JSContext* cx) |
| 483 |
: reportp(nullptr), exnObject(cx) {} |
| 484 |
|
| 485 |
JS::ErrorReportBuilder::~ErrorReportBuilder() = default; |
| 486 |
|
| 487 |
bool JS::ErrorReportBuilder::init(JSContext* cx, |
| 488 |
const JS::ExceptionStack& exnStack, |
| 489 |
SniffingBehavior sniffingBehavior) { |
| 490 |
MOZ_ASSERT(!cx->isExceptionPending()); |
| 491 |
MOZ_ASSERT(!reportp); |
| 492 |
|
| 493 |
if (exnStack.exception().isObject()) { |
| 494 |
// Because ToString below could error and an exception object could become |
| 495 |
// unrooted, we must root our exception object, if any. |
| 496 |
exnObject = &exnStack.exception().toObject(); |
| 497 |
reportp = ErrorFromException(cx, exnObject); |
| 498 |
|
| 499 |
if (reportp && reportp->isMuted) { |
| 500 |
sniffingBehavior = SniffingBehavior::NoSideEffects; |
| 501 |
} |
| 502 |
} |
| 503 |
|
| 504 |
// Be careful not to invoke ToString if we've already successfully extracted |
| 505 |
// an error report, since the exception might be wrapped in a security |
| 506 |
// wrapper, and ToString-ing it might throw. |
| 507 |
RootedString str(cx); |
| 508 |
if (reportp) { |
| 509 |
str = ErrorReportToString(cx, exnObject, reportp, sniffingBehavior); |
| 510 |
} else if (exnStack.exception().isSymbol()) { |
| 511 |
RootedValue strVal(cx); |
| 512 |
if (js::SymbolDescriptiveString(cx, exnStack.exception().toSymbol(), |
| 513 |
&strVal)) { |
| 514 |
str = strVal.toString(); |
| 515 |
} else { |
| 516 |
str = nullptr; |
| 517 |
} |
| 518 |
} else if (exnObject && sniffingBehavior == NoSideEffects) { |
| 519 |
str = cx->names().Object; |
| 520 |
} else { |
| 521 |
str = js::ToString<CanGC>(cx, exnStack.exception()); |
| 522 |
} |
| 523 |
|
| 524 |
if (!str) { |
| 525 |
cx->clearPendingException(); |
| 526 |
} |
| 527 |
|
| 528 |
// If ErrorFromException didn't get us a JSErrorReport, then the object |
| 529 |
// was not an ErrorObject, security-wrapped or otherwise. However, it might |
| 530 |
// still quack like one. Give duck-typing a chance. We start by looking for |
| 531 |
// "filename" (all lowercase), since that's where DOMExceptions store their |
| 532 |
// filename. Then we check "fileName", which is where Errors store it. We |
| 533 |
// have to do it in that order, because DOMExceptions have Error.prototype |
| 534 |
// on their proto chain, and hence also have a "fileName" property, but its |
| 535 |
// value is "". |
| 536 |
const char* filename_str = "filename"; |
| 537 |
if (!reportp && exnObject && sniffingBehavior == WithSideEffects && |
| 538 |
IsDuckTypedErrorObject(cx, exnObject, &filename_str)) { |
| 539 |
// Temporary value for pulling properties off of duck-typed objects. |
| 540 |
RootedValue val(cx); |
| 541 |
|
| 542 |
RootedString name(cx); |
| 543 |
if (JS_GetProperty(cx, exnObject, "name", &val) && val.isString()) { |
| 544 |
name = val.toString(); |
| 545 |
} else { |
| 546 |
cx->clearPendingException(); |
| 547 |
} |
| 548 |
|
| 549 |
RootedString msg(cx); |
| 550 |
if (JS_GetProperty(cx, exnObject, "message", &val) && val.isString()) { |
| 551 |
msg = val.toString(); |
| 552 |
} else { |
| 553 |
cx->clearPendingException(); |
| 554 |
} |
| 555 |
|
| 556 |
// If we have the right fields, override the ToString we performed on |
| 557 |
// the exception object above with something built out of its quacks |
| 558 |
// (i.e. as much of |NameQuack: MessageQuack| as we can make). |
| 559 |
str = FormatErrorMessage(cx, name, msg); |
| 560 |
|
| 561 |
{ |
| 562 |
AutoClearPendingException acpe(cx); |
| 563 |
if (JS_GetProperty(cx, exnObject, filename_str, &val)) { |
| 564 |
RootedString tmp(cx, js::ToString<CanGC>(cx, val)); |
| 565 |
if (tmp) { |
| 566 |
filename = JS_EncodeStringToUTF8(cx, tmp); |
| 567 |
} |
| 568 |
} |
| 569 |
} |
| 570 |
if (!filename) { |
| 571 |
filename = DuplicateString(""); |
| 572 |
if (!filename) { |
| 573 |
ReportOutOfMemory(cx); |
| 574 |
return false; |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
uint32_t lineno; |
| 579 |
if (!JS_GetProperty(cx, exnObject, "lineNumber", &val) || |
| 580 |
!ToUint32(cx, val, &lineno)) { |
| 581 |
cx->clearPendingException(); |
| 582 |
lineno = 0; |
| 583 |
} |
| 584 |
|
| 585 |
uint32_t column; |
| 586 |
if (!JS_GetProperty(cx, exnObject, "columnNumber", &val) || |
| 587 |
!ToUint32(cx, val, &column)) { |
| 588 |
cx->clearPendingException(); |
| 589 |
column = 0; |
| 590 |
} |
| 591 |
|
| 592 |
reportp = &ownedReport; |
| 593 |
new (reportp) JSErrorReport(); |
| 594 |
ownedReport.filename = JS::ConstUTF8CharsZ(filename.get()); |
| 595 |
ownedReport.lineno = lineno; |
| 596 |
ownedReport.exnType = JSEXN_INTERNALERR; |
| 597 |
ownedReport.column = JS::ColumnNumberOneOrigin(column); |
| 598 |
|
| 599 |
if (str) { |
| 600 |
// Note that using |str| for |message_| here is kind of wrong, |
| 601 |
// because |str| is supposed to be of the format |
| 602 |
// |ErrorName: ErrorMessage|, and |message_| is supposed to |
| 603 |
// correspond to |ErrorMessage|. But this is what we've |
| 604 |
// historically done for duck-typed error objects. |
| 605 |
// |
| 606 |
// If only this stuff could get specced one day... |
| 607 |
if (auto utf8 = JS_EncodeStringToUTF8(cx, str)) { |
| 608 |
ownedReport.initOwnedMessage(utf8.release()); |
| 609 |
} else { |
| 610 |
cx->clearPendingException(); |
| 611 |
str = nullptr; |
| 612 |
} |
| 613 |
} |
| 614 |
} |
| 615 |
|
| 616 |
const char* utf8Message = nullptr; |
| 617 |
if (str) { |
| 618 |
toStringResultBytesStorage = JS_EncodeStringToUTF8(cx, str); |
| 619 |
utf8Message = toStringResultBytesStorage.get(); |
| 620 |
if (!utf8Message) { |
| 621 |
cx->clearPendingException(); |
| 622 |
} |
| 623 |
} |
| 624 |
if (!utf8Message) { |
| 625 |
utf8Message = "unknown (can't convert to string)"; |
| 626 |
} |
| 627 |
|
| 628 |
if (!reportp) { |
| 629 |
// This is basically an inlined version of |
| 630 |
// |
| 631 |
// JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, |
| 632 |
// JSMSG_UNCAUGHT_EXCEPTION, utf8Message); |
| 633 |
// |
| 634 |
// but without the reporting bits. Instead it just puts all |
| 635 |
// the stuff we care about in our ownedReport and message_. |
| 636 |
if (!populateUncaughtExceptionReportUTF8(cx, exnStack.stack(), |
| 637 |
utf8Message)) { |
| 638 |
// Just give up. We're out of memory or something; not much we can |
| 639 |
// do here. |
| 640 |
return false; |
| 641 |
} |
| 642 |
} else { |
| 643 |
toStringResult_ = JS::ConstUTF8CharsZ(utf8Message, strlen(utf8Message)); |
| 644 |
} |
| 645 |
|
| 646 |
return true; |
| 647 |
} |
| 648 |
|
| 649 |
bool JS::ErrorReportBuilder::populateUncaughtExceptionReportUTF8( |
| 650 |
JSContext* cx, HandleObject stack, ...) { |
| 651 |
va_list ap; |
| 652 |
va_start(ap, stack); |
| 653 |
bool ok = populateUncaughtExceptionReportUTF8VA(cx, stack, ap); |
| 654 |
va_end(ap); |
| 655 |
return ok; |
| 656 |
} |
| 657 |
|
| 658 |
bool JS::ErrorReportBuilder::populateUncaughtExceptionReportUTF8VA( |
| 659 |
JSContext* cx, HandleObject stack, va_list ap) { |
| 660 |
new (&ownedReport) JSErrorReport(); |
| 661 |
ownedReport.isWarning_ = false; |
| 662 |
ownedReport.errorNumber = JSMSG_UNCAUGHT_EXCEPTION; |
| 663 |
|
| 664 |
bool skippedAsync; |
| 665 |
Rooted<SavedFrame*> frame( |
| 666 |
cx, UnwrapSavedFrame(cx, cx->realm()->principals(), stack, |
| 667 |
SavedFrameSelfHosted::Exclude, skippedAsync)); |
| 668 |
if (frame) { |
| 669 |
filename = StringToNewUTF8CharsZ(cx, *frame->getSource()); |
| 670 |
if (!filename) { |
| 671 |
return false; |
| 672 |
} |
| 673 |
|
| 674 |
// |ownedReport.filename| inherits the lifetime of |ErrorReport::filename|. |
| 675 |
ownedReport.filename = JS::ConstUTF8CharsZ(filename.get()); |
| 676 |
ownedReport.sourceId = frame->getSourceId(); |
| 677 |
ownedReport.lineno = frame->getLine(); |
| 678 |
ownedReport.column = |
| 679 |
JS::ColumnNumberOneOrigin(frame->getColumn().oneOriginValue()); |
| 680 |
ownedReport.isMuted = frame->getMutedErrors(); |
| 681 |
} else { |
| 682 |
// XXXbz this assumes the stack we have right now is still |
| 683 |
// related to our exception object. |
| 684 |
NonBuiltinFrameIter iter(cx, cx->realm()->principals()); |
| 685 |
if (!iter.done()) { |
| 686 |
ownedReport.filename = JS::ConstUTF8CharsZ(iter.filename()); |
| 687 |
JS::TaggedColumnNumberOneOrigin column; |
| 688 |
ownedReport.sourceId = |
| 689 |
iter.hasScript() ? iter.script()->scriptSource()->id() : 0; |
| 690 |
ownedReport.lineno = iter.computeLine(&column); |
| 691 |
ownedReport.column = JS::ColumnNumberOneOrigin(column.oneOriginValue()); |
| 692 |
ownedReport.isMuted = iter.mutedErrors(); |
| 693 |
} |
| 694 |
} |
| 695 |
|
| 696 |
AutoReportFrontendContext fc(cx); |
| 697 |
if (!ExpandErrorArgumentsVA(&fc, GetErrorMessage, nullptr, |
| 698 |
JSMSG_UNCAUGHT_EXCEPTION, ArgumentsAreUTF8, |
| 699 |
&ownedReport, ap)) { |
| 700 |
return false; |
| 701 |
} |
| 702 |
|
| 703 |
toStringResult_ = ownedReport.message(); |
| 704 |
reportp = &ownedReport; |
| 705 |
return true; |
| 706 |
} |
| 707 |
|
| 708 |
JSObject* js::CopyErrorObject(JSContext* cx, Handle<ErrorObject*> err) { |
| 709 |
UniquePtr<JSErrorReport> copyReport; |
| 710 |
if (JSErrorReport* errorReport = err->getErrorReport()) { |
| 711 |
copyReport = CopyErrorReport(cx, errorReport); |
| 712 |
if (!copyReport) { |
| 713 |
return nullptr; |
| 714 |
} |
| 715 |
} |
| 716 |
|
| 717 |
RootedString message(cx, err->getMessage()); |
| 718 |
if (message && !cx->compartment()->wrap(cx, &message)) { |
| 719 |
return nullptr; |
| 720 |
} |
| 721 |
RootedString fileName(cx, err->fileName(cx)); |
| 722 |
if (!cx->compartment()->wrap(cx, &fileName)) { |
| 723 |
return nullptr; |
| 724 |
} |
| 725 |
RootedObject stack(cx, err->stack()); |
| 726 |
if (!cx->compartment()->wrap(cx, &stack)) { |
| 727 |
return nullptr; |
| 728 |
} |
| 729 |
if (stack && JS_IsDeadWrapper(stack)) { |
| 730 |
// ErrorObject::create expects |stack| to be either nullptr or a (possibly |
| 731 |
// wrapped) SavedFrame instance. |
| 732 |
stack = nullptr; |
| 733 |
} |
| 734 |
Rooted<mozilla::Maybe<Value>> cause(cx, mozilla::Nothing()); |
| 735 |
if (auto maybeCause = err->getCause()) { |
| 736 |
RootedValue errorCause(cx, maybeCause.value()); |
| 737 |
if (!cx->compartment()->wrap(cx, &errorCause)) { |
| 738 |
return nullptr; |
| 739 |
} |
| 740 |
cause = mozilla::Some(errorCause.get()); |
| 741 |
} |
| 742 |
uint32_t sourceId = err->sourceId(); |
| 743 |
uint32_t lineNumber = err->lineNumber(); |
| 744 |
JS::ColumnNumberOneOrigin columnNumber = err->columnNumber(); |
| 745 |
JSExnType errorType = err->type(); |
| 746 |
|
| 747 |
// Create the Error object. |
| 748 |
return ErrorObject::create(cx, errorType, stack, fileName, sourceId, |
| 749 |
lineNumber, columnNumber, std::move(copyReport), |
| 750 |
message, cause); |
| 751 |
} |
| 752 |
|
| 753 |
JS_PUBLIC_API bool JS::CreateError(JSContext* cx, JSExnType type, |
| 754 |
HandleObject stack, HandleString fileName, |
| 755 |
uint32_t lineNumber, |
| 756 |
JS::ColumnNumberOneOrigin columnNumber, |
| 757 |
JSErrorReport* report, HandleString message, |
| 758 |
Handle<mozilla::Maybe<Value>> cause, |
| 759 |
MutableHandleValue rval) { |
| 760 |
cx->check(stack, fileName, message); |
| 761 |
AssertObjectIsSavedFrameOrWrapper(cx, stack); |
| 762 |
|
| 763 |
js::UniquePtr<JSErrorReport> rep; |
| 764 |
if (report) { |
| 765 |
rep = CopyErrorReport(cx, report); |
| 766 |
if (!rep) { |
| 767 |
return false; |
| 768 |
} |
| 769 |
} |
| 770 |
|
| 771 |
JSObject* obj = |
| 772 |
js::ErrorObject::create(cx, type, stack, fileName, 0, lineNumber, |
| 773 |
columnNumber, std::move(rep), message, cause); |
| 774 |
if (!obj) { |
| 775 |
return false; |
| 776 |
} |
| 777 |
|
| 778 |
rval.setObject(*obj); |
| 779 |
return true; |
| 780 |
} |
| 781 |
|
| 782 |
const char* js::ValueToSourceForError(JSContext* cx, HandleValue val, |
| 783 |
UniqueChars& bytes) { |
| 784 |
if (val.isUndefined()) { |
| 785 |
return "undefined"; |
| 786 |
} |
| 787 |
|
| 788 |
if (val.isNull()) { |
| 789 |
return "null"; |
| 790 |
} |
| 791 |
|
| 792 |
AutoClearPendingException acpe(cx); |
| 793 |
|
| 794 |
// This function must always return a non-null string. If the conversion to |
| 795 |
// string fails due to OOM, we return this string instead. |
| 796 |
static constexpr char ErrorConvertingToStringMsg[] = |
| 797 |
"<<error converting value to string>>"; |
| 798 |
|
| 799 |
RootedString str(cx, JS_ValueToSource(cx, val)); |
| 800 |
if (!str) { |
| 801 |
return ErrorConvertingToStringMsg; |
| 802 |
} |
| 803 |
|
| 804 |
JSStringBuilder sb(cx); |
| 805 |
if (val.isObject()) { |
| 806 |
RootedObject valObj(cx, &val.toObject()); |
| 807 |
ESClass cls; |
| 808 |
if (!JS::GetBuiltinClass(cx, valObj, &cls)) { |
| 809 |
return "<<error determining class of value>>"; |
| 810 |
} |
| 811 |
const char* s; |
| 812 |
if (cls == ESClass::Array) { |
| 813 |
s = "the array "; |
| 814 |
} else if (cls == ESClass::ArrayBuffer) { |
| 815 |
s = "the array buffer "; |
| 816 |
} else if (JS_IsArrayBufferViewObject(valObj)) { |
| 817 |
s = "the typed array "; |
| 818 |
} else { |
| 819 |
s = "the object "; |
| 820 |
} |
| 821 |
if (!sb.append(s, strlen(s))) { |
| 822 |
return ErrorConvertingToStringMsg; |
| 823 |
} |
| 824 |
} else if (val.isNumber()) { |
| 825 |
if (!sb.append("the number ")) { |
| 826 |
return ErrorConvertingToStringMsg; |
| 827 |
} |
| 828 |
} else if (val.isString()) { |
| 829 |
if (!sb.append("the string ")) { |
| 830 |
return ErrorConvertingToStringMsg; |
| 831 |
} |
| 832 |
} else if (val.isBigInt()) { |
| 833 |
if (!sb.append("the BigInt ")) { |
| 834 |
return ErrorConvertingToStringMsg; |
| 835 |
} |
| 836 |
} else { |
| 837 |
MOZ_ASSERT(val.isBoolean() || val.isSymbol()); |
| 838 |
bytes = StringToNewUTF8CharsZ(cx, *str); |
| 839 |
if (!bytes) { |
| 840 |
return ErrorConvertingToStringMsg; |
| 841 |
} |
| 842 |
return bytes.get(); |
| 843 |
} |
| 844 |
if (!sb.append(str)) { |
| 845 |
return ErrorConvertingToStringMsg; |
| 846 |
} |
| 847 |
str = sb.finishString(); |
| 848 |
if (!str) { |
| 849 |
return ErrorConvertingToStringMsg; |
| 850 |
} |
| 851 |
bytes = StringToNewUTF8CharsZ(cx, *str); |
| 852 |
if (!bytes) { |
| 853 |
return ErrorConvertingToStringMsg; |
| 854 |
} |
| 855 |
return bytes.get(); |
| 856 |
} |
| 857 |
|
| 858 |
bool js::GetInternalError(JSContext* cx, unsigned errorNumber, |
| 859 |
MutableHandleValue error) { |
| 860 |
FixedInvokeArgs<1> args(cx); |
| 861 |
args[0].set(Int32Value(errorNumber)); |
| 862 |
return CallSelfHostedFunction(cx, cx->names().GetInternalError, |
| 863 |
NullHandleValue, args, error); |
| 864 |
} |
| 865 |
|
| 866 |
bool js::GetTypeError(JSContext* cx, unsigned errorNumber, |
| 867 |
MutableHandleValue error) { |
| 868 |
FixedInvokeArgs<1> args(cx); |
| 869 |
args[0].set(Int32Value(errorNumber)); |
| 870 |
return CallSelfHostedFunction(cx, cx->names().GetTypeError, NullHandleValue, |
| 871 |
args, error); |
| 872 |
} |
| 873 |
|
| 874 |
bool js::GetAggregateError(JSContext* cx, unsigned errorNumber, |
| 875 |
MutableHandleValue error) { |
| 876 |
FixedInvokeArgs<1> args(cx); |
| 877 |
args[0].set(Int32Value(errorNumber)); |
| 878 |
return CallSelfHostedFunction(cx, cx->names().GetAggregateError, |
| 879 |
NullHandleValue, args, error); |
| 880 |
} |
| 881 |
|
| 882 |
JS_PUBLIC_API mozilla::Maybe<Value> JS::GetExceptionCause(JSObject* exc) { |
| 883 |
if (!exc->is<ErrorObject>()) { |
| 884 |
return mozilla::Nothing(); |
| 885 |
} |
| 886 |
auto& error = exc->as<ErrorObject>(); |
| 887 |
return error.getCause(); |
| 888 |
} |