forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreport.zig
545 lines (488 loc) · 18.9 KB
/
report.zig
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
const std = @import("std");
const logger = @import("logger.zig");
const root = @import("root");
const bun = @import("global.zig");
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const CLI = @import("./cli.zig").Cli;
const Features = @import("./analytics/analytics_thread.zig").Features;
const Platform = @import("./analytics/analytics_thread.zig").GenerateHeader.GeneratePlatform;
const HTTP = @import("http").AsyncHTTP;
const CrashReporter = @import("crash_reporter");
const Report = @This();
var crash_report_writer: CrashReportWriter = CrashReportWriter{ .file = null };
const CrashWritable = if (Environment.isWasm) std.io.fixedBufferStream([2048]u8) else std.fs.File.Writer;
var crash_reporter_path: [1024]u8 = undefined;
pub const CrashReportWriter = struct {
file: ?std.io.BufferedWriter(4096, CrashWritable) = null,
file_path: []const u8 = "",
pub fn printFrame(_: ?*anyopaque, frame: CrashReporter.StackFrame) void {
const function_name = if (frame.function_name.len > 0) frame.function_name else "[function ?]";
const filename = if (frame.filename.len > 0) frame.function_name else "[file ?]";
crash_report_writer.print("[0x{X}] - <b>{s}<r> {s}:{d}\n", .{ frame.pc, function_name, filename, frame.line_number });
}
pub fn dump() void {
if (comptime !Environment.isWasm)
CrashReporter.print();
}
pub fn done() void {
if (comptime !Environment.isWasm)
CrashReporter.print();
}
pub fn print(this: *CrashReportWriter, comptime fmt: string, args: anytype) void {
Output.prettyError(fmt, args);
if (this.file) |*file| {
var writer = file.writer();
writer.print(comptime Output.prettyFmt(fmt, false), args) catch {};
}
}
pub fn flush(this: *CrashReportWriter) void {
if (this.file) |*file| {
file.flush() catch {};
}
Output.flush();
}
pub fn generateFile(this: *CrashReportWriter) void {
if (this.file != null) return;
var base_dir: []const u8 = ".";
if (std.os.getenv("BUN_INSTALL")) |install_dir| {
base_dir = std.mem.trimRight(u8, install_dir, std.fs.path.sep_str);
} else if (std.os.getenv("HOME")) |home_dir| {
base_dir = std.mem.trimRight(u8, home_dir, std.fs.path.sep_str);
}
const file_path = std.fmt.bufPrintZ(
&crash_reporter_path,
"{s}/.bun-crash/v{s}-{d}.crash",
.{ base_dir, Global.package_json_version, @intCast(u64, @maximum(std.time.milliTimestamp(), 0)) },
) catch return;
std.fs.cwd().makeDir(std.fs.path.dirname(std.mem.span(file_path)).?) catch {};
var file = std.fs.cwd().createFileZ(file_path, .{ .truncate = true }) catch return;
this.file = std.io.bufferedWriter(
file.writer(),
);
this.file_path = std.mem.span(file_path);
}
pub fn printPath(this: *CrashReportWriter) void {
var display_path = this.file_path;
if (this.file_path.len > 0) {
var tilda = false;
if (std.os.getenv("HOME")) |home_dir| {
if (strings.hasPrefix(display_path, home_dir)) {
display_path = display_path[home_dir.len..];
tilda = true;
}
}
if (tilda) {
Output.prettyError("\nCrash report saved to:\n <b>~{s}<r>\n", .{display_path});
} else {
Output.prettyError("\nCrash report saved to:\n <b>{s}<r>\n", .{display_path});
}
}
}
};
pub fn printMetadata() void {
@setCold(true);
crash_report_writer.generateFile();
const cmd_label: string = if (CLI.cmd) |tag| @tagName(tag) else "Unknown";
const platform = if (Environment.isMac) "macOS" else "Linux";
const arch = if (Environment.isAarch64)
if (Environment.isMac) "Silicon" else "arm64"
else
"x64";
var analytics_platform = Platform.forOS();
crash_report_writer.print(
\\
\\<r>–––– bun meta ––––
++ "\nBun v" ++ Global.package_json_version ++ " " ++ platform ++ " " ++ arch ++ " {s}\n" ++
\\{s}: {}
\\
, .{
analytics_platform.version,
cmd_label,
Features.formatter(),
});
const http_count = HTTP.active_requests_count.loadUnchecked();
if (http_count > 0)
crash_report_writer.print(
\\HTTP: {d}
\\
, .{http_count});
if (comptime bun.use_mimalloc) {
var elapsed_msecs: usize = 0;
var user_msecs: usize = 0;
var system_msecs: usize = 0;
var current_rss: usize = 0;
var peak_rss: usize = 0;
var current_commit: usize = 0;
var peak_commit: usize = 0;
var page_faults: usize = 0;
const mimalloc = @import("allocators/mimalloc.zig");
mimalloc.mi_process_info(
&elapsed_msecs,
&user_msecs,
&system_msecs,
¤t_rss,
&peak_rss,
¤t_commit,
&peak_commit,
&page_faults,
);
crash_report_writer.print("Elapsed: {d}ms | User: {d}ms | Sys: {d}ms\nRSS: {:<3.2} | Peak: {:<3.2} | Commit: {:<3.2} | Faults: {d}\n", .{
elapsed_msecs,
user_msecs,
system_msecs,
std.fmt.fmtIntSizeDec(current_rss),
std.fmt.fmtIntSizeDec(peak_rss),
std.fmt.fmtIntSizeDec(current_commit),
page_faults,
});
}
crash_report_writer.print("–––– bun meta ––––\n", .{});
}
var has_printed_fatal = false;
var has_printed_crash = false;
pub fn fatal(err_: ?anyerror, msg_: ?string) void {
const had_printed_fatal = has_printed_fatal;
if (!has_printed_fatal) {
has_printed_fatal = true;
crash_report_writer.generateFile();
if (err_) |err| {
if (Output.isEmojiEnabled()) {
crash_report_writer.print(
"\n<r><red>error<r><d>:<r> <b>{s}<r>\n",
.{@errorName(err)},
);
} else {
crash_report_writer.print(
"\n<r>error: {s}\n\n",
.{@errorName(err)},
);
}
}
if (msg_) |msg| {
const msg_ptr = @ptrToInt(msg.ptr);
if (msg_ptr > 0) {
const len = @maximum(@minimum(msg.len, 1024), 0);
if (len > 0) {
if (Output.isEmojiEnabled()) {
crash_report_writer.print(
"\n<r><red>uh-oh<r><d>:<r> <b>{s}<r>\n",
.{msg[0..len]},
);
} else {
crash_report_writer.print(
"\n<r>an uh-oh: {s}\n\n",
.{msg[0..len]},
);
}
}
}
}
if (err_ == null) {
if (Output.isEmojiEnabled()) {
if (msg_ == null and err_ == null) {
crash_report_writer.print("<r><red>", .{});
} else {
crash_report_writer.print("<r>", .{});
}
crash_report_writer.print("bun will crash now<r> 😭😭😭\n", .{});
} else {
crash_report_writer.print("bun has crashed :'(\n", .{});
}
}
crash_report_writer.flush();
printMetadata();
crash_report_writer.flush();
// It only is a real crash report if it's not coming from Zig
CrashReportWriter.dump();
crash_report_writer.flush();
crash_report_writer.printPath();
}
if (!had_printed_fatal) {
crash_report_writer.print("\nAsk for #help in https://bun.sh/discord or go to https://bun.sh/issues\n\n", .{});
crash_report_writer.flush();
}
}
var globalError_ranOnce = false;
pub noinline fn handleCrash(signal: i32, addr: usize) void {
const had_printed_fatal = has_printed_fatal;
if (has_printed_fatal) return;
has_printed_fatal = true;
crash_report_writer.generateFile();
const name = switch (signal) {
std.os.SIG.SEGV => error.SegmentationFault,
std.os.SIG.ILL => error.InstructionError,
std.os.SIG.BUS => error.BusError,
else => error.Crash,
};
crash_report_writer.print("\n<r><red>{s}<d> at {d}\n\n", .{ @errorName(name), addr });
printMetadata();
CrashReportWriter.dump();
if (!had_printed_fatal) {
crash_report_writer.print("\nAsk for #help in https://bun.sh/discord or go to https://bun.sh/issues\n\n", .{});
}
crash_report_writer.flush();
if (crash_report_writer.file) |file| {
// don't handle return codes here
_ = std.os.system.close(file.unbuffered_writer.context.handle);
}
crash_report_writer.file = null;
if (comptime Environment.isDebug) {
if (@errorReturnTrace()) |stack| {
std.debug.dumpStackTrace(stack.*);
}
}
std.c._exit(128 + @truncate(u8, @intCast(u8, @maximum(signal, 0))));
}
pub noinline fn globalError(err: anyerror) noreturn {
@setCold(true);
if (@atomicRmw(bool, &globalError_ranOnce, .Xchg, true, .Monotonic)) {
Global.exit(1);
}
switch (err) {
error.SyntaxError => {
Output.prettyError(
"\n<r><red>SyntaxError<r><d>:<r> An error occurred while parsing code",
.{},
);
Global.exit(1);
},
error.OutOfMemory => {
Output.prettyError(
"\n<r><red>OutOfMemory<r><d>:<r> There might be an infinite loop somewhere",
.{},
);
printMetadata();
Global.exit(1);
},
error.CurrentWorkingDirectoryUnlinked => {
Output.prettyError(
"\n<r><red>error: <r>The current working directory was deleted, so that command didn't work. Please cd into a different directory and try again.",
.{},
);
Global.exit(1);
},
error.BundleFailed => {
Output.prettyError(
"\n<r><red>BundleFailed<r>",
.{},
);
Global.exit(1);
},
error.InvalidArgument, error.InstallFailed => {
Global.exit(1);
},
error.SystemFdQuotaExceeded => {
const limit = std.os.getrlimit(.NOFILE) catch std.mem.zeroes(std.os.rlimit);
if (comptime Environment.isMac) {
Output.prettyError(
\\
\\<r><red>error<r>: Your computer ran out of file descriptors <d>(<red>SystemFdQuotaExceeded<r><d>)<r>
\\
\\<d>Current limit: {d}<r>
\\
\\To fix this, try running:
\\
\\ <cyan>sudo launchctl limit maxfiles 2147483646<r>
\\ <cyan>ulimit -n 2147483646<r>
\\
\\That will only work until you reboot.
\\
,
.{
limit.cur,
},
);
} else {
Output.prettyError(
\\
\\<r><red>error<r>: Your computer ran out of file descriptors <d>(<red>SystemFdQuotaExceeded<r><d>)<r>
\\
\\<d>Current limit: {d}<r>
\\
\\To fix this, try running:
\\
\\ <cyan>sudo echo -e "\nfs.file-max=2147483646\n" >> /etc/sysctl.conf<r>
\\ <cyan>sudo sysctl -p<r>
\\ <cyan>ulimit -n 2147483646<r>
\\
,
.{
limit.cur,
},
);
if (std.os.getenv("USER")) |user| {
if (user.len > 0) {
Output.prettyError(
\\
\\If that still doesn't work, you may need to add these lines to /etc/security/limits.conf:
\\
\\ <cyan>{s} soft nofile 2147483646<r>
\\ <cyan>{s} hard nofile 2147483646<r>
\\
,
.{ user, user },
);
}
}
}
Global.exit(1);
},
error.@"Invalid Bunfig" => {
Global.exit(1);
},
error.ProcessFdQuotaExceeded => {
const limit = std.os.getrlimit(.NOFILE) catch std.mem.zeroes(std.os.rlimit);
if (comptime Environment.isMac) {
Output.prettyError(
\\
\\<r><red>error<r>: bun ran out of file descriptors <d>(<red>ProcessFdQuotaExceeded<r><d>)<r>
\\
\\<d>Current limit: {d}<r>
\\
\\To fix this, try running:
\\
\\ <cyan>ulimit -n 2147483646<r>
\\
\\You may also need to run:
\\
\\ <cyan>sudo launchctl limit maxfiles 2147483646<r>
\\
,
.{
limit.cur,
},
);
} else {
Output.prettyError(
\\
\\<r><red>error<r>: bun ran out of file descriptors <d>(<red>ProcessFdQuotaExceeded<r><d>)<r>
\\
\\<d>Current limit: {d}<r>
\\
\\To fix this, try running:
\\
\\ <cyan>ulimit -n 2147483646<r>
\\
\\That will only work for the current shell. To fix this for the entire system, run:
\\
\\ <cyan>sudo echo -e "\nfs.file-max=2147483646\n" >> /etc/sysctl.conf<r>
\\ <cyan>sudo sysctl -p<r>
\\
,
.{
limit.cur,
},
);
if (std.os.getenv("USER")) |user| {
if (user.len > 0) {
Output.prettyError(
\\
\\If that still doesn't work, you may need to add these lines to /etc/security/limits.conf:
\\
\\ <cyan>{s} soft nofile 2147483646<r>
\\ <cyan>{s} hard nofile 2147483646<r>
\\
,
.{ user, user },
);
}
}
}
Global.exit(1);
},
// The usage of `unreachable` in Zig's std.os may cause the file descriptor problem to show up as other errors
error.NotOpenForReading, error.Unexpected => {
const limit = std.os.getrlimit(.NOFILE) catch std.mem.zeroes(std.os.rlimit);
if (limit.cur > 0 and limit.cur < (8096 * 2)) {
Output.prettyError(
\\
\\<r><red>error<r>: An unknown error ocurred, possibly due to low max file descriptors <d>(<red>Unexpected<r><d>)<r>
\\
\\<d>Current limit: {d}<r>
\\
\\To fix this, try running:
\\
\\ <cyan>ulimit -n 2147483646<r>
\\
,
.{
limit.cur,
},
);
if (Environment.isLinux) {
if (std.os.getenv("USER")) |user| {
if (user.len > 0) {
Output.prettyError(
\\
\\If that still doesn't work, you may need to add these lines to /etc/security/limits.conf:
\\
\\ <cyan>{s} soft nofile 2147483646<r>
\\ <cyan>{s} hard nofile 2147483646<r>
\\
,
.{
user,
user,
},
);
}
}
} else if (Environment.isMac) {
Output.prettyError(
\\
\\If that still doesn't work, you may need to run:
\\
\\ <cyan>sudo launchctl limit maxfiles 2147483646<r>
\\
,
.{},
);
}
Global.exit(1);
}
},
error.FileNotFound => {
Output.prettyError(
"\n<r><red>error<r><d>:<r> <b>FileNotFound<r>\nbun could not find a file, and the code that produces this error is missing a better error.\n",
.{},
);
Output.flush();
Report.printMetadata();
Output.flush();
print_stacktrace: {
var debug_info = std.debug.getSelfDebugInfo() catch break :print_stacktrace;
var trace = @errorReturnTrace() orelse break :print_stacktrace;
Output.disableBuffering();
std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.debug.detectTTYConfig()) catch break :print_stacktrace;
}
Global.exit(1);
},
error.MissingPackageJSON => {
Output.prettyError(
"\n<r><red>error<r><d>:<r> <b>MissingPackageJSON<r>\nbun could not find a package.json file.\n",
.{},
);
Global.exit(1);
},
error.MissingValue => {
Global.exit(1);
},
else => {},
}
Report.fatal(err, null);
print_stacktrace: {
var debug_info = std.debug.getSelfDebugInfo() catch break :print_stacktrace;
var trace = @errorReturnTrace() orelse break :print_stacktrace;
Output.disableBuffering();
std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.debug.detectTTYConfig()) catch break :print_stacktrace;
}
Global.exit(1);
}