-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathVirtualMachine.zig
More file actions
3835 lines (3328 loc) · 142 KB
/
VirtualMachine.zig
File metadata and controls
3835 lines (3328 loc) · 142 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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This is the shared global state for a single JS instance execution.
//!
//! Today, Bun is one VM per thread, so the name "VirtualMachine" sort of makes
//! sense. If that changes, this should be renamed `ScriptExecutionContext`.
const VirtualMachine = @This();
export var has_bun_garbage_collector_flag_enabled = false;
pub export var isBunTest: bool = false;
pub export var Bun__defaultRemainingRunsUntilSkipReleaseAccess: c_int = 10;
// TODO: evaluate if this has any measurable performance impact.
pub var synthetic_allocation_limit: usize = std.math.maxInt(u32);
pub var string_allocation_limit: usize = std.math.maxInt(u32);
comptime {
_ = Bun__remapStackFramePositions;
@export(&scriptExecutionStatus, .{ .name = "Bun__VM__scriptExecutionStatus" });
@export(&setEntryPointEvalResultESM, .{ .name = "Bun__VM__setEntryPointEvalResultESM" });
@export(&setEntryPointEvalResultCJS, .{ .name = "Bun__VM__setEntryPointEvalResultCJS" });
@export(&specifierIsEvalEntryPoint, .{ .name = "Bun__VM__specifierIsEvalEntryPoint" });
@export(&string_allocation_limit, .{ .name = "Bun__stringSyntheticAllocationLimit" });
@export(&allowAddons, .{ .name = "Bun__VM__allowAddons" });
@export(&allowRejectionHandledWarning, .{ .name = "Bun__VM__allowRejectionHandledWarning" });
}
global: *JSGlobalObject,
allocator: std.mem.Allocator,
has_loaded_constructors: bool = false,
transpiler: Transpiler,
bun_watcher: ImportWatcher = .{ .none = {} },
console: *ConsoleObject,
log: *logger.Log,
main: []const u8 = "",
main_is_html_entrypoint: bool = false,
main_resolved_path: bun.String = bun.String.empty,
main_hash: u32 = 0,
/// Set if code overrides Bun.main to a custom value, and then reset when the VM loads a new file
/// (e.g. when bun:test starts testing a new file)
overridden_main: jsc.Strong.Optional = .empty,
entry_point: ServerEntryPoint = undefined,
origin: URL = URL{},
node_fs: ?*bun.api.node.fs.NodeFS = null,
timer: bun.api.Timer.All,
event_loop_handle: ?*jsc.PlatformEventLoop = null,
pending_unref_counter: i32 = 0,
preload: []const []const u8 = &.{},
unhandled_pending_rejection_to_capture: ?*JSValue = null,
standalone_module_graph: ?*bun.StandaloneModuleGraph = null,
smol: bool = false,
dns_result_order: DNSResolver.Order = .verbatim,
cpu_profiler_config: ?CPUProfilerConfig = null,
heap_profiler_config: ?HeapProfilerConfig = null,
counters: Counters = .{},
hot_reload: bun.cli.Command.HotReload = .none,
jsc_vm: *VM = undefined,
/// hide bun:wrap from stack traces
/// bun:wrap is very noisy
hide_bun_stackframes: bool = true,
is_printing_plugin: bool = false,
is_shutting_down: bool = false,
plugin_runner: ?PluginRunner = null,
is_main_thread: bool = false,
exit_handler: ExitHandler = .{},
default_tls_reject_unauthorized: ?bool = null,
default_verbose_fetch: ?bun.http.HTTPVerboseLevel = null,
/// Do not access this field directly!
///
/// It exists in the VirtualMachine struct so that we don't accidentally
/// make a stack copy of it only use it through source_mappings.
///
/// This proposal could let us safely move it back https://github.com/ziglang/zig/issues/7769
saved_source_map_table: SavedSourceMap.HashTable = undefined,
source_mappings: SavedSourceMap = undefined,
arena: *Arena = undefined,
has_loaded: bool = false,
transpiled_count: usize = 0,
resolved_count: usize = 0,
had_errors: bool = false,
macros: MacroMap,
macro_entry_points: std.AutoArrayHashMap(i32, *MacroEntryPoint),
macro_mode: bool = false,
no_macros: bool = false,
auto_killer: ProcessAutoKiller = .{ .enabled = false },
has_any_macro_remappings: bool = false,
is_from_devserver: bool = false,
has_enabled_macro_mode: bool = false,
/// Used by bun:test to set global hooks for beforeAll, beforeEach, etc.
is_in_preload: bool = false,
has_patched_run_main: bool = false,
transpiler_store: ModuleLoader.RuntimeTranspilerStore,
after_event_loop_callback_ctx: ?*anyopaque = null,
after_event_loop_callback: ?jsc.OpaqueCallback = null,
remap_stack_frames_mutex: bun.Mutex = .{},
/// The arguments used to launch the process _after_ the script name and bun and any flags applied to Bun
/// "bun run foo --bar"
/// ["--bar"]
/// "bun run foo baz --bar"
/// ["baz", "--bar"]
/// "bun run foo
/// []
/// "bun foo --bar"
/// ["--bar"]
/// "bun foo baz --bar"
/// ["baz", "--bar"]
/// "bun foo
/// []
argv: []const []const u8 = &[_][]const u8{},
origin_timer: std.time.Timer = undefined,
origin_timestamp: u64 = 0,
/// For fake timers: override performance.now() with a specific value (in nanoseconds)
/// When null, use the real timer. When set, return this value instead.
overridden_performance_now: ?u64 = null,
macro_event_loop: EventLoop = EventLoop{},
regular_event_loop: EventLoop = EventLoop{},
event_loop: *EventLoop = undefined,
ref_strings: jsc.RefString.Map = undefined,
ref_strings_mutex: bun.Mutex = undefined,
active_tasks: usize = 0,
rare_data: ?*jsc.RareData = null,
/// Owned storage for proxy env vars set via process.env at runtime. Not
/// in RareData because lazy RareData creation races with worker spawn
/// (worker thread needs to lock parent.proxy_env_storage.lock atomically
/// with observing the env map; a null-check on rare_data can't be both
/// lock-free and correct). ~56 bytes — negligible on VirtualMachine.
proxy_env_storage: jsc.RareData.ProxyEnvStorage = .{},
is_us_loop_entered: bool = false,
pending_internal_promise: ?*JSInternalPromise = null,
entry_point_result: struct {
value: jsc.Strong.Optional = .empty,
cjs_set_value: bool = false,
} = .{},
auto_install_dependencies: bool = false,
onUnhandledRejection: *const OnUnhandledRejection = defaultOnUnhandledRejection,
onUnhandledRejectionCtx: ?*anyopaque = null,
onUnhandledRejectionExceptionList: ?*ExceptionList = null,
unhandled_error_counter: usize = 0,
is_handling_uncaught_exception: bool = false,
exit_on_uncaught_exception: bool = false,
modules: ModuleLoader.AsyncModule.Queue = .{},
aggressive_garbage_collection: GCLevel = GCLevel.none,
module_loader: ModuleLoader = .{},
gc_controller: jsc.GarbageCollectionController = .{},
worker: ?*webcore.WebWorker = null,
ipc: ?IPCInstanceUnion = null,
hot_reload_counter: u32 = 0,
debugger: ?jsc.Debugger = null,
has_started_debugger: bool = false,
has_terminated: bool = false,
debug_thread_id: if (Environment.allow_assert) std.Thread.Id else void,
body_value_hive_allocator: webcore.Body.Value.HiveAllocator = undefined,
is_inside_deferred_task_queue: bool = false,
/// When true, drainMicrotasksWithGlobal is suppressed. Used by SpawnSyncEventLoop
/// to prevent the isolated event loop from draining the shared JSC microtask queue
/// (which would execute user JavaScript during spawnSync).
suppress_microtask_drain: bool = false,
// defaults off. .on("message") will set it to true unless overridden
// process.channel.unref() will set it to false and mark it overridden
// on disconnect it will be disabled
channel_ref: bun.Async.KeepAlive = .{},
// if process.channel.ref() or unref() has been called, this is set to true
channel_ref_overridden: bool = false,
// if one disconnect event listener should be ignored
channel_ref_should_ignore_one_disconnect_event_listener: bool = false,
/// A set of extensions that exist in the require.extensions map. Keys
/// contain the leading '.'. Value is either a loader for built in
/// functions, or an index into JSCommonJSExtensions.
///
/// `.keys() == transpiler.resolver.opts.extra_cjs_extensions`, so
/// mutations in this map must update the resolver.
commonjs_custom_extensions: bun.StringArrayHashMapUnmanaged(node_module_module.CustomLoader) = .empty,
/// Incremented when the `require.extensions` for a built-in extension is mutated.
/// An example is mutating `require.extensions['.js']` to intercept all '.js' files.
/// The value is decremented when defaults are restored.
has_mutated_built_in_extensions: u32 = 0,
initial_script_execution_context_identifier: i32,
extern "C" fn Bake__getAsyncLocalStorage(globalObject: *JSGlobalObject) callconv(jsc.conv) jsc.JSValue;
pub fn getDevServerAsyncLocalStorage(this: *VirtualMachine) !?jsc.JSValue {
const jsvalue = try jsc.fromJSHostCall(this.global, @src(), Bake__getAsyncLocalStorage, .{this.global});
if (jsvalue.isEmptyOrUndefinedOrNull()) return null;
return jsvalue;
}
pub const ProcessAutoKiller = @import("./ProcessAutoKiller.zig");
pub const OnUnhandledRejection = fn (*VirtualMachine, globalObject: *JSGlobalObject, JSValue) void;
pub const OnException = fn (*ZigException) void;
pub fn allowAddons(this: *VirtualMachine) callconv(.c) bool {
return if (this.transpiler.options.transform_options.allow_addons) |allow_addons| allow_addons else true;
}
pub fn allowRejectionHandledWarning(this: *VirtualMachine) callconv(.c) bool {
return this.unhandledRejectionsMode() != .bun;
}
pub fn unhandledRejectionsMode(this: *VirtualMachine) api.UnhandledRejections {
return this.transpiler.options.transform_options.unhandled_rejections orelse .bun;
}
pub fn initRequestBodyValue(this: *VirtualMachine, body: jsc.WebCore.Body.Value) !*Body.Value.HiveRef {
return .init(body, &this.body_value_hive_allocator);
}
/// Whether this VM should be destroyed after it exits, even if it is the main thread's VM.
/// Worker VMs are always destroyed on exit, regardless of this setting. Setting this to
/// true may expose bugs that would otherwise only occur using Workers. Controlled by
pub fn shouldDestructMainThreadOnExit(_: *const VirtualMachine) bool {
return bun.feature_flag.BUN_DESTRUCT_VM_ON_EXIT.get();
}
pub threadlocal var is_bundler_thread_for_bytecode_cache: bool = false;
pub fn uwsLoop(this: *const VirtualMachine) *uws.Loop {
if (comptime Environment.isPosix) {
if (Environment.allow_assert) {
return this.event_loop_handle orelse @panic("uws event_loop_handle is null");
}
return this.event_loop_handle.?;
}
return uws.Loop.get();
}
pub fn uvLoop(this: *const VirtualMachine) *bun.Async.Loop {
if (Environment.allow_assert) {
return this.event_loop_handle orelse @panic("libuv event_loop_handle is null");
}
return this.event_loop_handle.?;
}
pub fn isMainThread(this: *const VirtualMachine) bool {
return this.worker == null;
}
pub fn isInspectorEnabled(this: *const VirtualMachine) bool {
return this.debugger != null;
}
pub fn isShuttingDown(this: *const VirtualMachine) bool {
return this.is_shutting_down;
}
pub fn getTLSRejectUnauthorized(this: *const VirtualMachine) bool {
return this.default_tls_reject_unauthorized orelse this.transpiler.env.getTLSRejectUnauthorized();
}
pub fn onSubprocessSpawn(this: *VirtualMachine, process: *bun.spawn.Process) void {
this.auto_killer.onSubprocessSpawn(process);
}
pub fn onSubprocessExit(this: *VirtualMachine, process: *bun.spawn.Process) void {
this.auto_killer.onSubprocessExit(process);
}
pub fn getVerboseFetch(this: *VirtualMachine) bun.http.HTTPVerboseLevel {
return this.default_verbose_fetch orelse {
if (this.transpiler.env.get("BUN_CONFIG_VERBOSE_FETCH")) |verbose_fetch| {
if (strings.eqlComptime(verbose_fetch, "true") or strings.eqlComptime(verbose_fetch, "1")) {
this.default_verbose_fetch = .headers;
return .headers;
} else if (strings.eqlComptime(verbose_fetch, "curl")) {
this.default_verbose_fetch = .curl;
return .curl;
}
}
this.default_verbose_fetch = .none;
return .none;
};
}
pub const VMHolder = struct {
pub threadlocal var vm: ?*VirtualMachine = null;
pub threadlocal var cached_global_object: ?*JSGlobalObject = null;
pub var main_thread_vm: ?*VirtualMachine = null;
pub export fn Bun__setDefaultGlobalObject(global: *JSGlobalObject) void {
if (vm) |vm_instance| {
vm_instance.global = global;
// Ensure this is always set when it should be.
if (vm_instance.is_main_thread) {
VMHolder.main_thread_vm = vm_instance;
}
}
cached_global_object = global;
}
pub export fn Bun__getDefaultGlobalObject() ?*JSGlobalObject {
return cached_global_object orelse {
if (vm) |vm_instance| {
cached_global_object = vm_instance.global;
}
return null;
};
}
pub export fn Bun__thisThreadHasVM() bool {
return vm != null;
}
};
pub inline fn get() *VirtualMachine {
return getOrNull().?;
}
pub inline fn getOrNull() ?*VirtualMachine {
return VMHolder.vm;
}
pub fn getMainThreadVM() ?*VirtualMachine {
return VMHolder.main_thread_vm;
}
pub fn mimeType(this: *VirtualMachine, str: []const u8) ?bun.http.MimeType {
return this.rareData().mimeTypeFromString(this.allocator, str);
}
/// Interning lookup for Blob/File `type` that preserves the raw MIME
/// string (no charset substitution). See `rare_data.mimeTypeInternedValue`.
pub fn mimeTypeInternedValue(this: *VirtualMachine, str: []const u8) ?[]const u8 {
return this.rareData().mimeTypeInternedValue(this.allocator, str);
}
pub fn onAfterEventLoop(this: *VirtualMachine) void {
if (this.after_event_loop_callback) |cb| {
const ctx = this.after_event_loop_callback_ctx;
this.after_event_loop_callback = null;
this.after_event_loop_callback_ctx = null;
cb(ctx);
}
}
pub fn isEventLoopAliveExcludingImmediates(vm: *const VirtualMachine) bool {
return vm.unhandled_error_counter == 0 and
(@intFromBool(vm.event_loop_handle.?.isActive()) +
vm.active_tasks +
vm.event_loop.tasks.count +
@intFromBool(vm.event_loop.hasPendingRefs()) > 0);
}
pub fn isEventLoopAlive(vm: *const VirtualMachine) bool {
return vm.isEventLoopAliveExcludingImmediates() or
// We need to keep running in this case so that immediate tasks get run. But immediates
// intentionally don't make the event loop _active_ so we need to check for them
// separately.
vm.event_loop.immediate_tasks.items.len > 0 or
vm.event_loop.next_immediate_tasks.items.len > 0;
}
pub fn wakeup(this: *VirtualMachine) void {
this.eventLoop().wakeup();
}
const SourceMapHandlerGetter = struct {
vm: *VirtualMachine,
printer: *js_printer.BufferPrinter,
pub fn get(this: *SourceMapHandlerGetter) js_printer.SourceMapHandler {
if (this.vm.debugger == null or this.vm.debugger.?.mode == .connect) {
return SavedSourceMap.SourceMapHandler.init(&this.vm.source_mappings);
}
return js_printer.SourceMapHandler.For(SourceMapHandlerGetter, onChunk).init(this);
}
/// When the inspector is enabled, we want to generate an inline sourcemap.
/// And, for now, we also store it in source_mappings like normal
/// This is hideously expensive memory-wise...
pub fn onChunk(this: *SourceMapHandlerGetter, chunk: SourceMap.Chunk, source: *const logger.Source) anyerror!void {
var temp_json_buffer = bun.MutableString.initEmpty(bun.default_allocator);
defer temp_json_buffer.deinit();
try chunk.printSourceMapContentsAtOffset(source, &temp_json_buffer, true, SavedSourceMap.vlq_offset, true);
const source_map_url_prefix_start = "//# sourceMappingURL=data:application/json;base64,";
// TODO: do we need to %-encode the path?
const source_url_len = source.path.text.len;
const source_mapping_url = "\n//# sourceURL=";
const prefix_len = source_map_url_prefix_start.len + source_mapping_url.len + source_url_len;
try this.vm.source_mappings.putMappings(source, chunk.buffer);
const encode_len = bun.base64.encodeLen(temp_json_buffer.list.items);
try this.printer.ctx.buffer.growIfNeeded(encode_len + prefix_len + 2);
this.printer.ctx.buffer.appendAssumeCapacity("\n" ++ source_map_url_prefix_start);
_ = bun.base64.encode(this.printer.ctx.buffer.list.items.ptr[this.printer.ctx.buffer.len()..this.printer.ctx.buffer.list.capacity], temp_json_buffer.list.items);
this.printer.ctx.buffer.list.items.len += encode_len;
this.printer.ctx.buffer.appendAssumeCapacity(source_mapping_url);
// TODO: do we need to %-encode the path?
this.printer.ctx.buffer.appendAssumeCapacity(source.path.text);
try this.printer.ctx.buffer.append("\n");
}
};
pub inline fn sourceMapHandler(this: *VirtualMachine, printer: *js_printer.BufferPrinter) SourceMapHandlerGetter {
return SourceMapHandlerGetter{
.vm = this,
.printer = printer,
};
}
pub const GCLevel = enum(u3) {
none = 0,
mild = 1,
aggressive = 2,
};
pub threadlocal var is_main_thread_vm: bool = false;
pub const UnhandledRejectionScope = struct {
ctx: ?*anyopaque = null,
onUnhandledRejection: *const OnUnhandledRejection = undefined,
count: usize = 0,
pub fn apply(this: *UnhandledRejectionScope, vm: *jsc.VirtualMachine) void {
vm.onUnhandledRejection = this.onUnhandledRejection;
vm.onUnhandledRejectionCtx = this.ctx;
vm.unhandled_error_counter = this.count;
}
};
pub fn onQuietUnhandledRejectionHandler(this: *VirtualMachine, _: *JSGlobalObject, _: JSValue) void {
this.unhandled_error_counter += 1;
}
pub fn onQuietUnhandledRejectionHandlerCaptureValue(this: *VirtualMachine, _: *JSGlobalObject, value: JSValue) void {
this.unhandled_error_counter += 1;
value.ensureStillAlive();
if (this.unhandled_pending_rejection_to_capture) |ptr| {
ptr.* = value;
}
}
pub fn unhandledRejectionScope(this: *VirtualMachine) UnhandledRejectionScope {
return .{
.onUnhandledRejection = this.onUnhandledRejection,
.ctx = this.onUnhandledRejectionCtx,
.count = this.unhandled_error_counter,
};
}
fn ensureSourceCodePrinter(this: *VirtualMachine) void {
if (source_code_printer == null) {
const allocator = if (bun.heap_breakdown.enabled) bun.heap_breakdown.namedAllocator("SourceCode") else this.allocator;
const writer = js_printer.BufferWriter.init(allocator);
source_code_printer = allocator.create(js_printer.BufferPrinter) catch unreachable;
source_code_printer.?.* = js_printer.BufferPrinter.init(writer);
source_code_printer.?.ctx.append_null_byte = false;
}
}
pub fn loadExtraEnvAndSourceCodePrinter(this: *VirtualMachine) void {
var map = this.transpiler.env.map;
ensureSourceCodePrinter(this);
if (map.get("BUN_SHOW_BUN_STACKFRAMES") != null) {
this.hide_bun_stackframes = false;
}
if (bun.feature_flag.BUN_FEATURE_FLAG_DISABLE_ASYNC_TRANSPILER.get()) {
this.transpiler_store.enabled = false;
}
if (map.map.fetchSwapRemove("NODE_CHANNEL_FD")) |kv| {
const fd_s = kv.value.value;
const mode = if (map.map.fetchSwapRemove("NODE_CHANNEL_SERIALIZATION_MODE")) |mode_kv|
IPC.Mode.fromString(mode_kv.value.value) orelse .json
else
.json;
IPC.log("IPC environment variables: NODE_CHANNEL_FD={s}, NODE_CHANNEL_SERIALIZATION_MODE={s}", .{ fd_s, @tagName(mode) });
if (std.fmt.parseInt(u31, fd_s, 10)) |fd| {
this.initIPCInstance(.fromUV(fd), mode);
} else |_| {
Output.warn("Failed to parse IPC channel number '{s}'", .{fd_s});
}
}
// Node.js checks if this are set to "1" and no other value
if (map.get("NODE_PRESERVE_SYMLINKS")) |value| {
this.transpiler.resolver.opts.preserve_symlinks = bun.strings.eqlComptime(value, "1");
}
if (map.get("BUN_GARBAGE_COLLECTOR_LEVEL")) |gc_level| {
// Reuse this flag for other things to avoid unnecessary hashtable
// lookups on start for obscure flags which we do not want others to
// depend on.
if (map.get("BUN_FEATURE_FLAG_FORCE_WAITER_THREAD") != null) {
bun.spawn.process.WaiterThread.setShouldUseWaiterThread();
}
// Only allowed for testing
if (map.get("BUN_FEATURE_FLAG_INTERNAL_FOR_TESTING") != null) {
ModuleLoader.is_allowed_to_use_internal_testing_apis = true;
}
if (strings.eqlComptime(gc_level, "1")) {
this.aggressive_garbage_collection = .mild;
has_bun_garbage_collector_flag_enabled = true;
} else if (strings.eqlComptime(gc_level, "2")) {
this.aggressive_garbage_collection = .aggressive;
has_bun_garbage_collector_flag_enabled = true;
}
if (map.get("BUN_FEATURE_FLAG_SYNTHETIC_MEMORY_LIMIT")) |value| {
if (std.fmt.parseInt(usize, value, 10)) |limit| {
synthetic_allocation_limit = limit;
string_allocation_limit = limit;
} else |_| {
Output.panic("BUN_FEATURE_FLAG_SYNTHETIC_MEMORY_LIMIT must be a positive integer", .{});
}
}
}
}
extern fn Bun__handleUncaughtException(*JSGlobalObject, err: JSValue, is_rejection: c_int) c_int;
extern fn Bun__handleUnhandledRejection(*JSGlobalObject, reason: JSValue, promise: JSValue) c_int;
extern fn Bun__wrapUnhandledRejectionErrorForUncaughtException(*JSGlobalObject, reason: JSValue) JSValue;
extern fn Bun__emitHandledPromiseEvent(*JSGlobalObject, promise: JSValue) bool;
extern fn Bun__promises__isErrorLike(*JSGlobalObject, reason: JSValue) bool;
extern fn Bun__promises__emitUnhandledRejectionWarning(*JSGlobalObject, reason: JSValue, promise: JSValue) void;
extern fn Bun__noSideEffectsToString(vm: *jsc.VM, globalObject: *JSGlobalObject, reason: JSValue) JSValue;
fn isErrorLike(globalObject: *JSGlobalObject, reason: JSValue) bun.JSError!bool {
return jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__isErrorLike, .{ globalObject, reason });
}
fn wrapUnhandledRejectionErrorForUncaughtException(globalObject: *JSGlobalObject, reason: JSValue) JSValue {
if (isErrorLike(globalObject, reason) catch blk: {
globalObject.clearException();
break :blk false;
}) return reason;
const reasonStr = blk: {
var scope: jsc.TopExceptionScope = undefined;
scope.init(globalObject, @src());
defer scope.deinit();
defer if (scope.exception()) |_| scope.clearException();
break :blk Bun__noSideEffectsToString(globalObject.vm(), globalObject, reason);
};
const msg_1 = "This error originated either by throwing inside of an async function without a catch block, " ++
"or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"";
if (reasonStr.isString()) {
return globalObject.ERR(.UNHANDLED_REJECTION, msg_1 ++ "{f}\".", .{reasonStr.asString().view(globalObject)}).toJS();
}
return globalObject.ERR(.UNHANDLED_REJECTION, msg_1 ++ "{s}\".", .{"undefined"}).toJS();
}
pub fn unhandledRejection(this: *jsc.VirtualMachine, globalObject: *JSGlobalObject, reason: JSValue, promise: JSValue) void {
if (this.isShuttingDown()) {
Output.debugWarn("unhandledRejection during shutdown.", .{});
return;
}
if (isBunTest) {
this.unhandled_error_counter += 1;
this.onUnhandledRejection(this, globalObject, reason);
return;
}
switch (this.unhandledRejectionsMode()) {
.bun => {
if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) return;
// continue to default handler
},
.none => {
defer this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => {}, // we are returning anyway
};
if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) return;
return; // ignore the unhandled rejection
},
.warn => {
defer this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => {}, // we are returning anyway
};
_ = Bun__handleUnhandledRejection(globalObject, reason, promise);
jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| {
_ = globalObject.reportUncaughtException(globalObject.takeException(err).asException(globalObject.vm()).?);
};
return;
},
.warn_with_error_code => {
defer this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => {}, // we are returning anyway
};
if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) return;
jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| {
_ = globalObject.reportUncaughtException(globalObject.takeException(err).asException(globalObject.vm()).?);
};
this.exit_handler.exit_code = 1;
return;
},
.strict => {
defer this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => {}, // we are returning anyway
};
const wrapped_reason = wrapUnhandledRejectionErrorForUncaughtException(globalObject, reason);
_ = this.uncaughtException(globalObject, wrapped_reason, true);
if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) return;
jsc.fromJSHostCallGeneric(globalObject, @src(), Bun__promises__emitUnhandledRejectionWarning, .{ globalObject, reason, promise }) catch |err| {
_ = globalObject.reportUncaughtException(globalObject.takeException(err).asException(globalObject.vm()).?);
};
return;
},
.throw => {
if (Bun__handleUnhandledRejection(globalObject, reason, promise) > 0) {
this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => {}, // we are returning anyway
};
return;
}
const wrapped_reason = wrapUnhandledRejectionErrorForUncaughtException(globalObject, reason);
if (this.uncaughtException(globalObject, wrapped_reason, true)) {
this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => {}, // we are returning anyway
};
return;
}
// continue to default handler
this.eventLoop().drainMicrotasks() catch |e| switch (e) {
error.JSTerminated => return,
};
},
}
this.unhandled_error_counter += 1;
this.onUnhandledRejection(this, globalObject, reason);
return;
}
pub fn handledPromise(this: *jsc.VirtualMachine, globalObject: *JSGlobalObject, promise: JSValue) bool {
if (this.isShuttingDown()) {
return true;
}
return Bun__emitHandledPromiseEvent(globalObject, promise);
}
pub fn uncaughtException(this: *jsc.VirtualMachine, globalObject: *JSGlobalObject, err: JSValue, is_rejection: bool) bool {
if (this.isShuttingDown()) {
return true;
}
if (isBunTest) {
this.unhandled_error_counter += 1;
this.onUnhandledRejection(this, globalObject, err);
return true;
}
if (this.is_handling_uncaught_exception) {
this.runErrorHandler(err, null);
bun.api.node.process.exit(globalObject, 7);
@panic("Uncaught exception while handling uncaught exception");
}
if (this.exit_on_uncaught_exception) {
this.runErrorHandler(err, null);
bun.api.node.process.exit(globalObject, 1);
@panic("made it past Bun__Process__exit");
}
this.is_handling_uncaught_exception = true;
defer this.is_handling_uncaught_exception = false;
const handled = Bun__handleUncaughtException(globalObject, err.toError() orelse err, if (is_rejection) 1 else 0) > 0;
if (!handled) {
// TODO maybe we want a separate code path for uncaught exceptions
this.unhandled_error_counter += 1;
this.exit_handler.exit_code = 1;
this.onUnhandledRejection(this, globalObject, err);
}
return handled;
}
pub fn reportExceptionInHotReloadedModuleIfNeeded(this: *jsc.VirtualMachine) void {
defer this.addMainToWatcherIfNeeded();
var promise = this.pending_internal_promise orelse return;
if (promise.status() == .rejected and !promise.isHandled()) {
this.unhandledRejection(this.global, promise.result(), promise.asValue());
promise.setHandled(this.global.vm());
}
}
pub fn addMainToWatcherIfNeeded(this: *jsc.VirtualMachine) void {
if (this.isWatcherEnabled()) {
const main = this.main;
if (main.len == 0) return;
_ = this.bun_watcher.addFileByPathSlow(main, this.transpiler.options.loader(std.fs.path.extension(main)));
}
}
pub fn defaultOnUnhandledRejection(this: *jsc.VirtualMachine, _: *JSGlobalObject, value: JSValue) void {
this.runErrorHandler(value, this.onUnhandledRejectionExceptionList);
}
pub inline fn packageManager(this: *VirtualMachine) *PackageManager {
return this.transpiler.getPackageManager();
}
pub fn garbageCollect(this: *const VirtualMachine, sync: bool) usize {
@branchHint(.cold);
Global.mimalloc_cleanup(false);
if (sync)
return this.global.vm().runGC(true);
this.global.vm().collectAsync();
return this.global.vm().heapSize();
}
pub inline fn autoGarbageCollect(this: *const VirtualMachine) void {
if (this.aggressive_garbage_collection != .none) {
_ = this.garbageCollect(this.aggressive_garbage_collection == .aggressive);
}
}
pub fn reload(this: *VirtualMachine, _: *HotReloader.Task) void {
Output.debug("Reloading...", .{});
const should_clear_terminal = !this.transpiler.env.hasSetNoClearTerminalOnReload(!Output.enable_ansi_colors_stdout);
if (this.hot_reload == .watch) {
Output.flush();
bun.reloadProcess(
bun.default_allocator,
should_clear_terminal,
false,
);
}
if (should_clear_terminal) {
Output.flush();
Output.disableBuffering();
Output.resetTerminalAll();
Output.enableBuffering();
}
jsc.API.cron.CronJob.clearAllForVM(this, .reload);
this.global.reload() catch @panic("Failed to reload");
this.hot_reload_counter += 1;
this.pending_internal_promise = this.reloadEntryPoint(this.main) catch @panic("Failed to reload");
}
pub inline fn nodeFS(this: *VirtualMachine) *Node.fs.NodeFS {
return this.node_fs orelse brk: {
this.node_fs = bun.default_allocator.create(Node.fs.NodeFS) catch unreachable;
this.node_fs.?.* = Node.fs.NodeFS{
// only used when standalone module graph is enabled
.vm = if (this.standalone_module_graph != null) this else null,
};
break :brk this.node_fs.?;
};
}
pub inline fn rareData(this: *VirtualMachine) *jsc.RareData {
return this.rare_data orelse brk: {
this.rare_data = this.allocator.create(jsc.RareData) catch unreachable;
this.rare_data.?.* = .{};
break :brk this.rare_data.?;
};
}
pub inline fn eventLoop(this: *VirtualMachine) *EventLoop {
return this.event_loop;
}
pub fn prepareLoop(_: *VirtualMachine) void {}
pub fn enterUWSLoop(this: *VirtualMachine) void {
var loop = this.event_loop_handle.?;
loop.run();
}
pub fn onBeforeExit(this: *VirtualMachine) void {
this.exit_handler.dispatchOnBeforeExit();
var dispatch = false;
while (true) {
while (this.isEventLoopAlive()) : (dispatch = true) {
this.tick();
this.eventLoop().autoTickActive();
}
if (dispatch) {
this.exit_handler.dispatchOnBeforeExit();
dispatch = false;
if (this.isEventLoopAlive()) continue;
}
break;
}
}
pub fn scriptExecutionStatus(this: *const VirtualMachine) callconv(.c) jsc.ScriptExecutionStatus {
if (this.is_shutting_down) {
return .stopped;
}
if (this.worker) |worker| {
if (worker.hasRequestedTerminate()) {
return .stopped;
}
}
return .running;
}
pub fn specifierIsEvalEntryPoint(this: *VirtualMachine, specifier: JSValue) callconv(.c) bool {
if (this.module_loader.eval_source) |eval_source| {
var specifier_str = specifier.toBunString(this.global) catch @panic("unexpected exception");
defer specifier_str.deref();
return specifier_str.eqlUTF8(eval_source.path.text);
}
return false;
}
pub fn setEntryPointEvalResultESM(this: *VirtualMachine, result: JSValue) callconv(.c) void {
// allow esm evaluate to set value multiple times
if (!this.entry_point_result.cjs_set_value) {
this.entry_point_result.value.set(this.global, result);
}
}
pub fn setEntryPointEvalResultCJS(this: *VirtualMachine, value: JSValue) callconv(.c) void {
if (!this.entry_point_result.value.has()) {
this.entry_point_result.value.set(this.global, value);
this.entry_point_result.cjs_set_value = true;
}
}
pub fn onExit(this: *VirtualMachine) void {
// Write CPU profile if profiling was enabled - do this FIRST before any shutdown begins
// Grab the config and null it out to make this idempotent
if (this.cpu_profiler_config) |config| {
this.cpu_profiler_config = null;
CPUProfiler.stopAndWriteProfile(this.jsc_vm, config) catch |err| {
Output.err(err, "Failed to write CPU profile", .{});
};
}
// Write heap profile if profiling was enabled - do this after CPU profile but before shutdown
// Grab the config and null it out to make this idempotent
if (this.heap_profiler_config) |config| {
this.heap_profiler_config = null;
HeapProfiler.generateAndWriteProfile(this.jsc_vm, config) catch |err| {
Output.err(err, "Failed to write heap profile", .{});
};
}
this.exit_handler.dispatchOnExit();
this.is_shutting_down = true;
const rare_data = this.rare_data orelse return;
defer rare_data.cleanup_hooks.clearAndFree(bun.default_allocator);
// Make sure we run new cleanup hooks introduced by running cleanup hooks
while (rare_data.cleanup_hooks.items.len > 0) {
var hooks = rare_data.cleanup_hooks;
defer hooks.deinit(bun.default_allocator);
rare_data.cleanup_hooks = .{};
for (hooks.items) |hook| {
hook.execute();
}
}
}
extern fn Zig__GlobalObject__destructOnExit(*JSGlobalObject) void;
pub fn globalExit(this: *VirtualMachine) noreturn {
bun.assert(this.isShuttingDown());
// FIXME: we should be doing this, but we're not, but unfortunately doing it
// causes like 50+ tests to break
// this.eventLoop().tick();
if (this.shouldDestructMainThreadOnExit()) {
if (this.eventLoop().forever_timer) |t| t.deinit(true);
Zig__GlobalObject__destructOnExit(this.global);
this.transpiler.deinit();
this.gc_controller.deinit();
this.deinit();
}
bun.Global.exit(this.exit_handler.exit_code);
}
pub fn nextAsyncTaskID(this: *VirtualMachine) u64 {
var debugger: *jsc.Debugger = &(this.debugger orelse return 0);
debugger.next_debugger_id +%= 1;
return debugger.next_debugger_id;
}
pub fn hotMap(this: *VirtualMachine) ?*jsc.RareData.HotMap {
if (this.hot_reload != .hot) {
return null;
}
return this.rareData().hotMap(this.allocator);
}
pub inline fn enqueueTask(this: *VirtualMachine, task: jsc.Task) void {
this.eventLoop().enqueueTask(task);
}
pub inline fn enqueueImmediateTask(this: *VirtualMachine, task: *bun.api.Timer.ImmediateObject) void {
this.eventLoop().enqueueImmediateTask(task);
}
pub inline fn enqueueTaskConcurrent(this: *VirtualMachine, task: *jsc.ConcurrentTask) void {
this.eventLoop().enqueueTaskConcurrent(task);
}
pub fn tick(this: *VirtualMachine) void {
this.eventLoop().tick();
}
pub fn waitFor(this: *VirtualMachine, cond: *bool) void {
while (!cond.*) {
this.eventLoop().tick();
if (!cond.*) {
this.eventLoop().autoTick();
}
}
}
pub fn waitForPromise(this: *VirtualMachine, promise: jsc.AnyPromise) void {
this.eventLoop().waitForPromise(promise);
}
pub fn waitForTasks(this: *VirtualMachine) void {
while (this.isEventLoopAlive()) {
this.eventLoop().tick();
if (this.isEventLoopAlive()) {
this.eventLoop().autoTick();
}
}
}
pub const MacroMap = std.AutoArrayHashMap(i32, jsc.C.JSObjectRef);
pub fn enableMacroMode(this: *VirtualMachine) void {
jsc.markBinding(@src());
if (!this.has_enabled_macro_mode) {
this.has_enabled_macro_mode = true;
this.macro_event_loop.tasks = EventLoop.Queue.init(default_allocator);
this.macro_event_loop.tasks.ensureTotalCapacity(16) catch unreachable;
this.macro_event_loop.global = this.global;
this.macro_event_loop.virtual_machine = this;
this.macro_event_loop.concurrent_tasks = .{};
ensureSourceCodePrinter(this);
}
this.transpiler.options.target = .bun_macro;
this.transpiler.resolver.caches.fs.use_alternate_source_cache = true;
this.macro_mode = true;
this.event_loop = &this.macro_event_loop;
bun.analytics.Features.macros += 1;
this.transpiler_store.enabled = false;
}
pub fn disableMacroMode(this: *VirtualMachine) void {
this.transpiler.options.target = .bun;
this.transpiler.resolver.caches.fs.use_alternate_source_cache = false;
this.macro_mode = false;
this.event_loop = &this.regular_event_loop;
this.transpiler_store.enabled = true;
}
pub fn isWatcherEnabled(this: *VirtualMachine) bool {
return this.bun_watcher != .none;
}
/// Instead of storing timestamp as a i128, we store it as a u64.
/// We subtract the timestamp from Jan 1, 2000 (Y2K)
pub const origin_relative_epoch = 946684800 * std.time.ns_per_s;
fn getOriginTimestamp() u64 {