-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Expand file tree
/
Copy pathFormatStackTraceForJS.cpp
More file actions
756 lines (612 loc) · 30.3 KB
/
FormatStackTraceForJS.cpp
File metadata and controls
756 lines (612 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
#include "root.h"
#include "FormatStackTraceForJS.h"
#include "ZigGlobalObject.h"
#include "helpers.h"
#include "JavaScriptCore/ArgList.h"
#include "JavaScriptCore/CallData.h"
#include "JavaScriptCore/TopExceptionScope.h"
#include "JavaScriptCore/Error.h"
#include "JavaScriptCore/ErrorInstance.h"
#include "JavaScriptCore/ExceptionScope.h"
#include "JavaScriptCore/Identifier.h"
#include "JavaScriptCore/JSArray.h"
#include "JavaScriptCore/JSCast.h"
#include "JavaScriptCore/JSCJSValue.h"
#include "JavaScriptCore/JSObject.h"
#include "JavaScriptCore/JSString.h"
#include "JavaScriptCore/StackFrame.h"
#include "JavaScriptCore/VM.h"
#include "BunClientData.h"
#include "CallSite.h"
#include "ErrorStackTrace.h"
#include "headers-handwritten.h"
using namespace JSC;
using namespace WebCore;
namespace Bun {
static JSValue formatStackTraceToJSValue(JSC::VM& vm, Zig::GlobalObject* globalObject, JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSObject* errorObject, JSC::JSArray* callSites)
{
auto scope = DECLARE_THROW_SCOPE(vm);
// default formatting
size_t framesCount = callSites->length();
WTF::StringBuilder sb;
auto errorMessage = errorObject->getIfPropertyExists(lexicalGlobalObject, vm.propertyNames->message);
RETURN_IF_EXCEPTION(scope, {});
if (errorMessage) {
auto* str = errorMessage.toString(lexicalGlobalObject);
RETURN_IF_EXCEPTION(scope, {});
if (str->length() > 0) {
auto value = str->view(lexicalGlobalObject);
RETURN_IF_EXCEPTION(scope, {});
sb.append("Error: "_s);
sb.append(value.data);
} else {
sb.append("Error"_s);
}
} else {
sb.append("Error"_s);
}
for (size_t i = 0; i < framesCount; i++) {
sb.append("\n at "_s);
JSC::JSValue callSiteValue = callSites->getIndex(lexicalGlobalObject, i);
RETURN_IF_EXCEPTION(scope, {});
if (CallSite* callSite = JSC::jsDynamicCast<CallSite*>(callSiteValue)) {
callSite->formatAsString(vm, lexicalGlobalObject, sb);
RETURN_IF_EXCEPTION(scope, {});
} else {
// This matches Node.js / V8's behavior
// It can become "at [object Object]" if the object is not a CallSite
auto* str = callSiteValue.toString(lexicalGlobalObject);
RETURN_IF_EXCEPTION(scope, {});
auto value = str->value(lexicalGlobalObject);
RETURN_IF_EXCEPTION(scope, {});
sb.append(value.data);
}
}
return jsString(vm, sb.toString());
}
static JSValue formatStackTraceToJSValue(JSC::VM& vm, Zig::GlobalObject* globalObject, JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSObject* errorObject, JSC::JSArray* callSites, JSValue prepareStackTrace)
{
auto scope = DECLARE_THROW_SCOPE(vm);
auto stackStringValue = formatStackTraceToJSValue(vm, globalObject, lexicalGlobalObject, errorObject, callSites);
RETURN_IF_EXCEPTION(scope, {});
if (prepareStackTrace && prepareStackTrace.isObject()) {
JSC::CallData prepareStackTraceCallData = JSC::getCallData(prepareStackTrace);
if (prepareStackTraceCallData.type != JSC::CallData::Type::None) {
// In Node, if you console.log(error.stack) inside Error.prepareStackTrace
// it will display the stack as a formatted string, so we have to do the same.
errorObject->putDirect(vm, vm.propertyNames->stack, stackStringValue, 0);
JSC::MarkedArgumentBuffer arguments;
arguments.append(errorObject);
arguments.append(callSites);
JSC::JSValue result = profiledCall(
lexicalGlobalObject,
JSC::ProfilingReason::Other,
prepareStackTrace,
prepareStackTraceCallData,
lexicalGlobalObject->m_errorStructure.constructor(globalObject),
arguments);
RETURN_IF_EXCEPTION(scope, stackStringValue);
if (result.isUndefinedOrNull()) {
result = jsUndefined();
}
return result;
}
}
return stackStringValue;
}
static JSValue formatStackTraceToJSValueWithoutPrepareStackTrace(JSC::VM& vm, Zig::GlobalObject* globalObject, JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSObject* errorObject, JSC::JSArray* callSites)
{
JSValue prepareStackTrace = {};
if (lexicalGlobalObject->inherits<Zig::GlobalObject>()) {
if (auto prepare = globalObject->m_errorConstructorPrepareStackTraceValue.get()) {
prepareStackTrace = prepare;
}
} else {
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
auto* errorConstructor = lexicalGlobalObject->m_errorStructure.constructor(globalObject);
prepareStackTrace = errorConstructor->getIfPropertyExists(lexicalGlobalObject, JSC::Identifier::fromString(vm, "prepareStackTrace"_s));
CLEAR_IF_EXCEPTION(scope);
}
return formatStackTraceToJSValue(vm, globalObject, lexicalGlobalObject, errorObject, callSites, prepareStackTrace);
}
WTF::String formatStackTrace(
JSC::VM& vm,
Zig::GlobalObject* globalObject,
JSC::JSGlobalObject* lexicalGlobalObject,
const WTF::String& name,
const WTF::String& message,
OrdinalNumber& line,
OrdinalNumber& column,
WTF::String& sourceURL,
Vector<JSC::StackFrame>& stackTrace,
JSC::JSObject* errorInstance)
{
WTF::StringBuilder sb;
if (!name.isEmpty()) {
sb.append(name);
if (!message.isEmpty()) {
sb.append(": "_s);
sb.append(message);
}
} else if (!message.isEmpty()) {
sb.append(message);
}
// FIXME: why can size == 6 and capacity == 0?
// https://discord.com/channels/876711213126520882/1174901590457585765/1174907969419350036
size_t framesCount = stackTrace.size();
bool hasSet = false;
void* bunVM = nullptr;
const auto getBunVM = [&]() -> void* {
if (!bunVM) {
bunVM = clientData(vm)->bunVM;
}
return bunVM;
};
if (errorInstance) {
if (JSC::ErrorInstance* err = jsDynamicCast<JSC::ErrorInstance*>(errorInstance)) {
if (err->errorType() == ErrorType::SyntaxError && (stackTrace.isEmpty() || stackTrace.at(0).sourceURL(vm) != err->sourceURL())) {
// There appears to be an off-by-one error.
// The following reproduces the issue:
// /* empty comment */
// "".test(/[a-0]/);
auto originalLine = WTF::OrdinalNumber::fromOneBasedInt(err->line());
ZigStackFrame remappedFrame = {};
memset(&remappedFrame, 0, sizeof(ZigStackFrame));
remappedFrame.position.line_zero_based = originalLine.zeroBasedInt();
remappedFrame.position.column_zero_based = 0;
String sourceURLForFrame = err->sourceURL();
// If it's not a Zig::GlobalObject, don't bother source-mapping it.
if (globalObject && !sourceURLForFrame.isEmpty()) {
// https://github.com/oven-sh/bun/issues/3595
if (!sourceURLForFrame.isEmpty()) {
remappedFrame.source_url = Bun::toStringRef(sourceURLForFrame);
// This ensures the lifetime of the sourceURL is accounted for correctly
Bun__remapStackFramePositions(getBunVM(), &remappedFrame, 1);
sourceURLForFrame = remappedFrame.source_url.toWTFString();
}
}
// there is always a newline before each stack frame line, ensuring that the name + message
// exist on the first line, even if both are empty
sb.append("\n"_s);
sb.append(" at <parse> ("_s);
sb.append(remappedFrame.source_url.toWTFString());
if (remappedFrame.remapped) {
errorInstance->putDirect(vm, builtinNames(vm).originalLinePublicName(), jsNumber(originalLine.oneBasedInt()), PropertyAttribute::DontEnum | 0);
hasSet = true;
line = remappedFrame.position.line();
}
if (remappedFrame.remapped) {
sb.append(':');
sb.append(remappedFrame.position.line().oneBasedInt());
} else {
sb.append(':');
sb.append(originalLine.oneBasedInt());
}
sb.append(')');
}
}
}
if (framesCount == 0) {
ASSERT(stackTrace.isEmpty());
return sb.toString();
}
sb.append("\n"_s);
for (size_t i = 0; i < framesCount; i++) {
StackFrame& frame = stackTrace.at(i);
unsigned int flags = static_cast<unsigned int>(FunctionNameFlags::AddNewKeyword);
// -- get the data we need to render the text --
JSC::JSGlobalObject* globalObjectForFrame = lexicalGlobalObject;
if (frame.hasLineAndColumnInfo()) {
auto* callee = frame.callee();
if (callee) {
if (auto* object = callee->getObject()) {
globalObjectForFrame = object->globalObject();
}
}
}
WTF::String functionName = Zig::functionName(vm, globalObjectForFrame, frame, errorInstance ? Zig::FinalizerSafety::NotInFinalizer : Zig::FinalizerSafety::MustNotTriggerGC, &flags);
OrdinalNumber originalLine = {};
OrdinalNumber originalColumn = {};
OrdinalNumber displayLine = {};
OrdinalNumber displayColumn = {};
WTF::String sourceURLForFrame;
if (frame.hasLineAndColumnInfo()) {
ZigStackFrame remappedFrame = {};
LineColumn lineColumn = frame.computeLineAndColumn();
originalLine = OrdinalNumber::fromOneBasedInt(lineColumn.line);
originalColumn = OrdinalNumber::fromOneBasedInt(lineColumn.column);
displayLine = originalLine;
displayColumn = originalColumn;
remappedFrame.position.line_zero_based = originalLine.zeroBasedInt();
remappedFrame.position.column_zero_based = originalColumn.zeroBasedInt();
sourceURLForFrame = Zig::sourceURL(vm, frame);
bool isDefinitelyNotRunninginNodeVMGlobalObject = globalObject == globalObjectForFrame;
bool isDefaultGlobalObjectInAFinalizer = (globalObject && !lexicalGlobalObject && !errorInstance);
if (isDefinitelyNotRunninginNodeVMGlobalObject || isDefaultGlobalObjectInAFinalizer) {
// https://github.com/oven-sh/bun/issues/3595
if (!sourceURLForFrame.isEmpty()) {
remappedFrame.source_url = Bun::toStringRef(sourceURLForFrame);
// This ensures the lifetime of the sourceURL is accounted for correctly
Bun__remapStackFramePositions(getBunVM(), &remappedFrame, 1);
sourceURLForFrame = remappedFrame.source_url.toWTFString();
}
}
displayLine = remappedFrame.position.line();
displayColumn = remappedFrame.position.column();
if (!hasSet) {
hasSet = true;
line = remappedFrame.position.line();
column = remappedFrame.position.column();
sourceURL = sourceURLForFrame;
if (remappedFrame.remapped) {
if (errorInstance) {
errorInstance->putDirect(vm, builtinNames(vm).originalLinePublicName(), jsNumber(originalLine.oneBasedInt()), PropertyAttribute::DontEnum | 0);
errorInstance->putDirect(vm, builtinNames(vm).originalColumnPublicName(), jsNumber(originalColumn.oneBasedInt()), PropertyAttribute::DontEnum | 0);
}
}
}
}
if (functionName.isEmpty()) {
if (flags & (static_cast<unsigned int>(FunctionNameFlags::Eval) | static_cast<unsigned int>(FunctionNameFlags::Function))) {
functionName = "<anonymous>"_s;
}
}
if (sourceURLForFrame.isEmpty()) {
if (flags & static_cast<unsigned int>(FunctionNameFlags::Builtin)) {
sourceURLForFrame = "native"_s;
} else {
sourceURLForFrame = "unknown"_s;
}
}
// --- actually render the text ---
sb.append(" at "_s);
if (!functionName.isEmpty()) {
if (frame.isAsyncFrame()) {
sb.append("async "_s);
}
sb.append(functionName);
sb.append(" ("_s);
}
if (!sourceURLForFrame.isEmpty()) {
sb.append(sourceURLForFrame);
if (displayLine.zeroBasedInt() > 0 || displayColumn.zeroBasedInt() > 0) {
sb.append(':');
sb.append(displayLine.oneBasedInt());
if (displayColumn.zeroBasedInt() > 0) {
sb.append(':');
sb.append(displayColumn.oneBasedInt());
}
}
}
if (!functionName.isEmpty()) {
sb.append(')');
}
if (i != framesCount - 1) {
sb.append("\n"_s);
}
}
return sb.toString();
}
// error.stack calls this function
static String computeErrorInfoWithoutPrepareStackTrace(
JSC::VM& vm,
Zig::GlobalObject* globalObject,
JSC::JSGlobalObject* lexicalGlobalObject,
Vector<StackFrame>& stackTrace,
OrdinalNumber& line,
OrdinalNumber& column,
String& sourceURL,
JSObject* errorInstance)
{
auto scope = DECLARE_THROW_SCOPE(vm);
WTF::String name = "Error"_s;
WTF::String message;
if (errorInstance) {
// Note that we are not allowed to allocate memory in here. It's called inside a finalizer.
if (auto* instance = jsDynamicCast<ErrorInstance*>(errorInstance)) {
if (!lexicalGlobalObject) {
lexicalGlobalObject = errorInstance->globalObject();
}
name = instance->sanitizedNameString(lexicalGlobalObject);
RETURN_IF_EXCEPTION(scope, {});
message = instance->sanitizedMessageString(lexicalGlobalObject);
RETURN_IF_EXCEPTION(scope, {});
}
}
if (!globalObject) [[unlikely]] {
globalObject = defaultGlobalObject();
}
return Bun::formatStackTrace(vm, globalObject, lexicalGlobalObject, name, message, line, column, sourceURL, stackTrace, errorInstance);
}
static JSValue computeErrorInfoWithPrepareStackTrace(JSC::VM& vm, Zig::GlobalObject* globalObject, JSC::JSGlobalObject* lexicalGlobalObject, Vector<StackFrame>& stackFrames, OrdinalNumber& line, OrdinalNumber& column, String& sourceURL, JSObject* errorObject, JSObject* prepareStackTrace)
{
auto scope = DECLARE_THROW_SCOPE(vm);
JSCStackTrace stackTrace = JSCStackTrace::fromExisting(vm, stackFrames);
// Note: we cannot use tryCreateUninitializedRestricted here because we cannot allocate memory inside initializeIndex()
MarkedArgumentBuffer callSites;
// Create the call sites (one per frame)
Zig::createCallSitesFromFrames(globalObject, lexicalGlobalObject, stackTrace, callSites);
// We need to sourcemap it if it's a GlobalObject.
for (int i = 0; i < stackTrace.size(); i++) {
ZigStackFrame frame = {};
auto& stackFrame = stackFrames.at(i);
String sourceURLForFrame = Zig::sourceURL(vm, stackFrame);
// When you use node:vm, the global object can be different on a
// per-frame basis. We should sourcemap the frames which are in Bun's
// global object, and not sourcemap the frames which are in a different
// global object.
JSGlobalObject* globalObjectForFrame = lexicalGlobalObject;
if (stackFrame.hasLineAndColumnInfo()) {
auto* callee = stackFrame.callee();
// https://github.com/oven-sh/bun/issues/17698
if (callee) {
if (auto* object = callee->getObject()) {
globalObjectForFrame = object->globalObject();
}
}
}
if (globalObjectForFrame == globalObject) {
if (JSCStackFrame::SourcePositions* sourcePositions = stackTrace.at(i).getSourcePositions()) {
frame.position.line_zero_based = sourcePositions->line.zeroBasedInt();
frame.position.column_zero_based = sourcePositions->column.zeroBasedInt();
} else {
frame.position.line_zero_based = -1;
frame.position.column_zero_based = -1;
}
if (!sourceURLForFrame.isEmpty()) {
frame.source_url = Bun::toStringRef(sourceURLForFrame);
// This ensures the lifetime of the sourceURL is accounted for correctly
Bun__remapStackFramePositions(globalObject->bunVM(), &frame, 1);
sourceURLForFrame = frame.source_url.toWTFString();
}
}
auto* callsite = jsCast<CallSite*>(callSites.at(i));
if (!sourceURLForFrame.isEmpty())
callsite->setSourceURL(vm, jsString(vm, sourceURLForFrame));
if (frame.remapped) {
callsite->setLineNumber(frame.position.line());
callsite->setColumnNumber(frame.position.column());
}
}
JSArray* callSitesArray = JSC::constructArray(globalObject, globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), callSites);
RETURN_IF_EXCEPTION(scope, {});
RELEASE_AND_RETURN(scope, formatStackTraceToJSValue(vm, globalObject, lexicalGlobalObject, errorObject, callSitesArray, prepareStackTrace));
}
static String computeErrorInfoToString(JSC::VM& vm, Vector<StackFrame>& stackTrace, OrdinalNumber& line, OrdinalNumber& column, String& sourceURL)
{
Zig::GlobalObject* globalObject = nullptr;
JSC::JSGlobalObject* lexicalGlobalObject = nullptr;
return computeErrorInfoWithoutPrepareStackTrace(vm, globalObject, lexicalGlobalObject, stackTrace, line, column, sourceURL, nullptr);
}
static JSValue computeErrorInfoToJSValueWithoutSkipping(JSC::VM& vm, Vector<StackFrame>& stackTrace, OrdinalNumber& line, OrdinalNumber& column, String& sourceURL, JSObject* errorInstance, void* bunErrorData)
{
UNUSED_PARAM(bunErrorData);
Zig::GlobalObject* globalObject = nullptr;
JSC::JSGlobalObject* lexicalGlobalObject = nullptr;
lexicalGlobalObject = errorInstance->globalObject();
globalObject = jsDynamicCast<Zig::GlobalObject*>(lexicalGlobalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
// Error.prepareStackTrace - https://v8.dev/docs/stack-trace-api#customizing-stack-traces
if (!globalObject) {
// node:vm will use a different JSGlobalObject
globalObject = defaultGlobalObject();
if (!globalObject->isInsideErrorPrepareStackTraceCallback) {
auto* errorConstructor = lexicalGlobalObject->m_errorStructure.constructor(lexicalGlobalObject);
auto prepareStackTrace = errorConstructor->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "prepareStackTrace"_s));
RETURN_IF_EXCEPTION(scope, {});
if (prepareStackTrace) {
if (prepareStackTrace.isCell() && prepareStackTrace.isObject() && prepareStackTrace.isCallable()) {
globalObject->isInsideErrorPrepareStackTraceCallback = true;
auto result = computeErrorInfoWithPrepareStackTrace(vm, globalObject, lexicalGlobalObject, stackTrace, line, column, sourceURL, errorInstance, prepareStackTrace.getObject());
globalObject->isInsideErrorPrepareStackTraceCallback = false;
RELEASE_AND_RETURN(scope, result);
}
}
}
} else if (!globalObject->isInsideErrorPrepareStackTraceCallback) {
if (JSValue prepareStackTrace = globalObject->m_errorConstructorPrepareStackTraceValue.get()) {
if (prepareStackTrace) {
if (prepareStackTrace.isCallable()) {
globalObject->isInsideErrorPrepareStackTraceCallback = true;
auto result = computeErrorInfoWithPrepareStackTrace(vm, globalObject, lexicalGlobalObject, stackTrace, line, column, sourceURL, errorInstance, prepareStackTrace.getObject());
globalObject->isInsideErrorPrepareStackTraceCallback = false;
RELEASE_AND_RETURN(scope, result);
}
}
}
}
String result = computeErrorInfoWithoutPrepareStackTrace(vm, globalObject, lexicalGlobalObject, stackTrace, line, column, sourceURL, errorInstance);
RETURN_IF_EXCEPTION(scope, {});
return jsString(vm, result);
}
static JSValue computeErrorInfoToJSValue(JSC::VM& vm, Vector<StackFrame>& stackTrace, OrdinalNumber& line, OrdinalNumber& column, String& sourceURL, JSObject* errorInstance, void* bunErrorData)
{
return computeErrorInfoToJSValueWithoutSkipping(vm, stackTrace, line, column, sourceURL, errorInstance, bunErrorData);
}
WTF::String computeErrorInfoWrapperToString(JSC::VM& vm, Vector<StackFrame>& stackTrace, unsigned int& line_in, unsigned int& column_in, String& sourceURL, void* bunErrorData)
{
UNUSED_PARAM(bunErrorData);
OrdinalNumber line = OrdinalNumber::fromOneBasedInt(line_in);
OrdinalNumber column = OrdinalNumber::fromOneBasedInt(column_in);
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
WTF::String result = computeErrorInfoToString(vm, stackTrace, line, column, sourceURL);
if (scope.exception()) {
// TODO: is this correct? vm.setOnComputeErrorInfo doesnt appear to properly handle a function that can throw
// test/js/node/test/parallel/test-stream-writable-write-writev-finish.js is the one that trips the exception checker
(void)scope.tryClearException();
result = WTF::emptyString();
}
line_in = line.oneBasedInt();
column_in = column.oneBasedInt();
return result;
}
void computeLineColumnWithSourcemap(JSC::VM& vm, JSC::SourceProvider* _Nonnull sourceProvider, JSC::LineColumn& lineColumn)
{
auto sourceURL = sourceProvider->sourceURL();
if (sourceURL.isEmpty()) {
return;
}
OrdinalNumber line = OrdinalNumber::fromOneBasedInt(lineColumn.line);
OrdinalNumber column = OrdinalNumber::fromOneBasedInt(lineColumn.column);
ZigStackFrame frame = {};
frame.position.line_zero_based = line.zeroBasedInt();
frame.position.column_zero_based = column.zeroBasedInt();
frame.source_url = Bun::toStringRef(sourceURL);
Bun__remapStackFramePositions(Bun::vm(vm), &frame, 1);
if (frame.remapped) {
lineColumn.line = frame.position.line().oneBasedInt();
lineColumn.column = frame.position.column().oneBasedInt();
}
}
JSC::JSValue computeErrorInfoWrapperToJSValue(JSC::VM& vm, Vector<StackFrame>& stackTrace, unsigned int& line_in, unsigned int& column_in, String& sourceURL, JSObject* errorInstance, void* bunErrorData)
{
OrdinalNumber line = OrdinalNumber::fromOneBasedInt(line_in);
OrdinalNumber column = OrdinalNumber::fromOneBasedInt(column_in);
JSValue result = computeErrorInfoToJSValue(vm, stackTrace, line, column, sourceURL, errorInstance, bunErrorData);
line_in = line.oneBasedInt();
column_in = column.oneBasedInt();
return result;
}
JSC_DEFINE_HOST_FUNCTION(errorConstructorFuncAppendStackTrace, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
Zig::GlobalObject* globalObject = static_cast<Zig::GlobalObject*>(lexicalGlobalObject);
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
JSC::ErrorInstance* source = jsDynamicCast<JSC::ErrorInstance*>(callFrame->argument(0));
JSC::ErrorInstance* destination = jsDynamicCast<JSC::ErrorInstance*>(callFrame->argument(1));
if (!source || !destination) {
throwTypeError(lexicalGlobalObject, scope, "First & second argument must be an Error object"_s);
return {};
}
if (!destination->stackTrace()) {
destination->captureStackTrace(vm, globalObject, 1);
}
if (source->stackTrace()) {
destination->stackTrace()->appendVector(*source->stackTrace());
source->stackTrace()->clear();
}
return JSC::JSValue::encode(jsUndefined());
}
JSC_DEFINE_HOST_FUNCTION(jsFunctionDefaultErrorPrepareStackTrace, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
auto* globalObject = defaultGlobalObject(lexicalGlobalObject);
JSC::JSValue errorArg = callFrame->argument(0);
if (!errorArg.isObject()) {
throwTypeError(lexicalGlobalObject, scope, "First argument must be an object"_s);
return {};
}
auto* errorObject = errorArg.getObject();
auto callSites = jsDynamicCast<JSC::JSArray*>(callFrame->argument(1));
if (!callSites) {
callSites = JSArray::create(vm, globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), 0);
}
JSValue result = formatStackTraceToJSValue(vm, globalObject, lexicalGlobalObject, errorObject, callSites, jsUndefined());
RETURN_IF_EXCEPTION(scope, {});
return JSC::JSValue::encode(result);
}
JSC_DEFINE_CUSTOM_GETTER(errorInstanceLazyStackCustomGetter, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName))
{
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
auto* errorObject = jsDynamicCast<ErrorInstance*>(JSValue::decode(thisValue));
// This shouldn't be possible.
if (!errorObject) {
return JSValue::encode(jsUndefined());
}
OrdinalNumber line;
OrdinalNumber column;
String sourceURL;
auto stackTrace = errorObject->stackTrace();
JSValue result;
if (stackTrace == nullptr) {
WTF::Vector<JSC::StackFrame> emptyTrace;
result = computeErrorInfoToJSValue(vm, emptyTrace, line, column, sourceURL, errorObject, nullptr);
} else {
result = computeErrorInfoToJSValue(vm, *stackTrace, line, column, sourceURL, errorObject, nullptr);
stackTrace->clear();
errorObject->setStackFrames(vm, {});
}
RETURN_IF_EXCEPTION(scope, {});
errorObject->putDirect(vm, vm.propertyNames->stack, result, 0);
return JSValue::encode(result);
}
JSC_DEFINE_CUSTOM_SETTER(errorInstanceLazyStackCustomSetter, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, PropertyName))
{
auto& vm = JSC::getVM(globalObject);
JSValue decodedValue = JSValue::decode(thisValue);
if (auto* object = decodedValue.getObject()) {
object->putDirect(vm, vm.propertyNames->stack, JSValue::decode(value), 0);
}
return true;
}
JSC_DEFINE_HOST_FUNCTION(errorConstructorFuncCaptureStackTrace, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame))
{
Zig::GlobalObject* globalObject = static_cast<Zig::GlobalObject*>(lexicalGlobalObject);
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
JSC::JSValue objectArg = callFrame->argument(0);
if (!objectArg.isObject()) {
return JSC::JSValue::encode(throwTypeError(lexicalGlobalObject, scope, "invalid_argument"_s));
}
JSC::JSObject* errorObject = objectArg.asCell()->getObject();
JSC::JSValue caller = callFrame->argument(1);
size_t stackTraceLimit = globalObject->stackTraceLimit().value();
if (stackTraceLimit == 0) {
stackTraceLimit = DEFAULT_ERROR_STACK_TRACE_LIMIT;
}
WTF::Vector<JSC::StackFrame> stackTrace;
JSCStackTrace::getFramesForCaller(vm, callFrame, errorObject, caller, stackTrace, stackTraceLimit);
if (auto* instance = jsDynamicCast<JSC::ErrorInstance*>(errorObject)) {
// Force materialization before replacing the stack frames, so that JSC's
// internal lazy error info mechanism doesn't later see the replaced (possibly empty)
// stack trace and fail to create the stack property.
if (!instance->hasMaterializedErrorInfo())
instance->materializeErrorInfoIfNeeded(vm);
RETURN_IF_EXCEPTION(scope, {});
instance->setStackFrames(vm, WTF::move(stackTrace));
{
const auto& propertyName = vm.propertyNames->stack;
VM::DeletePropertyModeScope deleteScope(vm, VM::DeletePropertyMode::IgnoreConfigurable);
DeletePropertySlot slot;
JSObject::deleteProperty(instance, globalObject, propertyName, slot);
}
RETURN_IF_EXCEPTION(scope, {});
if (auto* zigGlobalObject = jsDynamicCast<Zig::GlobalObject*>(globalObject)) {
instance->putDirectCustomAccessor(vm, vm.propertyNames->stack, zigGlobalObject->m_lazyStackCustomGetterSetter.get(zigGlobalObject), JSC::PropertyAttribute::CustomAccessor | 0);
} else {
instance->putDirectCustomAccessor(vm, vm.propertyNames->stack, CustomGetterSetter::create(vm, errorInstanceLazyStackCustomGetter, errorInstanceLazyStackCustomSetter), JSC::PropertyAttribute::CustomAccessor | 0);
}
} else {
OrdinalNumber line;
OrdinalNumber column;
String sourceURL;
JSValue result = computeErrorInfoToJSValue(vm, stackTrace, line, column, sourceURL, errorObject, nullptr);
RETURN_IF_EXCEPTION(scope, {});
errorObject->putDirect(vm, vm.propertyNames->stack, result, 0);
}
return JSC::JSValue::encode(JSC::jsUndefined());
}
} // namespace Bun
namespace Zig {
void createCallSitesFromFrames(Zig::GlobalObject* globalObject, JSC::JSGlobalObject* lexicalGlobalObject, JSCStackTrace& stackTrace, MarkedArgumentBuffer& callSites)
{
/* From v8's "Stack Trace API" (https://github.com/v8/v8/wiki/Stack-Trace-API):
* "To maintain restrictions imposed on strict mode functions, frames that have a
* strict mode function and all frames below (its caller etc.) are not allow to access
* their receiver and function objects. For those frames, getFunction() and getThis()
* will return undefined."." */
bool encounteredStrictFrame = false;
// TODO: is it safe to use CallSite structure from a different JSGlobalObject? This case would happen within a node:vm
JSC::Structure* callSiteStructure = globalObject->callSiteStructure();
size_t framesCount = stackTrace.size();
for (size_t i = 0; i < framesCount; i++) {
CallSite* callSite = CallSite::create(lexicalGlobalObject, callSiteStructure, stackTrace.at(i), encounteredStrictFrame);
if (!encounteredStrictFrame) {
encounteredStrictFrame = callSite->isStrict();
}
callSites.append(callSite);
}
}
} // namespace Zig