From 437e15bae5aa01e111df8ab5d489f30f119c13bb Mon Sep 17 00:00:00 2001 From: "taylor.fish" Date: Tue, 26 Aug 2025 12:50:25 -0700 Subject: [PATCH] Replace `catch bun.outOfMemory()` with safer alternatives (#22141) Replace `catch bun.outOfMemory()`, which can accidentally catch non-OOM-related errors, with either `bun.handleOom` or a manual `catch |err| switch (err)`. (For internal tracking: fixes STAB-1070) --------- Co-authored-by: Dylan Conway --- cmake/sources/ZigSources.txt | 2 +- src/HTMLScanner.zig | 2 +- src/StandaloneModuleGraph.zig | 12 +- src/Watcher.zig | 8 +- src/allocators.zig | 8 +- src/allocators/AllocationScope.zig | 2 +- src/api/schema.zig | 2 +- src/ast/BundledAst.zig | 2 +- src/ast/E.zig | 10 +- src/ast/Expr.zig | 2 +- src/ast/ImportScanner.zig | 6 +- src/ast/NewStore.zig | 2 +- src/ast/P.zig | 112 ++++++++--------- src/ast/Parser.zig | 6 +- src/ast/SideEffects.zig | 4 +- src/ast/foldStringAddition.zig | 2 +- src/ast/maybe.zig | 8 +- src/ast/parseProperty.zig | 2 +- src/ast/parseStmt.zig | 4 +- src/ast/parseTypescript.zig | 12 +- src/ast/visit.zig | 6 +- src/ast/visitExpr.zig | 14 +-- src/ast/visitStmt.zig | 36 +++--- src/bake.zig | 4 +- src/bake/DevServer.zig | 47 ++++--- src/bake/DevServer/HmrSocket.zig | 2 +- src/bake/DevServer/HotReloadEvent.zig | 18 +-- src/bake/DevServer/IncrementalGraph.zig | 2 +- src/bake/DevServer/SourceMapStore.zig | 2 +- src/bun.js/Debugger.zig | 2 +- src/bun.js/ModuleLoader.zig | 8 +- src/bun.js/SavedSourceMap.zig | 8 +- src/bun.js/VirtualMachine.zig | 2 +- src/bun.js/api/BunObject.zig | 8 +- src/bun.js/api/JSBundler.zig | 16 ++- src/bun.js/api/JSTranspiler.zig | 12 +- src/bun.js/api/Timer.zig | 4 +- src/bun.js/api/bun/dns.zig | 54 ++++---- src/bun.js/api/bun/h2_frame_parser.zig | 30 ++--- src/bun.js/api/bun/process.zig | 12 +- src/bun.js/api/bun/socket.zig | 24 ++-- src/bun.js/api/bun/socket/Listener.zig | 42 +++---- src/bun.js/api/bun/socket/SocketAddress.zig | 4 +- .../bun/socket/WindowsNamedPipeContext.zig | 2 +- .../api/bun/socket/tls_socket_functions.zig | 8 +- src/bun.js/api/bun/spawn/stdio.zig | 6 +- src/bun.js/api/bun/subprocess.zig | 2 +- src/bun.js/api/bun/udp_socket.zig | 22 ++-- src/bun.js/api/crypto/CryptoHasher.zig | 2 +- src/bun.js/api/crypto/PasswordObject.zig | 4 +- src/bun.js/api/ffi.zig | 34 ++--- src/bun.js/api/glob.zig | 2 +- src/bun.js/api/html_rewriter.zig | 22 ++-- src/bun.js/api/server.zig | 31 ++--- src/bun.js/api/server/FileRoute.zig | 6 +- src/bun.js/api/server/HTMLBundle.zig | 36 +++--- src/bun.js/api/server/NodeHTTPResponse.zig | 10 +- src/bun.js/api/server/ServerConfig.zig | 26 ++-- src/bun.js/api/server/StaticRoute.zig | 6 +- src/bun.js/bindings/DeferredError.zig | 2 +- src/bun.js/bindings/HTTPServerAgent.zig | 2 +- src/bun.js/event_loop.zig | 4 +- .../event_loop/AnyTaskWithExtraContext.zig | 2 +- src/bun.js/event_loop/DeferredTaskQueue.zig | 2 +- src/bun.js/event_loop/ManagedTask.zig | 2 +- src/bun.js/event_loop/MiniEventLoop.zig | 10 +- src/bun.js/hot_reloader.zig | 4 +- src/bun.js/ipc.zig | 22 ++-- src/bun.js/node/node_cluster_binding.zig | 6 +- src/bun.js/node/node_crypto_binding.zig | 2 +- src/bun.js/node/node_fs.zig | 54 ++++---- src/bun.js/node/node_fs_stat_watcher.zig | 2 +- src/bun.js/node/node_fs_watcher.zig | 2 +- src/bun.js/node/node_process.zig | 8 +- src/bun.js/node/node_util_binding.zig | 2 +- src/bun.js/node/node_zlib_binding.zig | 4 +- src/bun.js/node/path.zig | 26 ++-- src/bun.js/node/path_watcher.zig | 12 +- src/bun.js/node/types.zig | 25 +++- src/bun.js/node/win_watcher.zig | 8 +- src/bun.js/rare_data.zig | 31 +++-- src/bun.js/test/jest.zig | 36 +++--- src/bun.js/virtual_machine_exports.zig | 2 +- src/bun.js/web_worker.zig | 39 ++++-- src/bun.js/webcore/ArrayBufferSink.zig | 2 +- src/bun.js/webcore/Blob.zig | 50 ++++---- src/bun.js/webcore/Body.zig | 8 +- src/bun.js/webcore/ByteBlobLoader.zig | 4 +- src/bun.js/webcore/ByteStream.zig | 4 +- src/bun.js/webcore/FileReader.zig | 6 +- src/bun.js/webcore/ObjectURLRegistry.zig | 4 +- src/bun.js/webcore/Response.zig | 14 +-- src/bun.js/webcore/S3Client.zig | 16 +-- src/bun.js/webcore/S3File.zig | 10 +- src/bun.js/webcore/blob/Store.zig | 2 +- src/bun.js/webcore/blob/copy_file.zig | 4 +- src/bun.js/webcore/blob/read_file.zig | 4 +- src/bun.js/webcore/fetch.zig | 42 ++++--- src/bun.js/webcore/streams.zig | 4 +- src/bun.zig | 34 +---- src/bundler/AstBuilder.zig | 2 +- src/bundler/BundleThread.zig | 6 +- src/bundler/Chunk.zig | 9 +- src/bundler/LinkerContext.zig | 32 ++--- src/bundler/LinkerGraph.zig | 6 +- src/bundler/ParseTask.zig | 22 ++-- src/bundler/ServerComponentParseTask.zig | 2 +- src/bundler/bundle_v2.zig | 116 +++++++++--------- src/bundler/linker_context/computeChunks.zig | 6 +- src/bundler/linker_context/doStep5.zig | 12 +- .../findAllImportedPartsInJSOrder.zig | 4 +- .../findImportedCSSFilesInJSOrder.zig | 4 +- .../findImportedFilesInCSSOrder.zig | 42 +++---- .../generateChunksInParallel.zig | 26 ++-- .../generateCodeForFileInChunkJS.zig | 24 ++-- .../generateCodeForLazyExport.zig | 12 +- .../generateCompileResultForHtmlChunk.zig | 22 ++-- .../linker_context/postProcessCSSChunk.zig | 4 +- .../linker_context/postProcessHTMLChunk.zig | 2 +- .../linker_context/postProcessJSChunk.zig | 4 +- .../linker_context/prepareCssAstsForChunk.zig | 18 +-- .../linker_context/scanImportsAndExports.zig | 32 ++--- src/bunfig.zig | 2 +- src/cli.zig | 2 +- src/cli/bunx_command.zig | 4 +- src/cli/create_command.zig | 2 +- src/cli/filter_run.zig | 6 +- src/cli/install_command.zig | 2 +- src/cli/outdated_command.zig | 20 +-- src/cli/pack_command.zig | 8 +- src/cli/run_command.zig | 25 +++- src/cli/test/Scanner.zig | 4 +- src/cli/test_command.zig | 30 ++--- src/cli/update_interactive_command.zig | 6 +- src/cli/upgrade_command.zig | 4 +- src/codegen/generate-node-errors.ts | 2 +- src/collections/hive_array.zig | 4 +- src/create/SourceFileProjectGenerator.zig | 2 +- src/css/context.zig | 24 ++-- src/css/css_modules.zig | 34 ++--- src/css/css_parser.zig | 104 ++++++++-------- src/css/declaration.zig | 14 +-- src/css/generics.zig | 2 +- src/css/media_query.zig | 4 +- src/css/printer.zig | 4 +- src/css/properties/align.zig | 26 ++-- src/css/properties/background.zig | 12 +- src/css/properties/border.zig | 8 +- src/css/properties/border_image.zig | 18 +-- src/css/properties/border_radius.zig | 8 +- src/css/properties/box_shadow.zig | 12 +- src/css/properties/custom.zig | 14 +-- src/css/properties/flex.zig | 18 +-- src/css/properties/font.zig | 16 +-- src/css/properties/grid.zig | 16 +-- src/css/properties/margin_padding.zig | 20 +-- src/css/properties/prefix_handler.zig | 6 +- src/css/properties/size.zig | 8 +- src/css/properties/transform.zig | 16 +-- src/css/properties/transition.zig | 12 +- src/css/properties/ui.zig | 12 +- src/css/rules/page.zig | 4 +- src/css/rules/rules.zig | 30 ++--- src/css/rules/supports.zig | 10 +- src/css/selectors/parser.zig | 2 +- src/css/selectors/selector.zig | 12 +- src/css/small_list.zig | 18 +-- src/css/values/calc.zig | 4 +- src/css/values/color_js.zig | 2 +- src/css/values/gradient.zig | 26 ++-- src/css/values/ident.zig | 2 +- src/css/values/image.zig | 2 +- src/css/values/syntax.zig | 6 +- src/css/values/url.zig | 2 +- src/deps/c_ares.zig | 16 +-- src/deps/uws/UpgradedDuplex.zig | 4 +- src/deps/uws/WindowsNamedPipe.zig | 8 +- src/deps/uws/socket.zig | 6 +- src/fs.zig | 8 +- src/handle_oom.zig | 66 ++++++++++ src/http.zig | 16 +-- src/http/HTTPThread.zig | 6 +- src/http/Headers.zig | 8 +- src/http/MimeType.zig | 14 +-- src/http/ProxyTunnel.zig | 2 +- src/http/websocket_client.zig | 4 +- .../WebSocketUpgradeClient.zig | 4 +- src/install/NetworkTask.zig | 8 +- src/install/PackageInstall.zig | 6 +- src/install/PackageInstaller.zig | 34 ++--- src/install/PackageManager.zig | 18 +-- .../PackageManager/PackageJSONEditor.zig | 8 +- .../PackageManagerDirectories.zig | 8 +- .../PackageManager/PackageManagerEnqueue.zig | 6 +- .../PackageManagerLifecycle.zig | 10 +- src/install/PackageManager/UpdateRequest.zig | 8 +- .../WorkspacePackageJSONCache.zig | 12 +- .../PackageManager/install_with_manager.zig | 8 +- src/install/PackageManager/patchPackage.zig | 16 +-- .../PackageManager/processDependencyList.zig | 6 +- src/install/PackageManager/runTasks.zig | 30 ++--- .../PackageManager/security_scanner.zig | 6 +- .../updatePackageJSONAndInstall.zig | 4 +- src/install/PackageManagerTask.zig | 2 +- src/install/PackageManifestMap.zig | 2 +- src/install/bin.zig | 4 +- src/install/dependency.zig | 2 +- src/install/hoisted_install.zig | 2 +- src/install/install.zig | 7 +- src/install/isolated_install/Store.zig | 8 +- src/install/lifecycle_script_runner.zig | 4 +- src/install/lockfile.zig | 4 +- src/install/lockfile/Package.zig | 2 +- src/install/lockfile/Package/Scripts.zig | 6 +- src/install/lockfile/Package/WorkspaceMap.zig | 4 +- src/install/lockfile/Tree.zig | 2 +- src/install/lockfile/printer/tree_printer.zig | 4 +- src/install/migration.zig | 4 +- src/install/patch_install.zig | 31 +++-- src/install/repository.zig | 10 +- src/io/MaxBuf.zig | 2 +- src/io/PipeReader.zig | 10 +- src/io/io.zig | 2 +- src/io/source.zig | 6 +- src/js_lexer.zig | 2 +- src/js_printer.zig | 8 +- src/main_wasm.zig | 4 +- src/napi/napi.zig | 4 +- src/options.zig | 2 +- src/patch.zig | 38 +++--- src/ptr/ref_count.zig | 4 +- src/resolver/data_url.zig | 2 +- src/resolver/resolve_path.zig | 2 +- src/resolver/resolver.zig | 10 +- src/router.zig | 2 +- src/s3/client.zig | 72 ++++++----- src/s3/credentials.zig | 22 ++-- src/s3/download_stream.zig | 2 +- src/s3/multipart.zig | 14 +-- src/s3/simple_request.zig | 6 +- src/shell/Builtin.zig | 8 +- src/shell/EnvMap.zig | 10 +- src/shell/EnvStr.zig | 2 +- src/shell/IOWriter.zig | 14 +-- src/shell/ParsedShellScript.zig | 4 +- src/shell/RefCountedStr.zig | 2 +- src/shell/Yield.zig | 4 +- src/shell/builtin/basename.zig | 2 +- src/shell/builtin/cp.zig | 22 ++-- src/shell/builtin/dirname.zig | 2 +- src/shell/builtin/echo.zig | 8 +- src/shell/builtin/export.zig | 4 +- src/shell/builtin/ls.zig | 20 +-- src/shell/builtin/mkdir.zig | 18 +-- src/shell/builtin/mv.zig | 4 +- src/shell/builtin/rm.zig | 22 ++-- src/shell/builtin/seq.zig | 4 +- src/shell/builtin/touch.zig | 6 +- src/shell/builtin/yes.zig | 2 +- src/shell/interpreter.zig | 34 ++--- src/shell/shell.zig | 36 +++--- src/shell/states/Assigns.zig | 2 +- src/shell/states/Cmd.zig | 16 +-- src/shell/states/CondExpr.zig | 2 +- src/shell/states/Expansion.zig | 82 +++++++------ src/shell/states/Pipeline.zig | 4 +- src/shell/subproc.zig | 38 +++--- src/sourcemap/CodeCoverage.zig | 10 +- src/sourcemap/sourcemap.zig | 10 +- src/sql/mysql/MySQLConnection.zig | 2 +- src/sql/mysql/MySQLStatement.zig | 6 +- src/sql/postgres/PostgresSQLConnection.zig | 2 +- src/sql/postgres/PostgresSQLStatement.zig | 6 +- src/string.zig | 2 +- src/string/MutableString.zig | 2 +- src/string/StringJoiner.zig | 4 +- src/string/WTFStringImpl.zig | 18 +-- src/sys/Error.zig | 4 +- src/sys/File.zig | 8 +- src/transpiler.zig | 6 +- src/valkey/valkey.zig | 14 +-- src/walker_skippable.zig | 8 +- test/internal/ban-limits.json | 1 + test/internal/ban-words.test.ts | 1 + 284 files changed, 1835 insertions(+), 1662 deletions(-) create mode 100644 src/handle_oom.zig diff --git a/cmake/sources/ZigSources.txt b/cmake/sources/ZigSources.txt index 970920f69b..8e903797ee 100644 --- a/cmake/sources/ZigSources.txt +++ b/cmake/sources/ZigSources.txt @@ -498,7 +498,6 @@ src/copy_file.zig src/crash_handler.zig src/create/SourceFileProjectGenerator.zig src/csrf.zig -src/css_scanner.zig src/css/compat.zig src/css/context.zig src/css/css_internals.zig @@ -650,6 +649,7 @@ src/glob.zig src/glob/GlobWalker.zig src/glob/match.zig src/Global.zig +src/handle_oom.zig src/heap_breakdown.zig src/highway.zig src/hmac.zig diff --git a/src/HTMLScanner.zig b/src/HTMLScanner.zig index 461e3ebbff..2a8226009f 100644 --- a/src/HTMLScanner.zig +++ b/src/HTMLScanner.zig @@ -58,7 +58,7 @@ pub fn onHTMLParseError(this: *HTMLScanner, message: []const u8) void { this.source, logger.Loc.Empty, message, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } pub fn onTag(this: *HTMLScanner, _: *lol.Element, path: []const u8, url_attribute: []const u8, kind: ImportKind) void { diff --git a/src/StandaloneModuleGraph.zig b/src/StandaloneModuleGraph.zig index df1ac4e296..b42b5182ac 100644 --- a/src/StandaloneModuleGraph.zig +++ b/src/StandaloneModuleGraph.zig @@ -248,7 +248,7 @@ pub const StandaloneModuleGraph = struct { }; const source_files = serialized.sourceFileNames(); - const slices = bun.default_allocator.alloc(?[]u8, source_files.len * 2) catch bun.outOfMemory(); + const slices = bun.handleOom(bun.default_allocator.alloc(?[]u8, source_files.len * 2)); const file_names: [][]const u8 = @ptrCast(slices[0..source_files.len]); const decompressed_contents_slice = slices[source_files.len..][0..source_files.len]; @@ -598,7 +598,7 @@ pub const StandaloneModuleGraph = struct { std.fs.path.sep_str, zname, &.{0}, - }) catch bun.outOfMemory(); + }) catch |e| bun.handleOom(e); zname = zname_z[0..zname_z.len -| 1 :0]; continue; } @@ -683,7 +683,7 @@ pub const StandaloneModuleGraph = struct { var file = bun.sys.File{ .handle = cloned_executable_fd }; const writer = file.writer(); const BufferedWriter = std.io.BufferedWriter(512 * 1024, @TypeOf(writer)); - var buffered_writer = bun.default_allocator.create(BufferedWriter) catch bun.outOfMemory(); + var buffered_writer = bun.handleOom(bun.default_allocator.create(BufferedWriter)); buffered_writer.* = .{ .unbuffered_writer = writer, }; @@ -929,7 +929,7 @@ pub const StandaloneModuleGraph = struct { var free_self_exe = false; const self_exe = if (self_exe_path) |path| brk: { free_self_exe = true; - break :brk allocator.dupeZ(u8, path) catch bun.outOfMemory(); + break :brk bun.handleOom(allocator.dupeZ(u8, path)); } else if (target.isDefault()) bun.selfExePath() catch |err| { return CompileResult.fail(std.fmt.allocPrint(allocator, "failed to get self executable path: {s}", .{@errorName(err)}) catch "failed to get self executable path"); @@ -958,7 +958,7 @@ pub const StandaloneModuleGraph = struct { } free_self_exe = true; - break :blk allocator.dupeZ(u8, dest_z) catch bun.outOfMemory(); + break :blk bun.handleOom(allocator.dupeZ(u8, dest_z)); }; defer if (free_self_exe) { @@ -1358,7 +1358,7 @@ pub const StandaloneModuleGraph = struct { const compressed_file = compressed_codes[@intCast(index)].slice(this.map.bytes); const size = bun.zstd.getDecompressedSize(compressed_file); - const bytes = bun.default_allocator.alloc(u8, size) catch bun.outOfMemory(); + const bytes = bun.handleOom(bun.default_allocator.alloc(u8, size)); const result = bun.zstd.decompress(bytes, compressed_file); if (result == .err) { diff --git a/src/Watcher.zig b/src/Watcher.zig index 6ee87623af..c62a9aab0f 100644 --- a/src/Watcher.zig +++ b/src/Watcher.zig @@ -322,7 +322,7 @@ fn appendFileAssumeCapacity( const watchlist_id = this.watchlist.len; const file_path_: string = if (comptime clone_file_path) - bun.asByteSlice(this.allocator.dupeZ(u8, file_path) catch bun.outOfMemory()) + bun.asByteSlice(bun.handleOom(this.allocator.dupeZ(u8, file_path))) else file_path; @@ -409,7 +409,7 @@ fn appendDirectoryAssumeCapacity( }; const file_path_: string = if (comptime clone_file_path) - bun.asByteSlice(this.allocator.dupeZ(u8, file_path) catch bun.outOfMemory()) + bun.asByteSlice(bun.handleOom(this.allocator.dupeZ(u8, file_path))) else file_path; @@ -529,7 +529,7 @@ pub fn appendFileMaybeLock( } } } - this.watchlist.ensureUnusedCapacity(this.allocator, 1 + @as(usize, @intCast(@intFromBool(parent_watch_item == null)))) catch bun.outOfMemory(); + bun.handleOom(this.watchlist.ensureUnusedCapacity(this.allocator, 1 + @as(usize, @intCast(@intFromBool(parent_watch_item == null))))); if (autowatch_parent_dir) { parent_watch_item = parent_watch_item orelse switch (this.appendDirectoryAssumeCapacity(dir_fd, parent_dir, parent_dir_hash, clone_file_path)) { @@ -595,7 +595,7 @@ pub fn addDirectory( return .{ .result = @truncate(idx) }; } - this.watchlist.ensureUnusedCapacity(this.allocator, 1) catch bun.outOfMemory(); + bun.handleOom(this.watchlist.ensureUnusedCapacity(this.allocator, 1)); return this.appendDirectoryAssumeCapacity(fd, file_path, hash, clone_file_path); } diff --git a/src/allocators.zig b/src/allocators.zig index 9ea5cec49f..134c260d9e 100644 --- a/src/allocators.zig +++ b/src/allocators.zig @@ -244,7 +244,7 @@ pub fn BSSList(comptime ValueType: type, comptime _count: anytype) type { pub fn init(allocator: std.mem.Allocator) *Self { if (!loaded) { - instance = bun.default_allocator.create(Self) catch bun.outOfMemory(); + instance = bun.handleOom(bun.default_allocator.create(Self)); // Avoid struct initialization syntax. // This makes Bun start about 1ms faster. // https://github.com/ziglang/zig/issues/24313 @@ -330,7 +330,7 @@ pub fn BSSStringList(comptime _count: usize, comptime _item_length: usize) type pub fn init(allocator: std.mem.Allocator) *Self { if (!loaded) { - instance = bun.default_allocator.create(Self) catch bun.outOfMemory(); + instance = bun.handleOom(bun.default_allocator.create(Self)); // Avoid struct initialization syntax. // This makes Bun start about 1ms faster. // https://github.com/ziglang/zig/issues/24313 @@ -513,7 +513,7 @@ pub fn BSSMap(comptime ValueType: type, comptime count: anytype, comptime store_ // Avoid struct initialization syntax. // This makes Bun start about 1ms faster. // https://github.com/ziglang/zig/issues/24313 - instance = bun.default_allocator.create(Self) catch bun.outOfMemory(); + instance = bun.handleOom(bun.default_allocator.create(Self)); instance.index = IndexMap{}; instance.allocator = allocator; instance.overflow_list.zero(); @@ -666,7 +666,7 @@ pub fn BSSMap(comptime ValueType: type, comptime count: anytype, comptime store_ pub fn init(allocator: std.mem.Allocator) *Self { if (!instance_loaded) { - instance = bun.default_allocator.create(Self) catch bun.outOfMemory(); + instance = bun.handleOom(bun.default_allocator.create(Self)); // Avoid struct initialization syntax. // This makes Bun start about 1ms faster. // https://github.com/ziglang/zig/issues/24313 diff --git a/src/allocators/AllocationScope.zig b/src/allocators/AllocationScope.zig index e8244c55c2..abc8cd9de9 100644 --- a/src/allocators/AllocationScope.zig +++ b/src/allocators/AllocationScope.zig @@ -235,7 +235,7 @@ pub fn trackExternalAllocation(scope: Self, ptr: []const u8, ret_addr: ?usize, e const state = scope.internal_state; state.mutex.lock(); defer state.mutex.unlock(); - state.allocations.ensureUnusedCapacity(state.parent, 1) catch bun.outOfMemory(); + bun.handleOom(state.allocations.ensureUnusedCapacity(state.parent, 1)); trackAllocationAssumeCapacity(state, ptr, ptr.len, ret_addr orelse @returnAddress(), extra); } diff --git a/src/api/schema.zig b/src/api/schema.zig index 38ab7a63e9..3da966b9c7 100644 --- a/src/api/schema.zig +++ b/src/api/schema.zig @@ -2820,7 +2820,7 @@ pub const api = struct { token: []const u8, pub fn dupe(this: NpmRegistry, allocator: std.mem.Allocator) NpmRegistry { - const buf = allocator.alloc(u8, this.url.len + this.username.len + this.password.len + this.token.len) catch bun.outOfMemory(); + const buf = bun.handleOom(allocator.alloc(u8, this.url.len + this.username.len + this.password.len + this.token.len)); var out: NpmRegistry = .{ .url = "", diff --git a/src/ast/BundledAst.zig b/src/ast/BundledAst.zig index 340e57ba3a..0398b3ab59 100644 --- a/src/ast/BundledAst.zig +++ b/src/ast/BundledAst.zig @@ -193,7 +193,7 @@ pub fn addUrlForCss( const encode_len = bun.base64.encodeLen(contents); const data_url_prefix_len = "data:".len + mime_type.len + ";base64,".len; const total_buffer_len = data_url_prefix_len + encode_len; - var encoded = allocator.alloc(u8, total_buffer_len) catch bun.outOfMemory(); + var encoded = bun.handleOom(allocator.alloc(u8, total_buffer_len)); _ = std.fmt.bufPrint(encoded[0..data_url_prefix_len], "data:{s};base64,", .{mime_type}) catch unreachable; const len = bun.base64.encode(encoded[data_url_prefix_len..], contents); break :url_for_css encoded[0 .. data_url_prefix_len + len]; diff --git a/src/ast/E.zig b/src/ast/E.zig index 2e134aea62..a787f836f8 100644 --- a/src/ast/E.zig +++ b/src/ast/E.zig @@ -434,7 +434,7 @@ pub const Number = struct { if (Environment.isNative) { var buf: [124]u8 = undefined; - return allocator.dupe(u8, bun.fmt.FormatDouble.dtoa(&buf, value)) catch bun.outOfMemory(); + return bun.handleOom(allocator.dupe(u8, bun.fmt.FormatDouble.dtoa(&buf, value))); } else { // do not attempt to implement the spec here, it would be error prone. } @@ -909,7 +909,7 @@ pub const String = struct { return if (bun.strings.isAllASCII(utf8)) init(utf8) else - init(bun.strings.toUTF16AllocForReal(allocator, utf8, false, false) catch bun.outOfMemory()); + init(bun.handleOom(bun.strings.toUTF16AllocForReal(allocator, utf8, false, false))); } pub fn slice8(this: *const String) []const u8 { @@ -924,11 +924,11 @@ pub const String = struct { pub fn resolveRopeIfNeeded(this: *String, allocator: std.mem.Allocator) void { if (this.next == null or !this.isUTF8()) return; - var bytes = std.ArrayList(u8).initCapacity(allocator, this.rope_len) catch bun.outOfMemory(); + var bytes = bun.handleOom(std.ArrayList(u8).initCapacity(allocator, this.rope_len)); bytes.appendSliceAssumeCapacity(this.data); var str = this.next; while (str) |part| { - bytes.appendSlice(part.data) catch bun.outOfMemory(); + bun.handleOom(bytes.appendSlice(part.data)); str = part.next; } this.data = bytes.items; @@ -937,7 +937,7 @@ pub const String = struct { pub fn slice(this: *String, allocator: std.mem.Allocator) []const u8 { this.resolveRopeIfNeeded(allocator); - return this.string(allocator) catch bun.outOfMemory(); + return bun.handleOom(this.string(allocator)); } pub var empty = String{}; diff --git a/src/ast/Expr.zig b/src/ast/Expr.zig index 147be2e539..7f4ed148ec 100644 --- a/src/ast/Expr.zig +++ b/src/ast/Expr.zig @@ -474,7 +474,7 @@ pub inline fn isString(expr: *const Expr) bool { pub inline fn asString(expr: *const Expr, allocator: std.mem.Allocator) ?string { switch (expr.data) { - .e_string => |str| return str.string(allocator) catch bun.outOfMemory(), + .e_string => |str| return bun.handleOom(str.string(allocator)), else => return null, } } diff --git a/src/ast/ImportScanner.zig b/src/ast/ImportScanner.zig index 5ab81b9a82..156fd0c211 100644 --- a/src/ast/ImportScanner.zig +++ b/src/ast/ImportScanner.zig @@ -217,7 +217,7 @@ pub fn scan( result.* = alias; } strings.sortDesc(sorted); - p.named_imports.ensureUnusedCapacity(p.allocator, sorted.len) catch bun.outOfMemory(); + bun.handleOom(p.named_imports.ensureUnusedCapacity(p.allocator, sorted.len)); // Create named imports for these property accesses. This will // cause missing imports to generate useful warnings. @@ -236,7 +236,7 @@ pub fn scan( .namespace_ref = namespace_ref, .import_record_index = st.import_record_index, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const name: LocRef = item; const name_ref = name.ref.?; @@ -262,7 +262,7 @@ pub fn scan( p.named_imports.ensureUnusedCapacity( p.allocator, st.items.len + @as(usize, @intFromBool(st.default_name != null)) + @as(usize, @intFromBool(st.star_name_loc != null)), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); if (st.star_name_loc) |loc| { record.contains_import_star = true; diff --git a/src/ast/NewStore.zig b/src/ast/NewStore.zig index 60aeb71f06..8abd0b402f 100644 --- a/src/ast/NewStore.zig +++ b/src/ast/NewStore.zig @@ -78,7 +78,7 @@ pub fn NewStore(comptime types: []const type, comptime count: usize) type { pub fn init() *Store { log("init", .{}); // Avoid initializing the entire struct. - const prealloc = backing_allocator.create(PreAlloc) catch bun.outOfMemory(); + const prealloc = bun.handleOom(backing_allocator.create(PreAlloc)); prealloc.zero(); return &prealloc.metadata; diff --git a/src/ast/P.zig b/src/ast/P.zig index cc6f586198..b321106fd5 100644 --- a/src/ast/P.zig +++ b/src/ast/P.zig @@ -565,7 +565,7 @@ pub fn NewParser_( pub fn transposeRequire(noalias p: *P, arg: Expr, state: *const TransposeState) Expr { if (!p.options.features.allow_runtime) { - const args = p.allocator.alloc(Expr, 1) catch bun.outOfMemory(); + const args = bun.handleOom(p.allocator.alloc(Expr, 1)); args[0] = arg; return p.newExpr( E.Call{ @@ -607,8 +607,8 @@ pub fn NewParser_( // Note that this symbol may be completely removed later. var path_name = fs.PathName.init(path.text); - const name = path_name.nonUniqueNameString(p.allocator) catch bun.outOfMemory(); - const namespace_ref = p.newSymbol(.other, name) catch bun.outOfMemory(); + const name = bun.handleOom(path_name.nonUniqueNameString(p.allocator)); + const namespace_ref = bun.handleOom(p.newSymbol(.other, name)); p.imports_to_convert_from_require.append(p.allocator, .{ .namespace = .{ @@ -616,8 +616,8 @@ pub fn NewParser_( .loc = arg.loc, }, .import_record_id = import_record_index, - }) catch bun.outOfMemory(); - p.import_items_for_namespace.put(p.allocator, namespace_ref, ImportItemForNamespaceMap.init(p.allocator)) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); + bun.handleOom(p.import_items_for_namespace.put(p.allocator, namespace_ref, ImportItemForNamespaceMap.init(p.allocator))); p.recordUsage(namespace_ref); if (!state.is_require_immediately_assigned_to_decl) { @@ -2022,7 +2022,7 @@ pub fn NewParser_( fn ensureRequireSymbol(p: *P) void { if (p.runtime_imports.__require != null) return; const static_symbol = generatedSymbolName("__require"); - p.runtime_imports.__require = declareSymbolMaybeGenerated(p, .other, logger.Loc.Empty, static_symbol, true) catch bun.outOfMemory(); + p.runtime_imports.__require = bun.handleOom(declareSymbolMaybeGenerated(p, .other, logger.Loc.Empty, static_symbol, true)); p.runtime_imports.put("__require", p.runtime_imports.__require.?); } @@ -2235,8 +2235,8 @@ pub fn NewParser_( { p.log.level = .verbose; - p.log.addDebugFmt(p.source, loc, p.allocator, "Expected this scope (.{s})", .{@tagName(kind)}) catch bun.outOfMemory(); - p.log.addDebugFmt(p.source, order.loc, p.allocator, "Found this scope (.{s})", .{@tagName(order.scope.kind)}) catch bun.outOfMemory(); + bun.handleOom(p.log.addDebugFmt(p.source, loc, p.allocator, "Expected this scope (.{s})", .{@tagName(kind)})); + bun.handleOom(p.log.addDebugFmt(p.source, order.loc, p.allocator, "Found this scope (.{s})", .{@tagName(order.scope.kind)})); p.panic("Scope mismatch while visiting", .{}); } @@ -2283,8 +2283,8 @@ pub fn NewParser_( if (p.scopes_in_order.items[last_i]) |prev_scope| { if (prev_scope.loc.start >= loc.start) { p.log.level = .verbose; - p.log.addDebugFmt(p.source, prev_scope.loc, p.allocator, "Previous Scope", .{}) catch bun.outOfMemory(); - p.log.addDebugFmt(p.source, loc, p.allocator, "Next Scope", .{}) catch bun.outOfMemory(); + bun.handleOom(p.log.addDebugFmt(p.source, prev_scope.loc, p.allocator, "Previous Scope", .{})); + bun.handleOom(p.log.addDebugFmt(p.source, loc, p.allocator, "Next Scope", .{})); p.panic("Scope location {d} must be greater than {d}", .{ loc.start, prev_scope.loc.start }); } } @@ -2959,7 +2959,7 @@ pub fn NewParser_( scope: js_ast.TSNamespaceScope, }; - var pair = p.allocator.create(Pair) catch bun.outOfMemory(); + var pair = bun.handleOom(p.allocator.create(Pair)); pair.map = .{}; pair.scope = .{ .exported_members = &pair.map, @@ -3331,7 +3331,7 @@ pub fn NewParser_( p.allocator, "panic here", .{}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } p.log.level = .verbose; @@ -4532,9 +4532,9 @@ pub fn NewParser_( if ((symbol.kind == .ts_namespace or symbol.kind == .ts_enum) and !p.emitted_namespace_vars.contains(name_ref)) { - p.emitted_namespace_vars.putNoClobber(allocator, name_ref, {}) catch bun.outOfMemory(); + bun.handleOom(p.emitted_namespace_vars.putNoClobber(allocator, name_ref, {})); - var decls = allocator.alloc(G.Decl, 1) catch bun.outOfMemory(); + var decls = bun.handleOom(allocator.alloc(G.Decl, 1)); decls[0] = G.Decl{ .binding = p.b(B.Identifier{ .ref = name_ref }, name_loc) }; if (p.enclosing_namespace_arg_ref == null) { @@ -4545,7 +4545,7 @@ pub fn NewParser_( .decls = G.Decl.List.init(decls), .is_export = is_export, }, stmt_loc), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { // Nested namespace: "let" stmts.append( @@ -4553,7 +4553,7 @@ pub fn NewParser_( .kind = .k_let, .decls = G.Decl.List.init(decls), }, stmt_loc), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -4592,10 +4592,10 @@ pub fn NewParser_( }, name_loc); }; - var func_args = allocator.alloc(G.Arg, 1) catch bun.outOfMemory(); + var func_args = bun.handleOom(allocator.alloc(G.Arg, 1)); func_args[0] = .{ .binding = p.b(B.Identifier{ .ref = arg_ref }, name_loc) }; - var args_list = allocator.alloc(ExprNodeIndex, 1) catch bun.outOfMemory(); + var args_list = bun.handleOom(allocator.alloc(ExprNodeIndex, 1)); args_list[0] = arg_expr; // TODO: if unsupported features includes arrow functions @@ -5466,15 +5466,15 @@ pub fn NewParser_( pub fn generateTempRefWithScope(p: *P, default_name: ?string, scope: *Scope) Ref { const name = (if (p.willUseRenamer()) default_name else null) orelse brk: { p.temp_ref_count += 1; - break :brk std.fmt.allocPrint(p.allocator, "__bun_temp_ref_{x}$", .{p.temp_ref_count}) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrint(p.allocator, "__bun_temp_ref_{x}$", .{p.temp_ref_count})); }; - const ref = p.newSymbol(.other, name) catch bun.outOfMemory(); + const ref = bun.handleOom(p.newSymbol(.other, name)); p.temp_refs_to_declare.append(p.allocator, .{ .ref = ref, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); - scope.generated.append(p.allocator, &.{ref}) catch bun.outOfMemory(); + bun.handleOom(scope.generated.append(p.allocator, &.{ref})); return ref; } @@ -5560,7 +5560,7 @@ pub fn NewParser_( if (decl.value) |*decl_value| { const value_loc = decl_value.loc; p.recordUsage(ctx.stack_ref); - const args = p.allocator.alloc(Expr, 3) catch bun.outOfMemory(); + const args = bun.handleOom(p.allocator.alloc(Expr, 3)); args[0] = Expr{ .data = .{ .e_identifier = .{ .ref = ctx.stack_ref } }, .loc = stmt.loc, @@ -5594,14 +5594,14 @@ pub fn NewParser_( switch (stmt.data) { .s_directive, .s_import, .s_export_from, .s_export_star => { // These can't go in a try/catch block - result.append(stmt) catch bun.outOfMemory(); + bun.handleOom(result.append(stmt)); continue; }, .s_class => { if (stmt.data.s_class.is_export) { // can't go in try/catch; hoist out - result.append(stmt) catch bun.outOfMemory(); + bun.handleOom(result.append(stmt)); continue; } }, @@ -5612,14 +5612,14 @@ pub fn NewParser_( .s_export_clause => |data| { // Merge export clauses together - exports.appendSlice(data.items) catch bun.outOfMemory(); + bun.handleOom(exports.appendSlice(data.items)); continue; }, .s_function => { if (should_hoist_fns) { // Hoist function declarations for cross-file ESM references - result.append(stmt) catch bun.outOfMemory(); + bun.handleOom(result.append(stmt)); continue; } }, @@ -5638,7 +5638,7 @@ pub fn NewParser_( }, .alias = p.symbols.items[identifier.ref.inner_index].original_name, .alias_loc = decl.binding.loc, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); local.kind = .k_var; } } @@ -5669,12 +5669,12 @@ pub fn NewParser_( caught_ref, err_ref, has_err_ref, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); p.declared_symbols.ensureUnusedCapacity( p.allocator, // 5 to include the _promise decl later on: if (ctx.has_await_using) 5 else 4, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); p.declared_symbols.appendAssumeCapacity(.{ .is_top_level = is_top_level, .ref = ctx.stack_ref }); p.declared_symbols.appendAssumeCapacity(.{ .is_top_level = is_top_level, .ref = caught_ref }); p.declared_symbols.appendAssumeCapacity(.{ .is_top_level = is_top_level, .ref = err_ref }); @@ -5685,7 +5685,7 @@ pub fn NewParser_( p.recordUsage(ctx.stack_ref); p.recordUsage(err_ref); p.recordUsage(has_err_ref); - const args = p.allocator.alloc(Expr, 3) catch bun.outOfMemory(); + const args = bun.handleOom(p.allocator.alloc(Expr, 3)); args[0] = Expr{ .data = .{ .e_identifier = .{ .ref = ctx.stack_ref } }, .loc = loc, @@ -5704,7 +5704,7 @@ pub fn NewParser_( const finally_stmts = finally: { if (ctx.has_await_using) { const promise_ref = p.generateTempRef("_promise"); - scope.generated.append(p.allocator, &.{promise_ref}) catch bun.outOfMemory(); + bun.handleOom(scope.generated.append(p.allocator, &.{promise_ref})); p.declared_symbols.appendAssumeCapacity(.{ .is_top_level = is_top_level, .ref = promise_ref }); const promise_ref_expr = p.newExpr(E.Identifier{ .ref = promise_ref }, loc); @@ -5714,10 +5714,10 @@ pub fn NewParser_( }, loc); p.recordUsage(promise_ref); - const statements = p.allocator.alloc(Stmt, 2) catch bun.outOfMemory(); + const statements = bun.handleOom(p.allocator.alloc(Stmt, 2)); statements[0] = p.s(S.Local{ .decls = decls: { - const decls = p.allocator.alloc(Decl, 1) catch bun.outOfMemory(); + const decls = bun.handleOom(p.allocator.alloc(Decl, 1)); decls[0] = .{ .binding = p.b(B.Identifier{ .ref = promise_ref }, loc), .value = call_dispose, @@ -5742,7 +5742,7 @@ pub fn NewParser_( break :finally statements; } else { - const single = p.allocator.alloc(Stmt, 1) catch bun.outOfMemory(); + const single = bun.handleOom(p.allocator.alloc(Stmt, 1)); single[0] = p.s(S.SExpr{ .value = call_dispose }, call_dispose.loc); break :finally single; } @@ -5750,10 +5750,10 @@ pub fn NewParser_( // Wrap everything in a try/catch/finally block p.recordUsage(caught_ref); - result.ensureUnusedCapacity(2 + @as(usize, @intFromBool(exports.items.len > 0))) catch bun.outOfMemory(); + bun.handleOom(result.ensureUnusedCapacity(2 + @as(usize, @intFromBool(exports.items.len > 0)))); result.appendAssumeCapacity(p.s(S.Local{ .decls = decls: { - const decls = p.allocator.alloc(Decl, 1) catch bun.outOfMemory(); + const decls = bun.handleOom(p.allocator.alloc(Decl, 1)); decls[0] = .{ .binding = p.b(B.Identifier{ .ref = ctx.stack_ref }, loc), .value = p.newExpr(E.Array{}, loc), @@ -5768,10 +5768,10 @@ pub fn NewParser_( .catch_ = .{ .binding = p.b(B.Identifier{ .ref = caught_ref }, loc), .body = catch_body: { - const statements = p.allocator.alloc(Stmt, 1) catch bun.outOfMemory(); + const statements = bun.handleOom(p.allocator.alloc(Stmt, 1)); statements[0] = p.s(S.Local{ .decls = decls: { - const decls = p.allocator.alloc(Decl, 2) catch bun.outOfMemory(); + const decls = bun.handleOom(p.allocator.alloc(Decl, 2)); decls[0] = .{ .binding = p.b(B.Identifier{ .ref = err_ref }, loc), .value = p.newExpr(E.Identifier{ .ref = caught_ref }, loc), @@ -5827,7 +5827,7 @@ pub fn NewParser_( }, .e_array => |arr| for (arr.items.slice()) |*item| { if (item.data != .e_string) { - p.log.addError(p.source, item.loc, import_meta_hot_accept_err) catch bun.outOfMemory(); + bun.handleOom(p.log.addError(p.source, item.loc, import_meta_hot_accept_err)); continue; } item.data = p.rewriteImportMetaHotAcceptString(item.data.e_string, item.loc) orelse @@ -5840,7 +5840,7 @@ pub fn NewParser_( } fn rewriteImportMetaHotAcceptString(p: *P, str: *E.String, loc: logger.Loc) ?Expr.Data { - str.toUTF8(p.allocator) catch bun.outOfMemory(); + bun.handleOom(str.toUTF8(p.allocator)); const specifier = str.data; const import_record_index = for (p.import_records.items, 0..) |import_record, i| { @@ -5848,7 +5848,7 @@ pub fn NewParser_( break i; } } else { - p.log.addError(p.source, loc, import_meta_hot_accept_err) catch bun.outOfMemory(); + bun.handleOom(p.log.addError(p.source, loc, import_meta_hot_accept_err)); return null; }; @@ -5920,7 +5920,7 @@ pub fn NewParser_( val, module_path, p.newExpr(E.String{ .data = original_name }, logger.Loc.Empty), - }) catch bun.outOfMemory(), + }) catch |err| bun.handleOom(err), }, logger.Loc.Empty); } @@ -5952,7 +5952,7 @@ pub fn NewParser_( p.declared_symbols.append(p.allocator, .{ .is_top_level = true, .ref = ctx_storage.*.?.signature_cb, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break :init &(ctx_storage.*.?); }; @@ -5975,7 +5975,7 @@ pub fn NewParser_( .e_import_identifier, .e_commonjs_export_identifier, => |id, tag| { - const gop = ctx.user_hooks.getOrPut(p.allocator, id.ref) catch bun.outOfMemory(); + const gop = bun.handleOom(ctx.user_hooks.getOrPut(p.allocator, id.ref)); if (!gop.found_existing) { gop.value_ptr.* = .{ .data = @unionInit(Expr.Data, @tagName(tag), id), @@ -5998,7 +5998,7 @@ pub fn NewParser_( // re-allocated entirely to fit. Only one slot of new capacity // is used since we know this statement list is not going to be // appended to afterwards; This function is a post-visit handler. - const new_stmts = p.allocator.alloc(Stmt, stmts.items.len + 1) catch bun.outOfMemory(); + const new_stmts = bun.handleOom(p.allocator.alloc(Stmt, stmts.items.len + 1)); @memcpy(new_stmts[1..], stmts.items); stmts.deinit(); stmts.* = ListManaged(Stmt).fromOwnedSlice(p.allocator, new_stmts); @@ -6026,14 +6026,14 @@ pub fn NewParser_( .value = p.newExpr(E.Call{ .target = Expr.initIdentifier(p.react_refresh.create_signature_ref, loc), }, loc), - }}) catch bun.outOfMemory() }, loc); + }}) catch |err| bun.handleOom(err) }, loc); } pub fn getReactRefreshHookSignalInit(p: *P, ctx: *ReactRefresh.HookContext, function_with_hook_calls: Expr) Expr { const loc = logger.Loc.Empty; const final = ctx.hasher.final(); - const hash_data = p.allocator.alloc(u8, comptime bun.base64.encodeLenFromSize(@sizeOf(@TypeOf(final)))) catch bun.outOfMemory(); + const hash_data = bun.handleOom(p.allocator.alloc(u8, comptime bun.base64.encodeLenFromSize(@sizeOf(@TypeOf(final))))); bun.assert(bun.base64.encode(hash_data, std.mem.asBytes(&final)) == hash_data.len); const have_custom_hooks = ctx.user_hooks.count() > 0; @@ -6044,7 +6044,7 @@ pub fn NewParser_( 2 + @as(usize, @intFromBool(have_force_arg)) + @as(usize, @intFromBool(have_custom_hooks)), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); args[0] = function_with_hook_calls; args[1] = p.newExpr(E.String{ .data = hash_data }, loc); @@ -6059,7 +6059,7 @@ pub fn NewParser_( p.s(S.Return{ .value = p.newExpr(E.Array{ .items = ExprNodeList.init(ctx.user_hooks.values()), }, loc) }, loc), - }) catch bun.outOfMemory(), + }) catch |err| bun.handleOom(err), .loc = loc, }, .prefer_expr = true, @@ -6198,7 +6198,7 @@ pub fn NewParser_( // }) // // which is then called in `evaluateCommonJSModuleOnce` - var args = allocator.alloc(Arg, 5 + @as(usize, @intFromBool(p.has_import_meta))) catch bun.outOfMemory(); + var args = bun.handleOom(allocator.alloc(Arg, 5 + @as(usize, @intFromBool(p.has_import_meta)))); args[0..5].* = .{ Arg{ .binding = p.b(B.Identifier{ .ref = p.exports_ref }, logger.Loc.Empty) }, Arg{ .binding = p.b(B.Identifier{ .ref = p.require_ref }, logger.Loc.Empty) }, @@ -6207,7 +6207,7 @@ pub fn NewParser_( Arg{ .binding = p.b(B.Identifier{ .ref = p.dirname_ref }, logger.Loc.Empty) }, }; if (p.has_import_meta) { - p.import_meta_ref = p.newSymbol(.other, "$Bun_import_meta") catch bun.outOfMemory(); + p.import_meta_ref = bun.handleOom(p.newSymbol(.other, "$Bun_import_meta")); args[5] = Arg{ .binding = p.b(B.Identifier{ .ref = p.import_meta_ref }, logger.Loc.Empty) }; } @@ -6223,7 +6223,7 @@ pub fn NewParser_( total_stmts_count += @as(usize, @intCast(@intFromBool(preserve_strict_mode))); - const stmts_to_copy = allocator.alloc(Stmt, total_stmts_count) catch bun.outOfMemory(); + const stmts_to_copy = bun.handleOom(allocator.alloc(Stmt, total_stmts_count)); { var remaining_stmts = stmts_to_copy; if (preserve_strict_mode) { @@ -6257,7 +6257,7 @@ pub fn NewParser_( logger.Loc.Empty, ); - var top_level_stmts = p.allocator.alloc(Stmt, 1) catch bun.outOfMemory(); + var top_level_stmts = bun.handleOom(p.allocator.alloc(Stmt, 1)); top_level_stmts[0] = p.s( S.SExpr{ .value = wrapper, @@ -6337,8 +6337,8 @@ pub fn NewParser_( p.allocator, "require_{any}", .{p.source.fmtIdentifier()}, - ) catch bun.outOfMemory(), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err), + ) catch |err| bun.handleOom(err); } break :brk Ref.None; diff --git a/src/ast/Parser.zig b/src/ast/Parser.zig index d2b7bcae9a..ff68c2e000 100644 --- a/src/ast/Parser.zig +++ b/src/ast/Parser.zig @@ -446,7 +446,7 @@ pub const Parser = struct { if (p.options.bundle) { // The bundler requires a part for generated module wrappers. This // part must be at the start as it is referred to by index. - before.append(js_ast.Part{}) catch bun.outOfMemory(); + bun.handleOom(before.append(js_ast.Part{})); } // --inspect-brk @@ -460,7 +460,7 @@ pub const Parser = struct { js_ast.Part{ .stmts = debugger_stmts, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } // When "using" declarations appear at the top level, we change all TDZ @@ -713,7 +713,7 @@ pub const Parser = struct { var import_part_stmts = remaining_stmts[0..1]; remaining_stmts = remaining_stmts[1..]; - p.module_scope.generated.push(p.allocator, deferred_import.namespace.ref.?) catch bun.outOfMemory(); + bun.handleOom(p.module_scope.generated.push(p.allocator, deferred_import.namespace.ref.?)); import_part_stmts[0] = Stmt.alloc( S.Import, diff --git a/src/ast/SideEffects.zig b/src/ast/SideEffects.zig index d0457809f2..39909204e5 100644 --- a/src/ast/SideEffects.zig +++ b/src/ast/SideEffects.zig @@ -347,7 +347,7 @@ pub const SideEffects = enum(u1) { const stack_bottom = stack.items.len; defer stack.shrinkRetainingCapacity(stack_bottom); - stack.append(.{ .bin = expr.data.e_binary }) catch bun.outOfMemory(); + bun.handleOom(stack.append(.{ .bin = expr.data.e_binary })); // Build stack up of expressions var left: Expr = expr.data.e_binary.left; @@ -357,7 +357,7 @@ pub const SideEffects = enum(u1) { .bin_strict_ne, .bin_comma, => { - stack.append(.{ .bin = left_bin }) catch bun.outOfMemory(); + bun.handleOom(stack.append(.{ .bin = left_bin })); left = left_bin.left; }, else => break, diff --git a/src/ast/foldStringAddition.zig b/src/ast/foldStringAddition.zig index 749cf6003b..ec2310fd97 100644 --- a/src/ast/foldStringAddition.zig +++ b/src/ast/foldStringAddition.zig @@ -182,7 +182,7 @@ pub fn foldStringAddition(l: Expr, r: Expr, allocator: std.mem.Allocator, kind: allocator, E.TemplatePart, &.{ left.parts, right.parts }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return lhs; } } else { diff --git a/src/ast/maybe.zig b/src/ast/maybe.zig index 0dce6e63ac..0c620c2962 100644 --- a/src/ast/maybe.zig +++ b/src/ast/maybe.zig @@ -459,12 +459,12 @@ pub fn AstMaybe( p.allocator, id.ref, .{}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const inner_use = gop.value_ptr.getOrPutValue( p.allocator, name, .{}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); inner_use.value_ptr.count_estimate += 1; } }, @@ -572,8 +572,8 @@ pub fn AstMaybe( p.allocator, "import.meta.hot.{s} does not exist", .{name}, - ) catch bun.outOfMemory(), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err), + ) catch |err| bun.handleOom(err); return .{ .data = .e_undefined, .loc = loc }; } }, diff --git a/src/ast/parseProperty.zig b/src/ast/parseProperty.zig index 6ebbffa8f3..9ca95c0b74 100644 --- a/src/ast/parseProperty.zig +++ b/src/ast/parseProperty.zig @@ -347,7 +347,7 @@ pub fn ParseProperty( // Handle invalid identifiers in property names // https://github.com/oven-sh/bun/issues/12039 if (p.lexer.token == .t_syntax_error) { - p.log.addRangeErrorFmt(p.source, name_range, p.allocator, "Unexpected {}", .{bun.fmt.quote(name)}) catch bun.outOfMemory(); + bun.handleOom(p.log.addRangeErrorFmt(p.source, name_range, p.allocator, "Unexpected {}", .{bun.fmt.quote(name)})); return error.SyntaxError; } diff --git a/src/ast/parseStmt.zig b/src/ast/parseStmt.zig index 8d53d35b65..274f64eaf9 100644 --- a/src/ast/parseStmt.zig +++ b/src/ast/parseStmt.zig @@ -376,8 +376,8 @@ pub fn ParseStmt( .{ path_name.fmtIdentifier(), }, - ) catch bun.outOfMemory(), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err), + ) catch |err| bun.handleOom(err); if (comptime track_symbol_usage_during_parse_pass) { // In the scan pass, we need _some_ way of knowing *not* to mark as unused diff --git a/src/ast/parseTypescript.zig b/src/ast/parseTypescript.zig index c024174346..bf6793aa25 100644 --- a/src/ast/parseTypescript.zig +++ b/src/ast/parseTypescript.zig @@ -210,7 +210,7 @@ pub fn ParseTypescript( p.popScope(); if (!opts.is_typescript_declare) { - name.ref = p.declareSymbol(.ts_namespace, name_loc, name_text) catch bun.outOfMemory(); + name.ref = bun.handleOom(p.declareSymbol(.ts_namespace, name_loc, name_text)); try p.ref_to_ts_namespace_member.put(p.allocator, name.ref.?, ns_member_data); } @@ -288,7 +288,7 @@ pub fn ParseTypescript( name.ref = try p.declareSymbol(.ts_enum, name_loc, name_text); _ = try p.pushScopeForParsePass(.entry, loc); p.current_scope.ts_namespace = ts_namespace; - p.ref_to_ts_namespace_member.putNoClobber(p.allocator, name.ref.?, enum_member_data) catch bun.outOfMemory(); + bun.handleOom(p.ref_to_ts_namespace_member.putNoClobber(p.allocator, name.ref.?, enum_member_data)); } try p.lexer.expect(.t_open_brace); @@ -329,7 +329,7 @@ pub fn ParseTypescript( exported_members.put(p.allocator, value.name, .{ .loc = value.loc, .data = .enum_property, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); if (p.lexer.token != .t_comma and p.lexer.token != .t_semicolon) { break; @@ -376,7 +376,7 @@ pub fn ParseTypescript( } else { arg_ref = p.declareSymbol(.hoisted, name_loc, name_text) catch unreachable; } - p.ref_to_ts_namespace_member.put(p.allocator, arg_ref, enum_member_data) catch bun.outOfMemory(); + bun.handleOom(p.ref_to_ts_namespace_member.put(p.allocator, arg_ref, enum_member_data)); ts_namespace.arg_ref = arg_ref; p.popScope(); @@ -406,7 +406,7 @@ pub fn ParseTypescript( if (i != null) count += 1; } - const items = p.allocator.alloc(ScopeOrder, count) catch bun.outOfMemory(); + const items = bun.handleOom(p.allocator.alloc(ScopeOrder, count)); var i: usize = 0; for (p.scopes_in_order.items[scope_index..]) |item| { items[i] = item orelse continue; @@ -414,7 +414,7 @@ pub fn ParseTypescript( } break :scope_order_clone items; }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return p.s(S.Enum{ .name = name, diff --git a/src/ast/visit.zig b/src/ast/visit.zig index 2071389486..e37b74e4f2 100644 --- a/src/ast/visit.zig +++ b/src/ast/visit.zig @@ -860,11 +860,11 @@ pub fn Visit( // Merge the two identifiers back into a single one p.symbols.items[hoisted_ref.innerIndex()].link = name_ref; } - non_fn_stmts.append(stmt) catch bun.outOfMemory(); + bun.handleOom(non_fn_stmts.append(stmt)); continue; } - const gpe = fn_stmts.getOrPut(name_ref) catch bun.outOfMemory(); + const gpe = bun.handleOom(fn_stmts.getOrPut(name_ref)); var index = gpe.value_ptr.*; if (!gpe.found_existing) { index = @as(u32, @intCast(let_decls.items.len)); @@ -889,7 +889,7 @@ pub fn Visit( }, data.func.name.?.loc, ), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } } diff --git a/src/ast/visitExpr.zig b/src/ast/visitExpr.zig index 7c508a81e9..4c0f42fd56 100644 --- a/src/ast/visitExpr.zig +++ b/src/ast/visitExpr.zig @@ -311,12 +311,12 @@ pub fn VisitExpr( .items = e_.children, .is_single_line = e_.children.len < 2, }, e_.close_tag_loc), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } else if (e_.children.len == 1) { props.append(allocator, G.Property{ .key = children_key, .value = e_.children.ptr[0], - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } // Either: @@ -490,7 +490,7 @@ pub fn VisitExpr( // Note that we only append to the stack (and therefore allocate memory // on the heap) when there are nested binary expressions. A single binary // expression doesn't add anything to the stack. - p.binary_expression_stack.append(v) catch bun.outOfMemory(); + bun.handleOom(p.binary_expression_stack.append(v)); v = BinaryExpressionVisitor{ .e = left_binary.?, .loc = left.loc, @@ -1449,8 +1449,8 @@ pub fn VisitExpr( p.allocator, "\"useState\" is not available in a server component. If you need interactivity, consider converting part of this to a Client Component (by adding `\"use client\";` to the top of the file).", .{}, - ) catch bun.outOfMemory(), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err), + ) catch |err| bun.handleOom(err); } } } @@ -1542,7 +1542,7 @@ pub fn VisitExpr( if (react_hook_data) |*hook| try_mark_hook: { const stmts = p.nearest_stmt_list orelse break :try_mark_hook; - stmts.append(p.getReactRefreshHookSignalDecl(hook.signature_cb)) catch bun.outOfMemory(); + bun.handleOom(stmts.append(p.getReactRefreshHookSignalDecl(hook.signature_cb))); p.handleReactRefreshPostVisitFunctionBody(&stmts_list, hook); e_.body.stmts = stmts_list.items; @@ -1568,7 +1568,7 @@ pub fn VisitExpr( if (react_hook_data) |*hook| try_mark_hook: { const stmts = p.nearest_stmt_list orelse break :try_mark_hook; - stmts.append(p.getReactRefreshHookSignalDecl(hook.signature_cb)) catch bun.outOfMemory(); + bun.handleOom(stmts.append(p.getReactRefreshHookSignalDecl(hook.signature_cb))); final_expr = p.getReactRefreshHookSignalInit(hook, expr); } diff --git a/src/ast/visitStmt.zig b/src/ast/visitStmt.zig index 265b1a543b..4de08b6d57 100644 --- a/src/ast/visitStmt.zig +++ b/src/ast/visitStmt.zig @@ -287,7 +287,7 @@ pub fn VisitStmt( if (p.current_scope.parent == null and p.will_wrap_module_in_try_catch_for_using) { try stmts.ensureUnusedCapacity(2); - const decls = p.allocator.alloc(G.Decl, 1) catch bun.outOfMemory(); + const decls = bun.handleOom(p.allocator.alloc(G.Decl, 1)); decls[0] = .{ .binding = p.b(B.Identifier{ .ref = data.default_name.ref.? }, data.default_name.loc), .value = data.value.expr, @@ -295,7 +295,7 @@ pub fn VisitStmt( stmts.appendAssumeCapacity(p.s(S.Local{ .decls = G.Decl.List.init(decls), }, stmt.loc)); - const items = p.allocator.alloc(js_ast.ClauseItem, 1) catch bun.outOfMemory(); + const items = bun.handleOom(p.allocator.alloc(js_ast.ClauseItem, 1)); items[0] = js_ast.ClauseItem{ .alias = "default", .alias_loc = data.default_name.loc, @@ -343,7 +343,7 @@ pub fn VisitStmt( } if (react_hook_data) |*hook| { - stmts.append(p.getReactRefreshHookSignalDecl(hook.signature_cb)) catch bun.outOfMemory(); + bun.handleOom(stmts.append(p.getReactRefreshHookSignalDecl(hook.signature_cb))); data.value = .{ .expr = p.getReactRefreshHookSignalInit(hook, p.newExpr( @@ -402,7 +402,7 @@ pub fn VisitStmt( .value = data.value.expr, }, }), - }, stmt.loc)) catch bun.outOfMemory(); + }, stmt.loc)) catch |err| bun.handleOom(err); data.value = .{ .expr = .initIdentifier(ref_to_use, stmt.loc) }; @@ -515,7 +515,7 @@ pub fn VisitStmt( data.func.flags.remove(.is_export); const enclosing_namespace_arg_ref = p.enclosing_namespace_arg_ref orelse bun.outOfMemory(); - stmts.ensureUnusedCapacity(3) catch bun.outOfMemory(); + bun.handleOom(stmts.ensureUnusedCapacity(3)); stmts.appendAssumeCapacity(stmt.*); stmts.appendAssumeCapacity(Stmt.assign( p.newExpr(E.Dot{ @@ -547,7 +547,7 @@ pub fn VisitStmt( }}), }, stmt.loc)); } else { - stmts.append(stmt.*) catch bun.outOfMemory(); + bun.handleOom(stmts.append(stmt.*)); } } else if (mark_as_dead) { if (p.options.features.replace_exports.getPtr(original_name)) |replacement| { @@ -1200,7 +1200,7 @@ pub fn VisitStmt( const first = p.s(S.Local{ .kind = init2.kind, .decls = bindings: { - const decls = p.allocator.alloc(G.Decl, 1) catch bun.outOfMemory(); + const decls = bun.handleOom(p.allocator.alloc(G.Decl, 1)); decls[0] = .{ .binding = p.b(B.Identifier{ .ref = id.ref }, loc), .value = p.newExpr(E.Identifier{ .ref = temp_ref }, loc), @@ -1210,7 +1210,7 @@ pub fn VisitStmt( }, loc); const length = if (data.body.data == .s_block) data.body.data.s_block.stmts.len else 1; - const statements = p.allocator.alloc(Stmt, 1 + length) catch bun.outOfMemory(); + const statements = bun.handleOom(p.allocator.alloc(Stmt, 1 + length)); statements[0] = first; if (data.body.data == .s_block) { @memcpy(statements[1..], data.body.data.s_block.stmts); @@ -1315,10 +1315,10 @@ pub fn VisitStmt( try p.top_level_enums.append(p.allocator, data.name.ref.?); } - p.recordDeclaredSymbol(data.name.ref.?) catch bun.outOfMemory(); - p.pushScopeForVisitPass(.entry, stmt.loc) catch bun.outOfMemory(); + bun.handleOom(p.recordDeclaredSymbol(data.name.ref.?)); + bun.handleOom(p.pushScopeForVisitPass(.entry, stmt.loc)); defer p.popScope(); - p.recordDeclaredSymbol(data.arg) catch bun.outOfMemory(); + bun.handleOom(p.recordDeclaredSymbol(data.arg)); const allocator = p.allocator; // Scan ahead for any variables inside this namespace. This must be done @@ -1327,7 +1327,7 @@ pub fn VisitStmt( // We need to convert the uses into property accesses on the namespace. for (data.values) |value| { if (value.ref.isValid()) { - p.is_exported_inside_namespace.put(allocator, value.ref, data.arg) catch bun.outOfMemory(); + bun.handleOom(p.is_exported_inside_namespace.put(allocator, value.ref, data.arg)); } } @@ -1336,7 +1336,7 @@ pub fn VisitStmt( // without initializers are initialized to undefined. var next_numeric_value: ?f64 = 0.0; - var value_exprs = ListManaged(Expr).initCapacity(allocator, data.values.len) catch bun.outOfMemory(); + var value_exprs = bun.handleOom(ListManaged(Expr).initCapacity(allocator, data.values.len)); var all_values_are_pure = true; @@ -1373,7 +1373,7 @@ pub fn VisitStmt( p.allocator, value.ref, .{ .enum_number = num.value }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); next_numeric_value = num.value + 1.0; }, @@ -1386,7 +1386,7 @@ pub fn VisitStmt( p.allocator, value.ref, .{ .enum_string = str }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); }, else => { if (visited.knownPrimitive() == .string) { @@ -1409,7 +1409,7 @@ pub fn VisitStmt( p.allocator, value.ref, .{ .enum_number = num }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { value.value = p.newExpr(E.Undefined{}, value.loc); } @@ -1451,7 +1451,7 @@ pub fn VisitStmt( // String-valued enums do not form a two-way map if (has_string_value) { - value_exprs.append(assign_target) catch bun.outOfMemory(); + bun.handleOom(value_exprs.append(assign_target)); } else { // "Enum[assignTarget] = 'Name'" value_exprs.append( @@ -1465,7 +1465,7 @@ pub fn VisitStmt( }, value.loc), name_as_e_string.?, ), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); p.recordUsage(data.arg); } } diff --git a/src/bake.zig b/src/bake.zig index 6b0ff69c76..d6161ec8d9 100644 --- a/src/bake.zig +++ b/src/bake.zig @@ -93,7 +93,7 @@ pub const StringRefList = struct { pub const empty: StringRefList = .{ .strings = .{} }; pub fn track(al: *StringRefList, str: ZigString.Slice) []const u8 { - al.strings.append(bun.default_allocator, str) catch bun.outOfMemory(); + bun.handleOom(al.strings.append(bun.default_allocator, str)); return str.slice(); } @@ -261,7 +261,7 @@ pub const Framework = struct { .{ .code = bun.runtimeEmbedFile(.src, "bake/bun-framework-react/client.tsx") }, .{ .code = bun.runtimeEmbedFile(.src, "bake/bun-framework-react/server.tsx") }, .{ .code = bun.runtimeEmbedFile(.src, "bake/bun-framework-react/ssr.tsx") }, - }) catch bun.outOfMemory(), + }) catch |err| bun.handleOom(err), }; } diff --git a/src/bake/DevServer.zig b/src/bake/DevServer.zig index 54b7de4381..aec224d777 100644 --- a/src/bake/DevServer.zig +++ b/src/bake/DevServer.zig @@ -841,7 +841,7 @@ fn onJsRequest(dev: *DevServer, req: *Request, resp: AnyResponse) void { arena.allocator(), source_id.kind, dev.allocator(), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const response = StaticRoute.initFromAnyBlob(&.fromOwnedSlice(dev.allocator(), json_bytes), .{ .server = dev.server, .mime_type = &.json, @@ -1035,7 +1035,7 @@ fn ensureRouteIsBundled( entry_points, false, std.time.Timer.start() catch @panic("timers unsupported"), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } dev.routeBundlePtr(route_bundle_index).server_state = .bundling; @@ -1168,7 +1168,7 @@ fn appendRouteEntryPointsIfNotStale(dev: *DevServer, entry_points: *EntryPointLi for (map.keys()) |abs_path| { const file = (dev.client_graph.bundled_files.get(abs_path) orelse continue).unpack(); if (file.kind() == .css) - entry_points.appendCss(alloc, abs_path) catch bun.outOfMemory(); + bun.handleOom(entry_points.appendCss(alloc, abs_path)); } } } @@ -1298,7 +1298,7 @@ fn onFrameworkRequestWithBundle( const str = bun.String.createFormat(client_prefix ++ "/route-{}{}.js", .{ std.fmt.fmtSliceHexLower(std.mem.asBytes(&bundle_index)), std.fmt.fmtSliceHexLower(std.mem.asBytes(&generation)), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); defer str.deref(); const js = str.toJS(dev.vm.global); bundle.cached_client_bundle_url = .create(js, dev.vm.global); @@ -1306,7 +1306,7 @@ fn onFrameworkRequestWithBundle( }, // styles bundle.cached_css_file_array.get() orelse arr: { - const js = dev.generateCssJSArray(route_bundle) catch bun.outOfMemory(); + const js = try dev.generateCssJSArray(route_bundle); bundle.cached_css_file_array = .create(js, dev.vm.global); break :arr js; }, @@ -1322,7 +1322,7 @@ fn onHtmlRequestWithBundle(dev: *DevServer, route_bundle_index: RouteBundle.Inde const html = &route_bundle.data.html; const blob = html.cached_response orelse generate: { - const payload = generateHTMLPayload(dev, route_bundle_index, route_bundle, html) catch bun.outOfMemory(); + const payload = bun.handleOom(generateHTMLPayload(dev, route_bundle_index, route_bundle, html)); errdefer dev.allocator().free(payload); html.cached_response = StaticRoute.initFromAnyBlob( @@ -1436,7 +1436,7 @@ fn generateJavaScriptCodeForHTMLFile( ) bun.OOM![]const u8 { var sfa_state = std.heap.stackFallback(65536, dev.allocator()); const sfa = sfa_state.get(); - var array = std.ArrayListUnmanaged(u8).initCapacity(sfa, 65536) catch bun.outOfMemory(); + var array = bun.handleOom(std.ArrayListUnmanaged(u8).initCapacity(sfa, 65536)); defer array.deinit(sfa); const w = array.writer(sfa); @@ -1477,7 +1477,7 @@ fn generateJavaScriptCodeForHTMLFile( pub fn onJsRequestWithBundle(dev: *DevServer, bundle_index: RouteBundle.Index, resp: AnyResponse, method: bun.http.Method) void { const route_bundle = dev.routeBundlePtr(bundle_index); const blob = route_bundle.client_bundle orelse generate: { - const payload = dev.generateClientBundle(route_bundle) catch bun.outOfMemory(); + const payload = bun.handleOom(dev.generateClientBundle(route_bundle)); errdefer dev.allocator().free(payload); route_bundle.client_bundle = StaticRoute.initFromAnyBlob( &.fromOwnedSlice(dev.allocator(), payload), @@ -2492,7 +2492,7 @@ pub fn finalizeBundle( while (it.next()) |socket_ptr_ptr| { const socket: *HmrSocket = socket_ptr_ptr.*; if (socket.subscriptions.hot_update) { - const entry = socket.referenced_source_maps.getOrPut(dev.allocator(), script_id) catch bun.outOfMemory(); + const entry = bun.handleOom(socket.referenced_source_maps.getOrPut(dev.allocator(), script_id)); if (!entry.found_existing) { sockets += 1; } else { @@ -2692,11 +2692,11 @@ fn startNextBundleIfPresent(dev: *DevServer) void { for (dev.next_bundle.route_queue.keys()) |route_bundle_index| { const rb = dev.routeBundlePtr(route_bundle_index); rb.server_state = .bundling; - dev.appendRouteEntryPointsIfNotStale(&entry_points, temp_alloc, route_bundle_index) catch bun.outOfMemory(); + bun.handleOom(dev.appendRouteEntryPointsIfNotStale(&entry_points, temp_alloc, route_bundle_index)); } if (entry_points.set.count() > 0) { - dev.startAsyncBundle(entry_points, is_reload, timer) catch bun.outOfMemory(); + bun.handleOom(dev.startAsyncBundle(entry_points, is_reload, timer)); } dev.next_bundle.route_queue.clearRetainingCapacity(); @@ -2817,11 +2817,14 @@ fn onRequest(dev: *DevServer, req: *Request, resp: anytype) void { var params: FrameworkRouter.MatchedParams = undefined; if (dev.router.matchSlow(req.url(), ¶ms)) |route_index| { dev.ensureRouteIsBundled( - dev.getOrPutRouteBundle(.{ .framework = route_index }) catch bun.outOfMemory(), + bun.handleOom(dev.getOrPutRouteBundle(.{ .framework = route_index })), .server_handler, req, AnyResponse.init(resp), - ) catch bun.outOfMemory(); + ) catch |err| switch (err) { + error.JSError => dev.vm.global.reportActiveExceptionAsUnhandled(err), + error.OutOfMemory => bun.outOfMemory(), + }; return; } @@ -2833,8 +2836,16 @@ fn onRequest(dev: *DevServer, req: *Request, resp: anytype) void { sendBuiltInNotFound(resp); } -pub fn respondForHTMLBundle(dev: *DevServer, html: *HTMLBundle.HTMLBundleRoute, req: *uws.Request, resp: AnyResponse) !void { - try dev.ensureRouteIsBundled(try dev.getOrPutRouteBundle(.{ .html = html }), .bundled_html_page, req, resp); +pub fn respondForHTMLBundle(dev: *DevServer, html: *HTMLBundle.HTMLBundleRoute, req: *uws.Request, resp: AnyResponse) bun.OOM!void { + dev.ensureRouteIsBundled( + try dev.getOrPutRouteBundle(.{ .html = html }), + .bundled_html_page, + req, + resp, + ) catch |err| switch (err) { + error.JSError => dev.vm.global.reportActiveExceptionAsUnhandled(err), + else => |other| return other, + }; } fn getOrPutRouteBundle(dev: *DevServer, route: RouteBundle.UnresolvedIndex) !RouteBundle.Index { @@ -3374,7 +3385,7 @@ pub fn onWebSocketUpgrade( assert(id == 0); const dw = HmrSocket.new(dev, res); - dev.active_websocket_connections.put(dev.allocator(), dw, {}) catch bun.outOfMemory(); + bun.handleOom(dev.active_websocket_connections.put(dev.allocator(), dw, {})); _ = res.upgrade( *HmrSocket, dw, @@ -3577,10 +3588,10 @@ pub const HmrSocket = @import("./DevServer/HmrSocket.zig"); pub fn routeToBundleIndexSlow(dev: *DevServer, pattern: []const u8) ?RouteBundle.Index { var params: FrameworkRouter.MatchedParams = undefined; if (dev.router.matchSlow(pattern, ¶ms)) |route_index| { - return dev.getOrPutRouteBundle(.{ .framework = route_index }) catch bun.outOfMemory(); + return bun.handleOom(dev.getOrPutRouteBundle(.{ .framework = route_index })); } if (dev.html_router.get(pattern)) |html| { - return dev.getOrPutRouteBundle(.{ .html = html }) catch bun.outOfMemory(); + return bun.handleOom(dev.getOrPutRouteBundle(.{ .html = html })); } return null; } diff --git a/src/bake/DevServer/HmrSocket.zig b/src/bake/DevServer/HmrSocket.zig index 7330a080aa..04aaef1ac9 100644 --- a/src/bake/DevServer/HmrSocket.zig +++ b/src/bake/DevServer/HmrSocket.zig @@ -164,7 +164,7 @@ pub fn onMessage(s: *HmrSocket, ws: AnyWebSocket, msg: []const u8, opcode: uws.O event.entry_points, true, std.time.Timer.start() catch @panic("timers unsupported"), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); event.entry_points.deinit(s.dev.allocator()); }, diff --git a/src/bake/DevServer/HotReloadEvent.zig b/src/bake/DevServer/HotReloadEvent.zig index e956c2540f..3b43ded0b1 100644 --- a/src/bake/DevServer/HotReloadEvent.zig +++ b/src/bake/DevServer/HotReloadEvent.zig @@ -52,12 +52,12 @@ pub fn isEmpty(ev: *const HotReloadEvent) bool { } pub fn appendFile(event: *HotReloadEvent, allocator: Allocator, file_path: []const u8) void { - _ = event.files.getOrPut(allocator, file_path) catch bun.outOfMemory(); + _ = bun.handleOom(event.files.getOrPut(allocator, file_path)); } pub fn appendDir(event: *HotReloadEvent, allocator: Allocator, dir_path: []const u8, maybe_sub_path: ?[]const u8) void { if (dir_path.len == 0) return; - _ = event.dirs.getOrPut(allocator, dir_path) catch bun.outOfMemory(); + _ = bun.handleOom(event.dirs.getOrPut(allocator, dir_path)); const sub_path = maybe_sub_path orelse return; if (sub_path.len == 0) return; @@ -67,7 +67,7 @@ pub fn appendDir(event: *HotReloadEvent, allocator: Allocator, dir_path: []const const starts_with_sep = platform.isSeparator(sub_path[0]); const sep_offset: i32 = if (ends_with_sep and starts_with_sep) -1 else 1; - event.extra_files.ensureUnusedCapacity(allocator, @intCast(@as(i32, @intCast(dir_path.len + sub_path.len)) + sep_offset + 1)) catch bun.outOfMemory(); + bun.handleOom(event.extra_files.ensureUnusedCapacity(allocator, @intCast(@as(i32, @intCast(dir_path.len + sub_path.len)) + sep_offset + 1))); event.extra_files.appendSliceAssumeCapacity(if (ends_with_sep) dir_path[0 .. dir_path.len - 1] else dir_path); event.extra_files.appendAssumeCapacity(platform.separator()); event.extra_files.appendSliceAssumeCapacity(sub_path); @@ -111,7 +111,7 @@ pub fn processFileList( // into BundleV2 is too complicated. the resolution is // cached, anyways. event.appendFile(dev.allocator(), dep.source_file_path); - dev.directory_watchers.freeDependencyIndex(dev.allocator(), index) catch bun.outOfMemory(); + bun.handleOom(dev.directory_watchers.freeDependencyIndex(dev.allocator(), index)); } else { // rebuild a new linked list for unaffected files dep.next = new_chain; @@ -130,16 +130,16 @@ pub fn processFileList( var rest_extra = event.extra_files.items; while (bun.strings.indexOfChar(rest_extra, 0)) |str| { - event.files.put(dev.allocator(), rest_extra[0..str], {}) catch bun.outOfMemory(); + bun.handleOom(event.files.put(dev.allocator(), rest_extra[0..str], {})); rest_extra = rest_extra[str + 1 ..]; } if (rest_extra.len > 0) { - event.files.put(dev.allocator(), rest_extra, {}) catch bun.outOfMemory(); + bun.handleOom(event.files.put(dev.allocator(), rest_extra, {})); } const changed_file_paths = event.files.keys(); inline for (.{ &dev.server_graph, &dev.client_graph }) |g| { - g.invalidate(changed_file_paths, entry_points, temp_alloc) catch bun.outOfMemory(); + bun.handleOom(g.invalidate(changed_file_paths, entry_points, temp_alloc)); } if (entry_points.set.count() == 0) { @@ -165,7 +165,7 @@ pub fn processFileList( for (map.keys()) |abs_path| { const file = (dev.client_graph.bundled_files.get(abs_path) orelse continue).unpack(); if (file.kind() == .css) - entry_points.appendCss(temp_alloc, abs_path) catch bun.outOfMemory(); + bun.handleOom(entry_points.appendCss(temp_alloc, abs_path)); } } } @@ -212,7 +212,7 @@ pub fn run(first: *HotReloadEvent) void { switch (dev.testing_batch_events) { .disabled => {}, .enabled => |*ev| { - ev.append(dev, entry_points) catch bun.outOfMemory(); + bun.handleOom(ev.append(dev, entry_points)); dev.publish(.testing_watch_synchronization, &.{ MessageId.testing_watch_synchronization.char(), 1, diff --git a/src/bake/DevServer/IncrementalGraph.zig b/src/bake/DevServer/IncrementalGraph.zig index efba4ac533..29ab77fb52 100644 --- a/src/bake/DevServer/IncrementalGraph.zig +++ b/src/bake/DevServer/IncrementalGraph.zig @@ -1486,7 +1486,7 @@ pub fn IncrementalGraph(comptime side: bake.Side) type { .client => .browser, .server => .bun, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } // Bust the resolution caches of the dir containing this file, diff --git a/src/bake/DevServer/SourceMapStore.zig b/src/bake/DevServer/SourceMapStore.zig index b22837ddcc..ae840474f0 100644 --- a/src/bake/DevServer/SourceMapStore.zig +++ b/src/bake/DevServer/SourceMapStore.zig @@ -491,7 +491,7 @@ pub fn getParsedSourceMap(store: *Self, script_id: Key, arena: Allocator, gpa: A const entry = &store.entries.values()[index]; const script_id_decoded: SourceId = @bitCast(script_id.get()); - const vlq_bytes = entry.renderMappings(script_id_decoded.kind, arena, arena) catch bun.outOfMemory(); + const vlq_bytes = bun.handleOom(entry.renderMappings(script_id_decoded.kind, arena, arena)); switch (SourceMap.Mapping.parse( gpa, diff --git a/src/bun.js/Debugger.zig b/src/bun.js/Debugger.zig index 2a634f6594..99a3a9918a 100644 --- a/src/bun.js/Debugger.zig +++ b/src/bun.js/Debugger.zig @@ -56,7 +56,7 @@ pub fn waitForDebuggerIfNecessary(this: *VirtualMachine) void { // TODO: remove this when tickWithTimeout actually works properly on Windows. if (debugger.wait_for_connection == .shortly) { uv.uv_update_time(this.uvLoop()); - var timer = bun.default_allocator.create(uv.Timer) catch bun.outOfMemory(); + var timer = bun.handleOom(bun.default_allocator.create(uv.Timer)); timer.* = std.mem.zeroes(uv.Timer); timer.init(this.uvLoop()); const onDebuggerTimer = struct { diff --git a/src/bun.js/ModuleLoader.zig b/src/bun.js/ModuleLoader.zig index 61c4c5ce84..378a6bb5c2 100644 --- a/src/bun.js/ModuleLoader.zig +++ b/src/bun.js/ModuleLoader.zig @@ -1517,7 +1517,7 @@ pub fn transpileSourceCode( const value = brk: { if (!jsc_vm.origin.isEmpty()) { - var buf = MutableString.init2048(jsc_vm.allocator) catch bun.outOfMemory(); + var buf = bun.handleOom(MutableString.init2048(jsc_vm.allocator)); defer buf.deinit(); var writer = buf.writer(); jsc.API.Bun.getPublicPath(specifier, jsc_vm.origin, @TypeOf(&writer), &writer); @@ -2079,7 +2079,7 @@ fn dumpSourceStringFailiable(vm: *VirtualMachine, specifier: string, written: [] }; if (vm.source_mappings.get(specifier)) |mappings| { defer mappings.deref(); - const map_path = std.mem.concat(bun.default_allocator, u8, &.{ std.fs.path.basename(specifier), ".map" }) catch bun.outOfMemory(); + const map_path = bun.handleOom(std.mem.concat(bun.default_allocator, u8, &.{ std.fs.path.basename(specifier), ".map" })); defer bun.default_allocator.free(map_path); const file = try parent.createFile(map_path, .{}); defer file.close(); @@ -2319,7 +2319,7 @@ pub const RuntimeTranspilerStore = struct { } if (ast_memory_store == null) { - ast_memory_store = bun.default_allocator.create(js_ast.ASTMemoryAllocator) catch bun.outOfMemory(); + ast_memory_store = bun.handleOom(bun.default_allocator.create(js_ast.ASTMemoryAllocator)); ast_memory_store.?.* = js_ast.ASTMemoryAllocator{ .allocator = allocator, .previous = null, @@ -2340,7 +2340,7 @@ pub const RuntimeTranspilerStore = struct { var log = logger.Log.init(allocator); defer { this.log = logger.Log.init(bun.default_allocator); - log.cloneToWithRecycled(&this.log, true) catch bun.outOfMemory(); + bun.handleOom(log.cloneToWithRecycled(&this.log, true)); } var vm = this.vm; var transpiler: bun.Transpiler = undefined; diff --git a/src/bun.js/SavedSourceMap.zig b/src/bun.js/SavedSourceMap.zig index 706a748507..a350f46436 100644 --- a/src/bun.js/SavedSourceMap.zig +++ b/src/bun.js/SavedSourceMap.zig @@ -105,12 +105,12 @@ pub const MissingSourceMapNoteInfo = struct { }; pub fn putBakeSourceProvider(this: *SavedSourceMap, opaque_source_provider: *BakeSourceProvider, path: []const u8) void { - this.putValue(path, Value.init(opaque_source_provider)) catch bun.outOfMemory(); + bun.handleOom(this.putValue(path, Value.init(opaque_source_provider))); } pub fn putZigSourceProvider(this: *SavedSourceMap, opaque_source_provider: *anyopaque, path: []const u8) void { const source_provider: *SourceProviderMap = @ptrCast(opaque_source_provider); - this.putValue(path, Value.init(source_provider)) catch bun.outOfMemory(); + bun.handleOom(this.putValue(path, Value.init(source_provider))); } pub fn removeZigSourceProvider(this: *SavedSourceMap, opaque_source_provider: *anyopaque, path: []const u8) void { @@ -235,7 +235,7 @@ fn getWithContent( if (parse.map) |map| { map.ref(); // The mutex is not locked. We have to check the hash table again. - this.putValue(path, Value.init(map)) catch bun.outOfMemory(); + bun.handleOom(this.putValue(path, Value.init(map))); return parse; } @@ -262,7 +262,7 @@ fn getWithContent( if (parse.map) |map| { map.ref(); // The mutex is not locked. We have to check the hash table again. - this.putValue(path, Value.init(map)) catch bun.outOfMemory(); + bun.handleOom(this.putValue(path, Value.init(map))); return parse; } diff --git a/src/bun.js/VirtualMachine.zig b/src/bun.js/VirtualMachine.zig index 30db947fee..7e91bcbf28 100644 --- a/src/bun.js/VirtualMachine.zig +++ b/src/bun.js/VirtualMachine.zig @@ -1711,7 +1711,7 @@ pub fn resolveMaybeNeedsTrailingSlash( source_utf8.slice(), error.NameTooLong, if (is_esm) .stmt else if (is_user_require_resolve) .require_resolve else .require, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const msg = logger.Msg{ .data = logger.rangeData( null, diff --git a/src/bun.js/api/BunObject.zig b/src/bun.js/api/BunObject.zig index 1a1ad773b8..df88c72e5d 100644 --- a/src/bun.js/api/BunObject.zig +++ b/src/bun.js/api/BunObject.zig @@ -394,7 +394,7 @@ pub fn inspectTable(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) } // very stable memory address - var array = MutableString.init(bun.default_allocator, 0) catch bun.outOfMemory(); + var array = bun.handleOom(MutableString.init(bun.default_allocator, 0)); defer array.deinit(); var buffered_writer_ = MutableString.BufferedWriter{ .context = &array }; var buffered_writer = &buffered_writer_; @@ -1133,7 +1133,7 @@ pub fn serve(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.J ); debugger.http_server_agent.notifyServerRoutesUpdated( jsc.API.AnyServer.from(server), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } return obj; @@ -1347,7 +1347,7 @@ pub fn getEmbeddedFiles(globalThis: *jsc.JSGlobalObject, _: *jsc.JSObject) bun.J const graph = vm.standalone_module_graph orelse return try jsc.JSValue.createEmptyArray(globalThis, 0); const unsorted_files = graph.files.values(); - var sort_indices = std.ArrayList(u32).initCapacity(bun.default_allocator, unsorted_files.len) catch bun.outOfMemory(); + var sort_indices = bun.handleOom(std.ArrayList(u32).initCapacity(bun.default_allocator, unsorted_files.len)); defer sort_indices.deinit(); for (0..unsorted_files.len) |index| { // Some % of people using `bun build --compile` want to obscure the source code @@ -1720,7 +1720,7 @@ pub const JSZlib = struct { defer reader.deinit(); return globalThis.throwValue(ZigString.init(reader.errorMessage() orelse "Zlib returned an error").toErrorInstance(globalThis)); }; - reader.list = .{ .items = reader.list.toOwnedSlice(allocator) catch bun.outOfMemory() }; + reader.list = .{ .items = bun.handleOom(reader.list.toOwnedSlice(allocator)) }; reader.list.capacity = reader.list.items.len; reader.list_ptr = &reader.list; diff --git a/src/bun.js/api/JSBundler.zig b/src/bun.js/api/JSBundler.zig index 559342c163..acc4336de8 100644 --- a/src/bun.js/api/JSBundler.zig +++ b/src/bun.js/api/JSBundler.zig @@ -1263,7 +1263,13 @@ pub const JSBundler = struct { plugin.globalObject(), resolve.import_record.source_file, exception, - ) catch bun.outOfMemory(), + ) catch |err| switch (err) { + error.OutOfMemory => bun.outOfMemory(), + error.JSError => { + plugin.globalObject().reportActiveExceptionAsUnhandled(err); + return; + }, + }, }; resolve.bv2.onResolveAsync(resolve); }, @@ -1275,7 +1281,13 @@ pub const JSBundler = struct { plugin.globalObject(), load.path, exception, - ) catch bun.outOfMemory(), + ) catch |err| switch (err) { + error.OutOfMemory => bun.outOfMemory(), + error.JSError => { + plugin.globalObject().reportActiveExceptionAsUnhandled(err); + return; + }, + }, }; load.bv2.onLoadAsync(load); }, diff --git a/src/bun.js/api/JSTranspiler.zig b/src/bun.js/api/JSTranspiler.zig index a80e13db72..2f2a3d4f80 100644 --- a/src/bun.js/api/JSTranspiler.zig +++ b/src/bun.js/api/JSTranspiler.zig @@ -171,7 +171,7 @@ pub const Config = struct { } if (out.isEmpty()) break :tsconfig; - this.tsconfig_buf = out.toOwnedSlice(allocator) catch bun.outOfMemory(); + this.tsconfig_buf = bun.handleOom(out.toOwnedSlice(allocator)); // TODO: JSC -> Ast conversion if (TSConfigJSON.parse( @@ -210,7 +210,7 @@ pub const Config = struct { } if (out.isEmpty()) break :macros; - this.macros_buf = out.toOwnedSlice(allocator) catch bun.outOfMemory(); + this.macros_buf = bun.handleOom(out.toOwnedSlice(allocator)); const source = &logger.Source.initPathString("macros.json", this.macros_buf); const json = (jsc.VirtualMachine.get().transpiler.resolver.caches.json.parseJSON( &this.log, @@ -486,7 +486,7 @@ pub const TransformTask = struct { defer arena.deinit(); const allocator = arena.allocator(); - var ast_memory_allocator = allocator.create(JSAst.ASTMemoryAllocator) catch bun.outOfMemory(); + var ast_memory_allocator = bun.handleOom(allocator.create(JSAst.ASTMemoryAllocator)); var ast_scope = ast_memory_allocator.enter(allocator); defer ast_scope.exit(); @@ -800,7 +800,7 @@ pub fn scan(this: *JSTranspiler, globalThis: *jsc.JSGlobalObject, callframe: *js this.transpiler.setAllocator(prev_allocator); arena.deinit(); } - var ast_memory_allocator = allocator.create(JSAst.ASTMemoryAllocator) catch bun.outOfMemory(); + var ast_memory_allocator = bun.handleOom(allocator.create(JSAst.ASTMemoryAllocator)); var ast_scope = ast_memory_allocator.enter(allocator); defer ast_scope.exit(); @@ -935,7 +935,7 @@ pub fn transformSync( const allocator = arena.allocator(); - var ast_memory_allocator = allocator.create(JSAst.ASTMemoryAllocator) catch bun.outOfMemory(); + var ast_memory_allocator = bun.handleOom(allocator.create(JSAst.ASTMemoryAllocator)); var ast_scope = ast_memory_allocator.enter(allocator); defer ast_scope.exit(); @@ -1069,7 +1069,7 @@ pub fn scanImports(this: *JSTranspiler, globalThis: *jsc.JSGlobalObject, callfra var arena = MimallocArena.init(); const prev_allocator = this.transpiler.allocator; const allocator = arena.allocator(); - var ast_memory_allocator = allocator.create(JSAst.ASTMemoryAllocator) catch bun.outOfMemory(); + var ast_memory_allocator = bun.handleOom(allocator.create(JSAst.ASTMemoryAllocator)); var ast_scope = ast_memory_allocator.enter(allocator); defer ast_scope.exit(); diff --git a/src/bun.js/api/Timer.zig b/src/bun.js/api/Timer.zig index 3fbf28568c..8345724837 100644 --- a/src/bun.js/api/Timer.zig +++ b/src/bun.js/api/Timer.zig @@ -315,7 +315,7 @@ pub const All = struct { bun.String.createFormat( "{d} does not fit into a 32-bit signed integer" ++ suffix, .{countdown}, - ) catch bun.outOfMemory() + ) catch |err| bun.handleOom(err) else // -Infinity is handled by TimeoutNegativeWarning bun.String.ascii("Infinity does not fit into a 32-bit signed integer" ++ suffix), @@ -323,7 +323,7 @@ pub const All = struct { bun.String.createFormat( "{d} is a negative number" ++ suffix, .{countdown}, - ) catch bun.outOfMemory() + ) catch |err| bun.handleOom(err) else bun.String.ascii("-Infinity is a negative number" ++ suffix), // std.fmt gives us "nan" but Node.js wants "NaN". diff --git a/src/bun.js/api/bun/dns.zig b/src/bun.js/api/bun/dns.zig index 3d68a3a26e..a9fca57010 100644 --- a/src/bun.js/api/bun/dns.zig +++ b/src/bun.js/api/bun/dns.zig @@ -61,7 +61,7 @@ const LibInfo = struct { var cache = this.getOrPutIntoPendingCache(key, .pending_host_cache_native); if (cache == .inflight) { - var dns_lookup = DNSLookup.init(this, globalThis, globalThis.allocator()) catch bun.outOfMemory(); + var dns_lookup = bun.handleOom(DNSLookup.init(this, globalThis, globalThis.allocator())); cache.inflight.append(dns_lookup); @@ -81,7 +81,7 @@ const LibInfo = struct { query, globalThis, "pending_host_cache_native", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const promise_value = request.head.promise.value(); const hints = query.options.toLibC(); @@ -136,7 +136,7 @@ const LibC = struct { var cache = this.getOrPutIntoPendingCache(key, .pending_host_cache_native); if (cache == .inflight) { - var dns_lookup = DNSLookup.init(this, globalThis, globalThis.allocator()) catch bun.outOfMemory(); + var dns_lookup = bun.handleOom(DNSLookup.init(this, globalThis, globalThis.allocator())); cache.inflight.append(dns_lookup); @@ -152,10 +152,10 @@ const LibC = struct { query, globalThis, "pending_host_cache_native", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const promise_value = request.head.promise.value(); - var io = GetAddrInfoRequest.Task.createOnJSThread(this.vm.allocator, globalThis, request) catch bun.outOfMemory(); + var io = bun.handleOom(GetAddrInfoRequest.Task.createOnJSThread(this.vm.allocator, globalThis, request)); io.schedule(); this.requestSent(globalThis.bunVM()); @@ -181,7 +181,7 @@ const LibUVBackend = struct { } }; - var holder = bun.default_allocator.create(Holder) catch bun.outOfMemory(); + var holder = bun.handleOom(bun.default_allocator.create(Holder)); holder.* = .{ .uv_info = uv_info, .task = undefined, @@ -196,7 +196,7 @@ const LibUVBackend = struct { var cache = this.getOrPutIntoPendingCache(key, .pending_host_cache_native); if (cache == .inflight) { - var dns_lookup = DNSLookup.init(this, globalThis, globalThis.allocator()) catch bun.outOfMemory(); + var dns_lookup = bun.handleOom(DNSLookup.init(this, globalThis, globalThis.allocator())); cache.inflight.append(dns_lookup); @@ -214,7 +214,7 @@ const LibUVBackend = struct { query, globalThis, "pending_host_cache_native", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); var hints = query.options.toLibC(); var port_buf: [128]u8 = undefined; @@ -780,7 +780,7 @@ pub const GetAddrInfoRequest = struct { // https://github.com/ziglang/zig/pull/14242 defer std.c.freeaddrinfo(addrinfo.?); - this.* = .{ .success = GetAddrInfo.Result.toList(default_allocator, addrinfo.?) catch bun.outOfMemory() }; + this.* = .{ .success = bun.handleOom(GetAddrInfo.Result.toList(default_allocator, addrinfo.?)) }; } }, @@ -1133,7 +1133,7 @@ pub const GlobalData = struct { resolver: Resolver, pub fn init(allocator: std.mem.Allocator, vm: *jsc.VirtualMachine) *GlobalData { - const global = allocator.create(GlobalData) catch bun.outOfMemory(); + const global = bun.handleOom(allocator.create(GlobalData)); global.* = .{ .resolver = Resolver.setup(allocator, vm), }; @@ -1194,7 +1194,7 @@ pub const internal = struct { pub fn toOwned(this: @This()) @This() { if (this.host) |host| { - const host_copy = bun.default_allocator.dupeZ(u8, host) catch bun.outOfMemory(); + const host_copy = bun.handleOom(bun.default_allocator.dupeZ(u8, host)); return .{ .host = host_copy, .hash = this.hash, @@ -1448,7 +1448,7 @@ pub const internal = struct { info_ = ai.next; } - var results = bun.default_allocator.alloc(ResultEntry, count) catch bun.outOfMemory(); + var results = bun.handleOom(bun.default_allocator.alloc(ResultEntry, count)); // copy results var i: usize = 0; @@ -1734,7 +1734,7 @@ pub const internal = struct { log("getaddrinfo({s}) = cache miss (libc)", .{host orelse ""}); // schedule the request to be executed on the work pool - bun.jsc.WorkPool.go(bun.default_allocator, *Request, req, workPoolCallback) catch bun.outOfMemory(); + bun.handleOom(bun.jsc.WorkPool.go(bun.default_allocator, *Request, req, workPoolCallback)); return req; } @@ -1797,7 +1797,7 @@ pub const internal = struct { return; } - request.notify.append(bun.default_allocator, .{ .socket = socket }) catch bun.outOfMemory(); + bun.handleOom(request.notify.append(bun.default_allocator, .{ .socket = socket })); } fn freeaddrinfo(req: *Request, err: c_int) callconv(.C) void { @@ -2471,7 +2471,7 @@ pub const Resolver = struct { return; } - const poll_entry = this.polls.getOrPut(fd) catch bun.outOfMemory(); + const poll_entry = bun.handleOom(this.polls.getOrPut(fd)); if (!poll_entry.found_existing) { const poll = UvDnsPoll.new(.{ .parent = this, @@ -2689,7 +2689,7 @@ pub const Resolver = struct { "pending_addr_cache_cares", ); if (cache == .inflight) { - var cares_reverse = CAresReverse.init(this, globalThis, globalThis.allocator(), ip) catch bun.outOfMemory(); + var cares_reverse = bun.handleOom(CAresReverse.init(this, globalThis, globalThis.allocator(), ip)); cache.inflight.append(cares_reverse); return cares_reverse.promise.value(); } @@ -2700,7 +2700,7 @@ pub const Resolver = struct { ip, globalThis, "pending_addr_cache_cares", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const promise = request.tail.promise.value(); channel.getHostByAddr( @@ -3067,7 +3067,7 @@ pub const Resolver = struct { var cache = this.getOrPutIntoResolvePendingCache(ResolveInfoRequest(cares_type, type_name), key, cache_name); if (cache == .inflight) { // CAresLookup will have the name ownership - var cares_lookup = CAresLookup(cares_type, type_name).init(this, globalThis, globalThis.allocator(), name) catch bun.outOfMemory(); + var cares_lookup = bun.handleOom(CAresLookup(cares_type, type_name).init(this, globalThis, globalThis.allocator(), name)); cache.inflight.append(cares_lookup); return cares_lookup.promise.value(); } @@ -3078,7 +3078,7 @@ pub const Resolver = struct { name, // CAresLookup will have the ownership globalThis, cache_name, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const promise = request.tail.promise.value(); channel.resolve( @@ -3115,7 +3115,7 @@ pub const Resolver = struct { var cache = this.getOrPutIntoPendingCache(key, .pending_host_cache_cares); if (cache == .inflight) { - var dns_lookup = DNSLookup.init(this, globalThis, globalThis.allocator()) catch bun.outOfMemory(); + var dns_lookup = bun.handleOom(DNSLookup.init(this, globalThis, globalThis.allocator())); cache.inflight.append(dns_lookup); return dns_lookup.promise.value(); } @@ -3128,7 +3128,7 @@ pub const Resolver = struct { query, globalThis, "pending_host_cache_cares", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const promise = request.tail.promise.value(); channel.getAddrInfo( @@ -3247,7 +3247,7 @@ pub const Resolver = struct { defer str.deref(); const slice = str.toSlice(bun.default_allocator).slice(); - var buffer = bun.default_allocator.alloc(u8, slice.len + 1) catch bun.outOfMemory(); + var buffer = bun.handleOom(bun.default_allocator.alloc(u8, slice.len + 1)); defer bun.default_allocator.free(buffer); _ = strings.copy(buffer[0..], slice); buffer[slice.len] = 0; @@ -3297,7 +3297,7 @@ pub const Resolver = struct { const allocator = bun.default_allocator; - const entries = allocator.alloc(c_ares.struct_ares_addr_port_node, triplesIterator.len) catch bun.outOfMemory(); + const entries = bun.handleOom(allocator.alloc(c_ares.struct_ares_addr_port_node, triplesIterator.len)); defer allocator.free(entries); var i: u32 = 0; @@ -3320,7 +3320,7 @@ pub const Resolver = struct { const addressSlice = try addressString.toOwnedSlice(allocator); defer allocator.free(addressSlice); - var addressBuffer = allocator.alloc(u8, addressSlice.len + 1) catch bun.outOfMemory(); + var addressBuffer = bun.handleOom(allocator.alloc(u8, addressSlice.len + 1)); defer allocator.free(addressBuffer); _ = strings.copy(addressBuffer[0..], addressSlice); @@ -3419,7 +3419,7 @@ pub const Resolver = struct { var channel = try resolver.getChannelOrError(globalThis); // This string will be freed in `CAresNameInfo.deinit` - const cache_name = std.fmt.allocPrint(bun.default_allocator, "{s}|{d}", .{ addr_s, port }) catch bun.outOfMemory(); + const cache_name = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s}|{d}", .{ addr_s, port })); const key = GetNameInfoRequest.PendingCacheKey.init(cache_name); var cache = resolver.getOrPutIntoResolvePendingCache( @@ -3429,7 +3429,7 @@ pub const Resolver = struct { ); if (cache == .inflight) { - var info = CAresNameInfo.init(globalThis, globalThis.allocator(), cache_name) catch bun.outOfMemory(); + var info = bun.handleOom(CAresNameInfo.init(globalThis, globalThis.allocator(), cache_name)); cache.inflight.append(info); return info.promise.value(); } @@ -3440,7 +3440,7 @@ pub const Resolver = struct { cache_name, // transfer ownership here globalThis, "pending_nameinfo_cache_cares", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const promise = request.tail.promise.value(); channel.getNameInfo( diff --git a/src/bun.js/api/bun/h2_frame_parser.zig b/src/bun.js/api/bun/h2_frame_parser.zig index e21e4440a7..7a9f04786c 100644 --- a/src/bun.js/api/bun/h2_frame_parser.zig +++ b/src/bun.js/api/bun/h2_frame_parser.zig @@ -778,7 +778,7 @@ pub const H2FrameParser = struct { } pub fn enqueue(self: *PendingQueue, value: PendingFrame, allocator: Allocator) void { - self.data.append(allocator, value) catch bun.outOfMemory(); + bun.handleOom(self.data.append(allocator, value)); self.len += 1; log("PendingQueue.enqueue {}", .{self.len}); } @@ -1015,7 +1015,7 @@ pub const H2FrameParser = struct { } if (last_frame.len == 0) { // we have an empty frame with means we can just use this frame with a new buffer - last_frame.buffer = client.allocator.alloc(u8, MAX_PAYLOAD_SIZE_WITHOUT_FRAME) catch bun.outOfMemory(); + last_frame.buffer = bun.handleOom(client.allocator.alloc(u8, MAX_PAYLOAD_SIZE_WITHOUT_FRAME)); } const max_size = MAX_PAYLOAD_SIZE_WITHOUT_FRAME; const remaining = max_size - last_frame.len; @@ -1051,7 +1051,7 @@ pub const H2FrameParser = struct { .end_stream = end_stream, .len = @intCast(bytes.len), // we need to clone this data to send it later - .buffer = if (bytes.len == 0) "" else client.allocator.alloc(u8, MAX_PAYLOAD_SIZE_WITHOUT_FRAME) catch bun.outOfMemory(), + .buffer = if (bytes.len == 0) "" else bun.handleOom(client.allocator.alloc(u8, MAX_PAYLOAD_SIZE_WITHOUT_FRAME)), .callback = if (callback.isCallable()) jsc.Strong.Optional.create(callback, globalThis) else .empty, }; if (bytes.len > 0) { @@ -1547,7 +1547,7 @@ pub const H2FrameParser = struct { this.writeBufferOffset += written; // we still have more to buffer and even more now - _ = this.writeBuffer.write(this.allocator, bytes) catch bun.outOfMemory(); + _ = bun.handleOom(this.writeBuffer.write(this.allocator, bytes)); this.globalThis.vm().reportExtraMemory(bytes.len); log("_genericWrite flushed {} and buffered more {}", .{ written, bytes.len }); @@ -1563,7 +1563,7 @@ pub const H2FrameParser = struct { if (written < bytes.len) { const pending = bytes[written..]; // ops not all data was sent, lets buffer again - _ = this.writeBuffer.write(this.allocator, pending) catch bun.outOfMemory(); + _ = bun.handleOom(this.writeBuffer.write(this.allocator, pending)); this.globalThis.vm().reportExtraMemory(pending.len); log("_genericWrite buffered more {}", .{pending.len}); @@ -1583,7 +1583,7 @@ pub const H2FrameParser = struct { if (written < bytes.len) { const pending = bytes[written..]; // ops not all data was sent, lets buffer again - _ = this.writeBuffer.write(this.allocator, pending) catch bun.outOfMemory(); + _ = bun.handleOom(this.writeBuffer.write(this.allocator, pending)); this.globalThis.vm().reportExtraMemory(pending.len); return false; @@ -1664,7 +1664,7 @@ pub const H2FrameParser = struct { else => { if (this.has_nonnative_backpressure) { // we should not invoke JS when we have backpressure is cheaper to keep it queued here - _ = this.writeBuffer.write(this.allocator, bytes) catch bun.outOfMemory(); + _ = bun.handleOom(this.writeBuffer.write(this.allocator, bytes)); this.globalThis.vm().reportExtraMemory(bytes.len); return false; @@ -1676,7 +1676,7 @@ pub const H2FrameParser = struct { switch (code) { -1 => { // dropped - _ = this.writeBuffer.write(this.allocator, bytes) catch bun.outOfMemory(); + _ = bun.handleOom(this.writeBuffer.write(this.allocator, bytes)); this.globalThis.vm().reportExtraMemory(bytes.len); this.has_nonnative_backpressure = true; }, @@ -1770,7 +1770,7 @@ pub const H2FrameParser = struct { this.remainingLength -= @intCast(end); if (this.remainingLength > 0) { // buffer more data - _ = this.readBuffer.appendSlice(payload) catch bun.outOfMemory(); + _ = bun.handleOom(this.readBuffer.appendSlice(payload)); this.globalThis.vm().reportExtraMemory(payload.len); return null; @@ -1783,7 +1783,7 @@ pub const H2FrameParser = struct { if (this.readBuffer.list.items.len > 0) { // return buffered data - _ = this.readBuffer.appendSlice(payload) catch bun.outOfMemory(); + _ = bun.handleOom(this.readBuffer.appendSlice(payload)); this.globalThis.vm().reportExtraMemory(payload.len); return .{ @@ -2417,7 +2417,7 @@ pub const H2FrameParser = struct { } // new stream open - const entry = this.streams.getOrPut(streamIdentifier) catch bun.outOfMemory(); + const entry = bun.handleOom(this.streams.getOrPut(streamIdentifier)); entry.value_ptr.* = Stream.init( streamIdentifier, @@ -2485,7 +2485,7 @@ pub const H2FrameParser = struct { const total = buffered_data + bytes.len; if (total < FrameHeader.byteSize) { // buffer more data - _ = this.readBuffer.appendSlice(bytes) catch bun.outOfMemory(); + _ = bun.handleOom(this.readBuffer.appendSlice(bytes)); this.globalThis.vm().reportExtraMemory(bytes.len); return bytes.len; @@ -2525,7 +2525,7 @@ pub const H2FrameParser = struct { if (bytes.len < FrameHeader.byteSize) { // buffer more dheaderata - this.readBuffer.appendSlice(bytes) catch bun.outOfMemory(); + bun.handleOom(this.readBuffer.appendSlice(bytes)); this.globalThis.vm().reportExtraMemory(bytes.len); return bytes.len; @@ -4277,10 +4277,10 @@ pub const H2FrameParser = struct { var this = brk: { if (ENABLE_ALLOCATOR_POOL) { if (H2FrameParser.pool == null) { - H2FrameParser.pool = bun.default_allocator.create(H2FrameParser.H2FrameParserHiveAllocator) catch bun.outOfMemory(); + H2FrameParser.pool = bun.handleOom(bun.default_allocator.create(H2FrameParser.H2FrameParserHiveAllocator)); H2FrameParser.pool.?.* = H2FrameParser.H2FrameParserHiveAllocator.init(bun.default_allocator); } - const self = H2FrameParser.pool.?.tryGet() catch bun.outOfMemory(); + const self = bun.handleOom(H2FrameParser.pool.?.tryGet()); self.* = H2FrameParser{ .ref_count = .init(), diff --git a/src/bun.js/api/bun/process.zig b/src/bun.js/api/bun/process.zig index d9ae7d3aba..2ac122bf6a 100644 --- a/src/bun.js/api/bun/process.zig +++ b/src/bun.js/api/bun/process.zig @@ -1817,7 +1817,7 @@ pub const sync = struct { .ignore => .ignore, .buffer => .{ .buffer = if (Environment.isWindows) - bun.default_allocator.create(bun.windows.libuv.Pipe) catch bun.outOfMemory(), + bun.handleOom(bun.default_allocator.create(bun.windows.libuv.Pipe)), }, }; } @@ -1867,11 +1867,11 @@ pub const sync = struct { pub const new = bun.TrivialNew(@This()); fn onAlloc(_: *SyncWindowsPipeReader, suggested_size: usize) []u8 { - return bun.default_allocator.alloc(u8, suggested_size) catch bun.outOfMemory(); + return bun.handleOom(bun.default_allocator.alloc(u8, suggested_size)); } fn onRead(this: *SyncWindowsPipeReader, data: []const u8) void { - this.chunks.append(@constCast(data)) catch bun.outOfMemory(); + bun.handleOom(this.chunks.append(@constCast(data))); } fn onError(this: *SyncWindowsPipeReader, err: bun.sys.E) void { @@ -2023,11 +2023,11 @@ pub const sync = struct { .status = this.status orelse @panic("Expected Process to have exited when waiting_count == 0"), .stdout = std.ArrayList(u8).fromOwnedSlice( bun.default_allocator, - flattenOwnedChunks(bun.default_allocator, bun.default_allocator, this.stdout) catch bun.outOfMemory(), + bun.handleOom(flattenOwnedChunks(bun.default_allocator, bun.default_allocator, this.stdout)), ), .stderr = std.ArrayList(u8).fromOwnedSlice( bun.default_allocator, - flattenOwnedChunks(bun.default_allocator, bun.default_allocator, this.stderr) catch bun.outOfMemory(), + bun.handleOom(flattenOwnedChunks(bun.default_allocator, bun.default_allocator, this.stderr)), ), }; this.stdout = &.{}; @@ -2067,7 +2067,7 @@ pub const sync = struct { try string_builder.allocate(bun.default_allocator); - var args = std.ArrayList(?[*:0]u8).initCapacity(bun.default_allocator, argv.len + 1) catch bun.outOfMemory(); + var args = bun.handleOom(std.ArrayList(?[*:0]u8).initCapacity(bun.default_allocator, argv.len + 1)); defer args.deinit(); for (argv) |arg| { diff --git a/src/bun.js/api/bun/socket.zig b/src/bun.js/api/bun/socket.zig index f85f6e1414..6574b78fc2 100644 --- a/src/bun.js/api/bun/socket.zig +++ b/src/bun.js/api/bun/socket.zig @@ -418,7 +418,7 @@ pub fn NewSocket(comptime ssl: bool) type { if (this.server_name) |server_name| { const host = server_name; if (host.len > 0) { - const host__ = default_allocator.dupeZ(u8, host) catch bun.outOfMemory(); + const host__ = bun.handleOom(default_allocator.dupeZ(u8, host)); defer default_allocator.free(host__); ssl_ptr.setHostname(host__); } @@ -426,7 +426,7 @@ pub fn NewSocket(comptime ssl: bool) type { if (connection == .host) { const host = connection.host.host; if (host.len > 0) { - const host__ = default_allocator.dupeZ(u8, host) catch bun.outOfMemory(); + const host__ = bun.handleOom(default_allocator.dupeZ(u8, host)); defer default_allocator.free(host__); ssl_ptr.setHostname(host__); } @@ -1004,7 +1004,7 @@ pub fn NewSocket(comptime ssl: bool) type { } if (remaining_in_input_data.len > 0) { - this.buffered_data_for_node_net.append(bun.default_allocator, remaining_in_input_data) catch bun.outOfMemory(); + bun.handleOom(this.buffered_data_for_node_net.append(bun.default_allocator, remaining_in_input_data)); } break :brk rc; @@ -1012,7 +1012,7 @@ pub fn NewSocket(comptime ssl: bool) type { } // slower-path: clone the data, do one write. - this.buffered_data_for_node_net.append(bun.default_allocator, buffer.slice()) catch bun.outOfMemory(); + bun.handleOom(this.buffered_data_for_node_net.append(bun.default_allocator, buffer.slice())); const rc = this.writeMaybeCorked(this.buffered_data_for_node_net.slice()); if (rc > 0) { const wrote: usize = @intCast(@max(rc, 0)); @@ -1166,7 +1166,7 @@ pub fn NewSocket(comptime ssl: bool) type { if (buffer_unwritten_data) { const remaining = bytes[uwrote..]; if (remaining.len > 0) { - this.buffered_data_for_node_net.append(bun.default_allocator, remaining) catch bun.outOfMemory(); + bun.handleOom(this.buffered_data_for_node_net.append(bun.default_allocator, remaining)); } } @@ -1453,7 +1453,7 @@ pub fn NewSocket(comptime ssl: bool) type { const ext_size = @sizeOf(WrappedSocket); - var handlers_ptr = bun.default_allocator.create(Handlers) catch bun.outOfMemory(); + var handlers_ptr = bun.handleOom(bun.default_allocator.create(Handlers)); handlers.withAsyncContextIfNeeded(globalObject); handlers_ptr.* = handlers; handlers_ptr.protect(); @@ -1464,8 +1464,8 @@ pub fn NewSocket(comptime ssl: bool) type { .socket = TLSSocket.Socket.detached, .connection = if (this.connection) |c| c.clone() else null, .wrapped = .tls, - .protos = if (protos) |p| (bun.default_allocator.dupe(u8, p[0..protos_len]) catch bun.outOfMemory()) else null, - .server_name = if (socket_config.server_name) |server_name| (bun.default_allocator.dupe(u8, server_name[0..bun.len(server_name)]) catch bun.outOfMemory()) else null, + .protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p[0..protos_len])) else null, + .server_name = if (socket_config.server_name) |server_name| bun.handleOom(bun.default_allocator.dupe(u8, server_name[0..bun.len(server_name)])) else null, .socket_context = null, // only set after the wrapTLS .flags = .{ .is_active = false, @@ -1528,7 +1528,7 @@ pub fn NewSocket(comptime ssl: bool) type { tls.ref(); const vm = handlers.vm; - var raw_handlers_ptr = bun.default_allocator.create(Handlers) catch bun.outOfMemory(); + var raw_handlers_ptr = bun.handleOom(bun.default_allocator.create(Handlers)); raw_handlers_ptr.* = blk: { const this_handlers = this.getHandlers(); break :blk .{ @@ -1976,7 +1976,7 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *jsc.JSGlobalObject, callframe: *jsc.C const is_server = false; // A duplex socket is always handled as a client - var handlers_ptr = handlers.vm.allocator.create(Handlers) catch bun.outOfMemory(); + var handlers_ptr = bun.handleOom(handlers.vm.allocator.create(Handlers)); handlers_ptr.* = handlers; handlers_ptr.is_server = is_server; handlers_ptr.withAsyncContextIfNeeded(globalObject); @@ -1988,8 +1988,8 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *jsc.JSGlobalObject, callframe: *jsc.C .socket = TLSSocket.Socket.detached, .connection = null, .wrapped = .tls, - .protos = if (protos) |p| (bun.default_allocator.dupe(u8, p[0..protos_len]) catch bun.outOfMemory()) else null, - .server_name = if (socket_config.server_name) |server_name| (bun.default_allocator.dupe(u8, server_name[0..bun.len(server_name)]) catch bun.outOfMemory()) else null, + .protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p[0..protos_len])) else null, + .server_name = if (socket_config.server_name) |server_name| bun.handleOom(bun.default_allocator.dupe(u8, server_name[0..bun.len(server_name)])) else null, .socket_context = null, // only set after the wrapTLS }); const tls_js_value = tls.getThisValue(globalObject); diff --git a/src/bun.js/api/bun/socket/Listener.zig b/src/bun.js/api/bun/socket/Listener.zig index 8d6765edcc..cfed0821e4 100644 --- a/src/bun.js/api/bun/socket/Listener.zig +++ b/src/bun.js/api/bun/socket/Listener.zig @@ -47,13 +47,13 @@ pub const UnixOrHost = union(enum) { switch (this) { .unix => |u| { return .{ - .unix = (bun.default_allocator.dupe(u8, u) catch bun.outOfMemory()), + .unix = bun.handleOom(bun.default_allocator.dupe(u8, u)), }; }, .host => |h| { return .{ .host = .{ - .host = (bun.default_allocator.dupe(u8, h.host) catch bun.outOfMemory()), + .host = bun.handleOom(bun.default_allocator.dupe(u8, h.host)), .port = this.host.port, }, }; @@ -129,7 +129,7 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa const slice = hostname_or_unix.slice(); var buf: bun.PathBuffer = undefined; if (normalizePipeName(slice, buf[0..])) |pipe_name| { - const connection: Listener.UnixOrHost = .{ .unix = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice() }; + const connection: Listener.UnixOrHost = .{ .unix = bun.handleOom(hostname_or_unix.cloneIfNeeded(bun.default_allocator)).slice() }; if (ssl_enabled) { if (ssl.?.protos) |p| { protos = p[0..ssl.?.protos_len]; @@ -141,7 +141,7 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa .ssl = ssl_enabled, .socket_context = null, .listener = .none, - .protos = if (protos) |p| (bun.default_allocator.dupe(u8, p) catch bun.outOfMemory()) else null, + .protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p)) else null, }; vm.eventLoop().ensureWaker(); @@ -152,7 +152,7 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa socket.strong_data = .create(socket_config.default_data, globalObject); } - var this: *Listener = handlers.vm.allocator.create(Listener) catch bun.outOfMemory(); + var this: *Listener = bun.handleOom(handlers.vm.allocator.create(Listener)); this.* = socket; //TODO: server_name is not supported on named pipes, I belive its , lets wait for someone to ask for it @@ -242,15 +242,15 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa } var connection: Listener.UnixOrHost = if (port) |port_| .{ - .host = .{ .host = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice(), .port = port_ }, + .host = .{ .host = bun.handleOom(hostname_or_unix.cloneIfNeeded(bun.default_allocator)).slice(), .port = port_ }, } else if (socket_config.fd) |fd| .{ .fd = fd } else .{ - .unix = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice(), + .unix = bun.handleOom(hostname_or_unix.cloneIfNeeded(bun.default_allocator)).slice(), }; var errno: c_int = 0; const listen_socket: *uws.ListenSocket = brk: { switch (connection) { .host => |c| { - const host = bun.default_allocator.dupeZ(u8, c.host) catch bun.outOfMemory(); + const host = bun.handleOom(bun.default_allocator.dupeZ(u8, c.host)); defer bun.default_allocator.free(host); const socket = socket_context.listen(ssl_enabled, host.ptr, c.port, socket_flags, 8, &errno); @@ -261,7 +261,7 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa break :brk socket; }, .unix => |u| { - const host = bun.default_allocator.dupeZ(u8, u) catch bun.outOfMemory(); + const host = bun.handleOom(bun.default_allocator.dupeZ(u8, u)); defer bun.default_allocator.free(host); break :brk socket_context.listenUnix(ssl_enabled, host, host.len, socket_flags, 8, &errno); }, @@ -302,7 +302,7 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa .ssl = ssl_enabled, .socket_context = socket_context, .listener = .{ .uws = listen_socket }, - .protos = if (protos) |p| (bun.default_allocator.dupe(u8, p) catch bun.outOfMemory()) else null, + .protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p)) else null, }; socket.handlers.protect(); @@ -319,7 +319,7 @@ pub fn listen(globalObject: *jsc.JSGlobalObject, opts: JSValue) bun.JSError!JSVa } } - var this: *Listener = handlers.vm.allocator.create(Listener) catch bun.outOfMemory(); + var this: *Listener = bun.handleOom(handlers.vm.allocator.create(Listener)); this.* = socket; this.socket_context.?.ext(ssl_enabled, *Listener).?.* = this; @@ -405,7 +405,7 @@ pub fn addServerName(this: *Listener, global: *jsc.JSGlobalObject, hostname: JSV bun.default_allocator, ); defer host_str.deinit(); - const server_name = bun.default_allocator.dupeZ(u8, host_str.slice()) catch bun.outOfMemory(); + const server_name = bun.handleOom(bun.default_allocator.dupeZ(u8, host_str.slice())); defer bun.default_allocator.free(server_name); if (server_name.len == 0) { return global.throwInvalidArguments("hostname pattern cannot be empty", .{}); @@ -580,10 +580,10 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock } } if (port) |_| { - break :blk .{ .host = .{ .host = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice(), .port = port.? } }; + break :blk .{ .host = .{ .host = bun.handleOom(hostname_or_unix.cloneIfNeeded(bun.default_allocator)).slice(), .port = port.? } }; } - break :blk .{ .unix = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice() }; + break :blk .{ .unix = bun.handleOom(hostname_or_unix.cloneIfNeeded(bun.default_allocator)).slice() }; }; if (Environment.isWindows) { @@ -617,7 +617,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock if (isNamedPipe) { default_data.ensureStillAlive(); - var handlers_ptr = handlers.vm.allocator.create(Handlers) catch bun.outOfMemory(); + var handlers_ptr = bun.handleOom(handlers.vm.allocator.create(Handlers)); handlers_ptr.* = handlers; var promise = jsc.JSPromise.create(globalObject); @@ -633,7 +633,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock prev.handlers = handlers_ptr; bun.assert(prev.socket.socket == .detached); prev.connection = connection; - prev.protos = if (protos) |p| (bun.default_allocator.dupe(u8, p) catch bun.outOfMemory()) else null; + prev.protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p)) else null; prev.server_name = server_name; prev.socket_context = null; break :blk prev; @@ -643,7 +643,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock .this_value = .zero, .socket = TLSSocket.Socket.detached, .connection = connection, - .protos = if (protos) |p| (bun.default_allocator.dupe(u8, p) catch bun.outOfMemory()) else null, + .protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p)) else null, .server_name = server_name, .socket_context = null, }); @@ -728,7 +728,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock protos = p[0..ssl.?.protos_len]; } if (ssl.?.server_name) |s| { - server_name = bun.default_allocator.dupe(u8, s[0..bun.len(s)]) catch bun.outOfMemory(); + server_name = bun.handleOom(bun.default_allocator.dupe(u8, s[0..bun.len(s)])); } uws.NewSocketHandler(true).configure(socket_context, true, *TLSSocket, NewSocket(true)); } else { @@ -737,7 +737,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock default_data.ensureStillAlive(); - var handlers_ptr = handlers.vm.allocator.create(Handlers) catch bun.outOfMemory(); + var handlers_ptr = bun.handleOom(handlers.vm.allocator.create(Handlers)); handlers_ptr.* = handlers; handlers_ptr.is_server = false; @@ -755,7 +755,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock prev.handlers = handlers_ptr; bun.assert(prev.socket.socket == .detached); prev.connection = connection; - prev.protos = if (protos) |p| (bun.default_allocator.dupe(u8, p) catch bun.outOfMemory()) else null; + prev.protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p)) else null; prev.server_name = server_name; prev.socket_context = socket_context; break :blk prev; @@ -765,7 +765,7 @@ pub fn connectInner(globalObject: *jsc.JSGlobalObject, prev_maybe_tcp: ?*TCPSock .this_value = .zero, .socket = SocketType.Socket.detached, .connection = connection, - .protos = if (protos) |p| (bun.default_allocator.dupe(u8, p) catch bun.outOfMemory()) else null, + .protos = if (protos) |p| bun.handleOom(bun.default_allocator.dupe(u8, p)) else null, .server_name = server_name, .socket_context = socket_context, // owns the socket context }); diff --git a/src/bun.js/api/bun/socket/SocketAddress.zig b/src/bun.js/api/bun/socket/SocketAddress.zig index 25af0145db..1e0e8fe634 100644 --- a/src/bun.js/api/bun/socket/SocketAddress.zig +++ b/src/bun.js/api/bun/socket/SocketAddress.zig @@ -225,7 +225,7 @@ pub fn initJS(global: *jsc.JSGlobalObject, options: Options) bun.JSError!SocketA }; if (options.address) |address_str| { presentation = address_str; - const slice = address_str.toOwnedSliceZ(alloc) catch bun.outOfMemory(); + const slice = bun.handleOom(address_str.toOwnedSliceZ(alloc)); defer alloc.free(slice); try pton(global, inet.AF_INET, slice, &sin.addr); } else { @@ -243,7 +243,7 @@ pub fn initJS(global: *jsc.JSGlobalObject, options: Options) bun.JSError!SocketA }; if (options.address) |address_str| { presentation = address_str; - const slice = address_str.toOwnedSliceZ(alloc) catch bun.outOfMemory(); + const slice = bun.handleOom(address_str.toOwnedSliceZ(alloc)); defer alloc.free(slice); try pton(global, inet.AF_INET6, slice, &sin6.addr); } else { diff --git a/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig b/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig index 1795aef38a..5969f43dfb 100644 --- a/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig +++ b/src/bun.js/api/bun/socket/WindowsNamedPipeContext.zig @@ -177,7 +177,7 @@ pub fn create(globalThis: *jsc.JSGlobalObject, socket: SocketType) *WindowsNamed }); // named_pipe owns the pipe (PipeWriter owns the pipe and will close and deinit it) - this.named_pipe = uws.WindowsNamedPipe.from(bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory(), .{ + this.named_pipe = uws.WindowsNamedPipe.from(bun.handleOom(bun.default_allocator.create(uv.Pipe)), .{ .ctx = this, .onOpen = @ptrCast(&WindowsNamedPipeContext.onOpen), .onData = @ptrCast(&WindowsNamedPipeContext.onData), diff --git a/src/bun.js/api/bun/socket/tls_socket_functions.zig b/src/bun.js/api/bun/socket/tls_socket_functions.zig index 344e07db1f..b1ea070bdc 100644 --- a/src/bun.js/api/bun/socket/tls_socket_functions.zig +++ b/src/bun.js/api/bun/socket/tls_socket_functions.zig @@ -39,7 +39,7 @@ pub fn setServername(this: *This, globalObject: *jsc.JSGlobalObject, callframe: // match node.js exceptions return globalObject.throw("Already started.", .{}); } - const host__ = default_allocator.dupeZ(u8, host) catch bun.outOfMemory(); + const host__ = bun.handleOom(default_allocator.dupeZ(u8, host)); defer default_allocator.free(host__); ssl_ptr.setHostname(host__); } @@ -237,7 +237,7 @@ pub fn getSharedSigalgs(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc. if (hash_str != null) { const hash_str_len = bun.len(hash_str); const hash_slice = hash_str[0..hash_str_len]; - const buffer = bun.default_allocator.alloc(u8, sig_with_md.len + hash_str_len + 1) catch bun.outOfMemory(); + const buffer = bun.handleOom(bun.default_allocator.alloc(u8, sig_with_md.len + hash_str_len + 1)); defer bun.default_allocator.free(buffer); bun.copy(u8, buffer, sig_with_md); @@ -245,7 +245,7 @@ pub fn getSharedSigalgs(this: *This, globalObject: *jsc.JSGlobalObject, _: *jsc. bun.copy(u8, buffer[sig_with_md.len + 1 ..], hash_slice); try array.putIndex(globalObject, @as(u32, @intCast(i)), jsc.ZigString.fromUTF8(buffer).toJS(globalObject)); } else { - const buffer = bun.default_allocator.alloc(u8, sig_with_md.len + 6) catch bun.outOfMemory(); + const buffer = bun.handleOom(bun.default_allocator.alloc(u8, sig_with_md.len + 6)); defer bun.default_allocator.free(buffer); bun.copy(u8, buffer, sig_with_md); @@ -621,7 +621,7 @@ noinline fn getSSLException(globalThis: *jsc.JSGlobalObject, defaultMessage: []c if (written > 0) { const message = output_buf[0..written]; - zig_str = ZigString.init(std.fmt.allocPrint(bun.default_allocator, "OpenSSL {s}", .{message}) catch bun.outOfMemory()); + zig_str = ZigString.init(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "OpenSSL {s}", .{message}))); var encoded_str = zig_str.withEncoding(); encoded_str.mark(); diff --git a/src/bun.js/api/bun/spawn/stdio.zig b/src/bun.js/api/bun/spawn/stdio.zig index e11696cd2c..8ff2915176 100644 --- a/src/bun.js/api/bun/spawn/stdio.zig +++ b/src/bun.js/api/bun/spawn/stdio.zig @@ -235,10 +235,10 @@ pub const Stdio = union(enum) { return .{ .err = .blob_used_as_out }; } - break :brk .{ .buffer = bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory() }; + break :brk .{ .buffer = bun.handleOom(bun.default_allocator.create(uv.Pipe)) }; }, - .ipc => .{ .ipc = bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory() }, - .capture, .pipe, .array_buffer, .readable_stream => .{ .buffer = bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory() }, + .ipc => .{ .ipc = bun.handleOom(bun.default_allocator.create(uv.Pipe)) }, + .capture, .pipe, .array_buffer, .readable_stream => .{ .buffer = bun.handleOom(bun.default_allocator.create(uv.Pipe)) }, .fd => |fd| .{ .pipe = fd }, .dup2 => .{ .dup2 = .{ .out = stdio.dup2.out, .to = stdio.dup2.to } }, .path => |pathlike| .{ .path = pathlike.slice() }, diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig index 3dcdfbc619..bd36b647d2 100644 --- a/src/bun.js/api/bun/subprocess.zig +++ b/src/bun.js/api/bun/subprocess.zig @@ -1745,7 +1745,7 @@ pub fn spawnMaybeSync( fn throwCommandNotFound(globalThis: *jsc.JSGlobalObject, command: []const u8) bun.JSError { const err = jsc.SystemError{ - .message = bun.String.createFormat("Executable not found in $PATH: \"{s}\"", .{command}) catch bun.outOfMemory(), + .message = bun.handleOom(bun.String.createFormat("Executable not found in $PATH: \"{s}\"", .{command})), .code = bun.String.static("ENOENT"), .errno = -bun.sys.UV_E.NOENT, .path = bun.String.cloneUTF8(command), diff --git a/src/bun.js/api/bun/udp_socket.zig b/src/bun.js/api/bun/udp_socket.zig index a5533b30f8..e34eadfa88 100644 --- a/src/bun.js/api/bun/udp_socket.zig +++ b/src/bun.js/api/bun/udp_socket.zig @@ -84,11 +84,11 @@ fn onData(socket: *uws.udp.Socket, buf: *uws.udp.PacketBuffer, packets: c_int) c if (comptime !bun.Environment.isWindows) { var buffer = std.mem.zeroes([bun.c.IF_NAMESIZE:0]u8); if (bun.c.if_indextoname(id, &buffer) != null) { - break :blk bun.String.createFormat("{s}%{s}", .{ span, std.mem.span(@as([*:0]u8, &buffer)) }) catch bun.outOfMemory(); + break :blk bun.handleOom(bun.String.createFormat("{s}%{s}", .{ span, std.mem.span(@as([*:0]u8, &buffer)) })); } } - break :blk bun.String.createFormat("{s}%{d}", .{ span, id }) catch bun.outOfMemory(); + break :blk bun.handleOom(bun.String.createFormat("{s}%{d}", .{ span, id })); } else bun.String.init(span); _ = callback.call(globalThis, udpSocket.thisValue, &.{ @@ -136,9 +136,9 @@ pub const UDPSocketConfig = struct { } const str = value.toBunString(globalThis) catch @panic("unreachable"); defer str.deref(); - break :brk str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(str.toOwnedSliceZ(default_allocator)); } else { - break :brk default_allocator.dupeZ(u8, "0.0.0.0") catch bun.outOfMemory(); + break :brk bun.handleOom(default_allocator.dupeZ(u8, "0.0.0.0")); } }; defer if (globalThis.hasException()) default_allocator.free(hostname); @@ -219,7 +219,7 @@ pub const UDPSocketConfig = struct { const str = try connect_host_js.toBunString(globalThis); defer str.deref(); - const connect_host = str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); + const connect_host = bun.handleOom(str.toOwnedSliceZ(default_allocator)); config.connect = .{ .port = if (connect_port < 1 or connect_port > 0xffff) 0 else @as(u16, @intCast(connect_port)), @@ -323,7 +323,7 @@ pub const UDPSocket = struct { const sys_err = jsc.SystemError{ .errno = err, .code = bun.String.static(code), - .message = bun.String.createFormat("bind {s} {s}", .{ code, config.hostname }) catch bun.outOfMemory(), + .message = bun.handleOom(bun.String.createFormat("bind {s} {s}", .{ code, config.hostname })), }; const error_value = sys_err.toErrorInstance(globalThis); error_value.put(globalThis, "address", try bun.String.createUTF8ForJS(globalThis, config.hostname)); @@ -606,10 +606,10 @@ pub const UDPSocket = struct { defer arena.deinit(); const alloc = arena.allocator(); - var payloads = alloc.alloc([*]const u8, len) catch bun.outOfMemory(); - var lens = alloc.alloc(usize, len) catch bun.outOfMemory(); - var addr_ptrs = alloc.alloc(?*const anyopaque, len) catch bun.outOfMemory(); - var addrs = alloc.alloc(std.posix.sockaddr.storage, len) catch bun.outOfMemory(); + var payloads = bun.handleOom(alloc.alloc([*]const u8, len)); + var lens = bun.handleOom(alloc.alloc(usize, len)); + var addr_ptrs = bun.handleOom(alloc.alloc(?*const anyopaque, len)); + var addrs = bun.handleOom(alloc.alloc(std.posix.sockaddr.storage, len)); var iter = try arg.arrayIterator(globalThis); @@ -907,7 +907,7 @@ pub const UDPSocket = struct { const str = try args.ptr[0].toBunString(globalThis); defer str.deref(); - const connect_host = str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); + const connect_host = bun.handleOom(str.toOwnedSliceZ(default_allocator)); defer default_allocator.free(connect_host); const connect_port_js = args.ptr[1]; diff --git a/src/bun.js/api/crypto/CryptoHasher.zig b/src/bun.js/api/crypto/CryptoHasher.zig index f72080f38a..e46b30f6b4 100644 --- a/src/bun.js/api/crypto/CryptoHasher.zig +++ b/src/bun.js/api/crypto/CryptoHasher.zig @@ -365,7 +365,7 @@ pub const CryptoHasher = union(enum) { _: *jsc.CallFrame, ) bun.JSError!jsc.JSValue { const copied: CryptoHasher = switch (this.*) { - .evp => |*inner| .{ .evp = inner.copy(globalObject.bunVM().rareData().boringEngine()) catch bun.outOfMemory() }, + .evp => |*inner| .{ .evp = bun.handleOom(inner.copy(globalObject.bunVM().rareData().boringEngine())) }, .hmac => |inner| brk: { const hmac = inner orelse { return throwHmacConsumed(globalObject); diff --git a/src/bun.js/api/crypto/PasswordObject.zig b/src/bun.js/api/crypto/PasswordObject.zig index a72781f9ad..1ed9b11440 100644 --- a/src/bun.js/api/crypto/PasswordObject.zig +++ b/src/bun.js/api/crypto/PasswordObject.zig @@ -373,7 +373,7 @@ pub const JSPasswordObject = struct { hash: []const u8, pub fn toErrorInstance(this: Value, globalObject: *jsc.JSGlobalObject) jsc.JSValue { - const error_code = std.fmt.allocPrint(bun.default_allocator, "PASSWORD{}", .{PascalToUpperUnderscoreCaseFormatter{ .input = @errorName(this.err) }}) catch bun.outOfMemory(); + const error_code = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "PASSWORD{}", .{PascalToUpperUnderscoreCaseFormatter{ .input = @errorName(this.err) }})); defer bun.default_allocator.free(error_code); const instance = globalObject.createErrorInstance("Password hashing failed with error \"{s}\"", .{@errorName(this.err)}); instance.put(globalObject, ZigString.static("code"), jsc.ZigString.init(error_code).toJS(globalObject)); @@ -585,7 +585,7 @@ pub const JSPasswordObject = struct { pass: bool, pub fn toErrorInstance(this: Value, globalObject: *jsc.JSGlobalObject) jsc.JSValue { - const error_code = std.fmt.allocPrint(bun.default_allocator, "PASSWORD{}", .{PascalToUpperUnderscoreCaseFormatter{ .input = @errorName(this.err) }}) catch bun.outOfMemory(); + const error_code = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "PASSWORD{}", .{PascalToUpperUnderscoreCaseFormatter{ .input = @errorName(this.err) }})); defer bun.default_allocator.free(error_code); const instance = globalObject.createErrorInstance("Password verification failed with error \"{s}\"", .{@errorName(this.err)}); instance.put(globalObject, ZigString.static("code"), jsc.ZigString.init(error_code).toJS(globalObject)); diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig index b499cdaf28..5533908a4d 100644 --- a/src/bun.js/api/ffi.zig +++ b/src/bun.js/api/ffi.zig @@ -200,7 +200,7 @@ pub const FFI = struct { } msg = msg[offset..]; - this.deferred_errors.append(bun.default_allocator, bun.default_allocator.dupe(u8, msg) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(this.deferred_errors.append(bun.default_allocator, bun.handleOom(bun.default_allocator.dupe(u8, msg)))); } const DeferredError = error{DeferredErrors}; @@ -456,7 +456,7 @@ pub const FFI = struct { for (this.symbols.map.keys(), this.symbols.map.values()) |symbol, *function| { // FIXME: why are we duping here? can we at least use a stack // fallback allocator? - const duped = bun.default_allocator.dupeZ(u8, symbol) catch bun.outOfMemory(); + const duped = bun.handleOom(bun.default_allocator.dupeZ(u8, symbol)); defer bun.default_allocator.free(duped); function.symbol_from_dynamic_library = state.getSymbol(duped) orelse { return globalThis.throw("{} is missing from {s}. Was it included in the source code?", .{ bun.fmt.quote(symbol), this.source.first() }); @@ -529,7 +529,7 @@ pub const FFI = struct { } const str = try val.getZigString(globalThis); if (str.isEmpty()) continue; - items.append(str.toOwnedSliceZ(bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(items.append(bun.handleOom(str.toOwnedSliceZ(bun.default_allocator)))); } return .{ .items = items.items }; @@ -543,7 +543,7 @@ pub const FFI = struct { const str = try value.getZigString(globalThis); if (str.isEmpty()) return .{}; var items = std.ArrayList([:0]const u8).init(bun.default_allocator); - items.append(str.toOwnedSliceZ(bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(items.append(bun.handleOom(str.toOwnedSliceZ(bun.default_allocator)))); return .{ .items = items.items }; } @@ -607,7 +607,7 @@ pub const FFI = struct { var flags = std.ArrayList(u8).init(allocator); defer flags.deinit(); - flags.appendSlice(CompileC.default_tcc_options) catch bun.outOfMemory(); + bun.handleOom(flags.appendSlice(CompileC.default_tcc_options)); while (try iter.next()) |value| { if (!value.isString()) { @@ -616,10 +616,10 @@ pub const FFI = struct { const slice = try value.toSlice(globalThis, allocator); if (slice.len == 0) continue; defer slice.deinit(); - flags.append(' ') catch bun.outOfMemory(); - flags.appendSlice(slice.slice()) catch bun.outOfMemory(); + bun.handleOom(flags.append(' ')); + bun.handleOom(flags.appendSlice(slice.slice())); } - flags.append(0) catch bun.outOfMemory(); + bun.handleOom(flags.append(0)); compile_c.flags = flags.items[0 .. flags.items.len - 1 :0]; flags = std.ArrayList(u8).init(allocator); } else { @@ -629,7 +629,7 @@ pub const FFI = struct { const str = try flags_value.getZigString(globalThis); if (!str.isEmpty()) { - compile_c.flags = str.toOwnedSliceZ(allocator) catch bun.outOfMemory(); + compile_c.flags = bun.handleOom(str.toOwnedSliceZ(allocator)); } } } @@ -644,13 +644,13 @@ pub const FFI = struct { var iter = try Iter.init(globalThis, define_obj); defer iter.deinit(); while (try iter.next()) |entry| { - const key = entry.toOwnedSliceZ(allocator) catch bun.outOfMemory(); + const key = bun.handleOom(entry.toOwnedSliceZ(allocator)); var owned_value: [:0]const u8 = ""; if (!iter.value.isUndefinedOrNull()) { if (iter.value.isString()) { const value = try iter.value.getZigString(globalThis); if (value.len > 0) { - owned_value = value.toOwnedSliceZ(allocator) catch bun.outOfMemory(); + owned_value = bun.handleOom(value.toOwnedSliceZ(allocator)); } } } @@ -659,7 +659,7 @@ pub const FFI = struct { return error.JSError; } - compile_c.define.append(allocator, .{ key, owned_value }) catch bun.outOfMemory(); + bun.handleOom(compile_c.define.append(allocator, .{ key, owned_value })); } } } @@ -705,10 +705,10 @@ pub const FFI = struct { var combined = std.ArrayList(u8).init(bun.default_allocator); defer combined.deinit(); var writer = combined.writer(); - writer.print("{d} errors while compiling {s}\n", .{ compile_c.deferred_errors.items.len, if (compile_c.current_file_for_errors.len > 0) compile_c.current_file_for_errors else compile_c.source.first() }) catch bun.outOfMemory(); + bun.handleOom(writer.print("{d} errors while compiling {s}\n", .{ compile_c.deferred_errors.items.len, if (compile_c.current_file_for_errors.len > 0) compile_c.current_file_for_errors else compile_c.source.first() })); for (compile_c.deferred_errors.items) |deferred_error| { - writer.print("{s}\n", .{deferred_error}) catch bun.outOfMemory(); + bun.handleOom(writer.print("{s}\n", .{deferred_error})); } return globalThis.throw("{s}", .{combined.items}); @@ -766,7 +766,7 @@ pub const FFI = struct { } // TODO: pub const new = bun.TrivialNew(FFI) - var lib = bun.default_allocator.create(FFI) catch bun.outOfMemory(); + var lib = bun.handleOom(bun.default_allocator.create(FFI)); lib.* = .{ .dylib = null, .shared_state = tcc_state, @@ -921,7 +921,7 @@ pub const FFI = struct { return val; } jsc.markBinding(@src()); - var strs = std.ArrayList(bun.String).initCapacity(allocator, symbols.count()) catch bun.outOfMemory(); + var strs = bun.handleOom(std.ArrayList(bun.String).initCapacity(allocator, symbols.count())); defer { for (strs.items) |str| { str.deref(); @@ -2308,7 +2308,7 @@ const CompilerRT = struct { }) catch {}; } var path_buf: [bun.MAX_PATH_BYTES]u8 = undefined; - compiler_rt_dir = bun.default_allocator.dupeZ(u8, bun.getFdPath(.fromStdDir(bunCC), &path_buf) catch return) catch bun.outOfMemory(); + compiler_rt_dir = bun.handleOom(bun.default_allocator.dupeZ(u8, bun.getFdPath(.fromStdDir(bunCC), &path_buf) catch return)); } var create_compiler_rt_dir_once = std.once(createCompilerRTDir); diff --git a/src/bun.js/api/glob.zig b/src/bun.js/api/glob.zig index a2b8bcb755..f25381c077 100644 --- a/src/bun.js/api/glob.zig +++ b/src/bun.js/api/glob.zig @@ -274,7 +274,7 @@ pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) b const pat_str: []u8 = @constCast((pat_arg.toSliceClone(globalThis) orelse return error.JSError).slice()); - const glob = alloc.create(Glob) catch bun.outOfMemory(); + const glob = bun.handleOom(alloc.create(Glob)); glob.* = .{ .pattern = pat_str }; return glob; diff --git a/src/bun.js/api/html_rewriter.zig b/src/bun.js/api/html_rewriter.zig index 007ed551f6..700d7e867d 100644 --- a/src/bun.js/api/html_rewriter.zig +++ b/src/bun.js/api/html_rewriter.zig @@ -41,7 +41,7 @@ pub const HTMLRewriter = struct { pub const fromJSDirect = js.fromJSDirect; pub fn constructor(_: *JSGlobalObject, _: *jsc.CallFrame) bun.JSError!*HTMLRewriter { - const rewriter = bun.default_allocator.create(HTMLRewriter) catch bun.outOfMemory(); + const rewriter = bun.handleOom(bun.default_allocator.create(HTMLRewriter)); rewriter.* = HTMLRewriter{ .builder = LOLHTML.HTMLRewriter.Builder.init(), .context = bun.new(LOLHTMLContext, .{ @@ -59,7 +59,7 @@ pub const HTMLRewriter = struct { callFrame: *jsc.CallFrame, listener: JSValue, ) bun.JSError!JSValue { - const selector_slice = std.fmt.allocPrint(bun.default_allocator, "{}", .{selector_name}) catch bun.outOfMemory(); + const selector_slice = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{}", .{selector_name})); defer bun.default_allocator.free(selector_slice); var selector = LOLHTML.HTMLSelector.parse(selector_slice) catch @@ -67,7 +67,7 @@ pub const HTMLRewriter = struct { errdefer selector.deinit(); const handler_ = try ElementHandler.init(global, listener); - const handler = bun.default_allocator.create(ElementHandler) catch bun.outOfMemory(); + const handler = bun.handleOom(bun.default_allocator.create(ElementHandler)); handler.* = handler_; errdefer { handler.deinit(); @@ -101,8 +101,8 @@ pub const HTMLRewriter = struct { return global.throwValue(createLOLHTMLError(global)); }; - this.context.selectors.append(bun.default_allocator, selector) catch bun.outOfMemory(); - this.context.element_handlers.append(bun.default_allocator, handler) catch bun.outOfMemory(); + bun.handleOom(this.context.selectors.append(bun.default_allocator, selector)); + bun.handleOom(this.context.element_handlers.append(bun.default_allocator, handler)); return callFrame.this(); } @@ -114,7 +114,7 @@ pub const HTMLRewriter = struct { ) bun.JSError!JSValue { const handler_ = try DocumentHandler.init(global, listener); - const handler = bun.default_allocator.create(DocumentHandler) catch bun.outOfMemory(); + const handler = bun.handleOom(bun.default_allocator.create(DocumentHandler)); handler.* = handler_; errdefer { handler.deinit(); @@ -152,7 +152,7 @@ pub const HTMLRewriter = struct { null, ); - this.context.document_handlers.append(bun.default_allocator, handler) catch bun.outOfMemory(); + bun.handleOom(this.context.document_handlers.append(bun.default_allocator, handler)); return callFrame.this(); } @@ -336,7 +336,7 @@ pub const HTMLRewriter = struct { return bun.sys.Error{ .errno = 1, // TODO: make this a union - .path = bun.default_allocator.dupe(u8, LOLHTML.HTMLString.lastError().slice()) catch bun.outOfMemory(), + .path = bun.handleOom(bun.default_allocator.dupe(u8, LOLHTML.HTMLString.lastError().slice())), }; }; if (comptime deinit_) bytes.listManaged(bun.default_allocator).deinit(); @@ -553,7 +553,7 @@ pub const HTMLRewriter = struct { bytes: []const u8, is_async: bool, ) ?JSValue { - sink.bytes.growBy(bytes.len) catch bun.outOfMemory(); + bun.handleOom(sink.bytes.growBy(bytes.len)); const global = sink.global; var response = sink.response; @@ -606,7 +606,7 @@ pub const HTMLRewriter = struct { } pub fn write(this: *BufferOutputSink, bytes: []const u8) void { - this.bytes.append(bytes) catch bun.outOfMemory(); + bun.handleOom(this.bytes.append(bytes)); } fn deinit(this: *BufferOutputSink) void { @@ -1708,7 +1708,7 @@ pub const Element = struct { return ZigString.init("Expected a function").withEncoding().toJS(globalObject); } - const end_tag_handler = bun.default_allocator.create(EndTag.Handler) catch bun.outOfMemory(); + const end_tag_handler = bun.handleOom(bun.default_allocator.create(EndTag.Handler)); end_tag_handler.* = .{ .global = globalObject, .callback = function }; this.element.?.onEndTag(EndTag.Handler.onEndTagHandler, end_tag_handler) catch { diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 9f7b5e757b..38bec4a432 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -189,7 +189,7 @@ pub const AnyRoute = union(enum) { pub fn htmlRouteFromJS(argument: jsc.JSValue, init_ctx: *ServerInitContext) bun.JSError!?AnyRoute { if (argument.as(HTMLBundle)) |html_bundle| { - const entry = init_ctx.dedupe_html_bundle_map.getOrPut(html_bundle) catch bun.outOfMemory(); + const entry = bun.handleOom(init_ctx.dedupe_html_bundle_map.getOrPut(html_bundle)); if (!entry.found_existing) { entry.value_ptr.* = HTMLBundle.Route.init(html_bundle); return .{ .html = entry.value_ptr.* }; @@ -366,7 +366,7 @@ const ServePlugins = struct { const plugin = bun.jsc.API.JSBundler.Plugin.create(global, .browser); var sfb = std.heap.stackFallback(@sizeOf(bun.String) * 4, bun.default_allocator); const alloc = sfb.get(); - const bunstring_array = alloc.alloc(bun.String, plugin_list.len) catch bun.outOfMemory(); + const bunstring_array = bun.handleOom(alloc.alloc(bun.String, plugin_list.len)); defer alloc.free(bunstring_array); for (plugin_list, bunstring_array) |raw_plugin, *out| { out.* = bun.String.init(raw_plugin); @@ -452,11 +452,11 @@ const ServePlugins = struct { this.state = .{ .loaded = plugin }; for (html_bundle_routes.items) |route| { - route.onPluginsResolved(plugin) catch bun.outOfMemory(); + bun.handleOom(route.onPluginsResolved(plugin)); route.deref(); } if (pending.dev_server) |server| { - server.onPluginsResolved(plugin) catch bun.outOfMemory(); + bun.handleOom(server.onPluginsResolved(plugin)); } } @@ -482,11 +482,11 @@ const ServePlugins = struct { this.state = .err; for (html_bundle_routes.items) |route| { - route.onPluginsRejected() catch bun.outOfMemory(); + bun.handleOom(route.onPluginsRejected()); route.deref(); } if (pending.dev_server) |server| { - server.onPluginsRejected() catch bun.outOfMemory(); + bun.handleOom(server.onPluginsRejected()); } Output.errGeneric("Failed to load plugins for Bun.serve:", .{}); @@ -593,7 +593,10 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d /// - .pending if `callback` was stored. It will call `onPluginsResolved` or `onPluginsRejected` later. pub fn getOrLoadPlugins(server: *ThisServer, callback: ServePlugins.Callback) ServePlugins.GetOrStartLoadResult { if (server.plugins) |p| { - return p.getOrStartLoad(server.globalThis, callback) catch bun.outOfMemory(); + return p.getOrStartLoad(server.globalThis, callback) catch |err| switch (err) { + error.JSError => std.debug.panic("unhandled exception from ServePlugins.getStartOrLoad", .{}), + error.OutOfMemory => bun.outOfMemory(), + }; } // no plugins return .{ .ready = null }; @@ -1081,7 +1084,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d if (this.vm.debugger) |*debugger| { debugger.http_server_agent.notifyServerRoutesUpdated( AnyServer.from(this), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } @@ -1206,7 +1209,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d existing_request = Request.init( bun.String.cloneUTF8(url.href), headers, - this.vm.initRequestBodyValue(body) catch bun.outOfMemory(), + bun.handleOom(this.vm.initRequestBodyValue(body)), method, ); } else if (first_arg.as(Request)) |request_| { @@ -2197,7 +2200,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d resp.onTimeout(*anyopaque, onTimeoutForIdleWarn, &did_send_idletimeout_warning_once); } - const ctx = this.request_pool_allocator.tryGet() catch bun.outOfMemory(); + const ctx = bun.handleOom(this.request_pool_allocator.tryGet()); ctx.create(this, req, resp, should_deinit_context, method); this.vm.jsc_vm.reportExtraMemory(@sizeOf(RequestContext)); const body = this.vm.initRequestBodyValue(.{ .Null = {} }) catch unreachable; @@ -2316,7 +2319,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } this.pending_requests += 1; req.setYield(false); - var ctx = this.request_pool_allocator.tryGet() catch bun.outOfMemory(); + var ctx = bun.handleOom(this.request_pool_allocator.tryGet()); var should_deinit_context = false; ctx.create(this, req, resp, &should_deinit_context, null); var body = this.vm.initRequestBodyValue(.{ .Null = {} }) catch unreachable; @@ -2434,7 +2437,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d const json_string = std.fmt.allocPrint(bun.default_allocator, "{{ \"workspace\": {{ \"root\": {}, \"uuid\": \"{}\" }} }}", .{ bun.fmt.formatJSONStringUTF8(this.dev_server.?.root, .{}), uuid, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); defer bun.default_allocator.free(json_string); resp.writeStatus("200 OK"); @@ -2590,7 +2593,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d .html => |html_bundle_route| { ServerConfig.applyStaticRoute(any_server, ssl_enabled, app, *HTMLBundle.Route, html_bundle_route.data, entry.path, entry.method); if (dev_server) |dev| { - dev.html_router.put(dev.allocator(), entry.path, html_bundle_route.data) catch bun.outOfMemory(); + bun.handleOom(dev.html_router.put(dev.allocator(), entry.path, html_bundle_route.data)); } needs_plugins = true; }, @@ -2621,7 +2624,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d var has_dev_server_for_star_path = false; if (dev_server) |dev| { // dev.setRoutes might register its own "/*" HTTP handler - has_dev_server_for_star_path = dev.setRoutes(this) catch bun.outOfMemory(); + has_dev_server_for_star_path = bun.handleOom(dev.setRoutes(this)); if (has_dev_server_for_star_path) { // Assume dev server "/*" covers all methods if it exists star_methods_covered_by_user = .initFull(); diff --git a/src/bun.js/api/server/FileRoute.zig b/src/bun.js/api/server/FileRoute.zig index 36d8f5d5bc..88b3eb03a1 100644 --- a/src/bun.js/api/server/FileRoute.zig +++ b/src/bun.js/api/server/FileRoute.zig @@ -35,7 +35,7 @@ pub fn lastModifiedDate(this: *const FileRoute) bun.JSError!?u64 { } pub fn initFromBlob(blob: Blob, opts: InitOptions) *FileRoute { - const headers = Headers.from(opts.headers, bun.default_allocator, .{ .body = &.{ .Blob = blob } }) catch bun.outOfMemory(); + const headers = bun.handleOom(Headers.from(opts.headers, bun.default_allocator, .{ .body = &.{ .Blob = blob } })); return bun.new(FileRoute, .{ .ref_count = .init(), .server = opts.server, @@ -70,7 +70,7 @@ pub fn fromJS(globalThis: *jsc.JSGlobalObject, argument: jsc.JSValue) bun.JSErro blob.globalThis = globalThis; blob.allocator = null; response.body.value = .{ .Blob = blob.dupe() }; - const headers = Headers.from(response.init.headers, bun.default_allocator, .{ .body = &.{ .Blob = blob } }) catch bun.outOfMemory(); + const headers = bun.handleOom(Headers.from(response.init.headers, bun.default_allocator, .{ .body = &.{ .Blob = blob } })); return bun.new(FileRoute, .{ .ref_count = .init(), @@ -92,7 +92,7 @@ pub fn fromJS(globalThis: *jsc.JSGlobalObject, argument: jsc.JSValue) bun.JSErro .ref_count = .init(), .server = null, .blob = b, - .headers = Headers.from(null, bun.default_allocator, .{ .body = &.{ .Blob = b } }) catch bun.outOfMemory(), + .headers = bun.handleOom(Headers.from(null, bun.default_allocator, .{ .body = &.{ .Blob = b } })), .has_content_length_header = false, .has_last_modified_header = false, .status_code = 200, diff --git a/src/bun.js/api/server/HTMLBundle.zig b/src/bun.js/api/server/HTMLBundle.zig index 2bf0ddc65d..c6c4e5f272 100644 --- a/src/bun.js/api/server/HTMLBundle.zig +++ b/src/bun.js/api/server/HTMLBundle.zig @@ -145,7 +145,7 @@ pub const Route = struct { if (server.config().isDevelopment()) { if (server.devServer()) |dev| { - dev.respondForHTMLBundle(this, req, resp) catch bun.outOfMemory(); + bun.handleOom(dev.respondForHTMLBundle(this, req, resp)); return; } @@ -163,7 +163,7 @@ pub const Route = struct { .pending => { if (bun.Environment.enable_logs) debug("onRequest: {s} - pending", .{req.url()}); - this.scheduleBundle(server) catch bun.outOfMemory(); + bun.handleOom(this.scheduleBundle(server)); continue :state this.state; }, .building => { @@ -182,7 +182,7 @@ pub const Route = struct { .route = this, }); - this.pending_responses.append(bun.default_allocator, pending) catch bun.outOfMemory(); + bun.handleOom(this.pending_responses.append(bun.default_allocator, pending)); this.ref(); resp.onAborted(*PendingResponse, PendingResponse.onAborted, pending); @@ -274,13 +274,13 @@ pub const Route = struct { config.define.map.unmanaged.entries.len = define.keys.len; @memcpy(config.define.map.keys(), define.keys); for (config.define.map.values(), define.values) |*to, from| { - to.* = config.define.map.allocator.dupe(u8, from) catch bun.outOfMemory(); + to.* = bun.handleOom(config.define.map.allocator.dupe(u8, from)); } try config.define.map.reIndex(); } if (!is_development) { - config.define.put("process.env.NODE_ENV", "\"production\"") catch bun.outOfMemory(); + bun.handleOom(config.define.put("process.env.NODE_ENV", "\"production\"")); config.jsx.development = false; } else { config.force_node_env = .development; @@ -318,7 +318,7 @@ pub const Route = struct { if (bun.Environment.enable_logs) debug("onComplete: err - {s}", .{@errorName(err)}); this.state = .{ .err = bun.logger.Log.init(bun.default_allocator) }; - completion_task.log.cloneToWithRecycled(&this.state.err, true) catch bun.outOfMemory(); + bun.handleOom(completion_task.log.cloneToWithRecycled(&this.state.err, true)); if (this.server) |server| { if (server.config().isDevelopment()) { @@ -360,20 +360,26 @@ pub const Route = struct { // Create static routes for each output file for (output_files) |*output_file| { - const blob = jsc.WebCore.Blob.Any{ .Blob = output_file.toBlob(bun.default_allocator, globalThis) catch bun.outOfMemory() }; + const blob = jsc.WebCore.Blob.Any{ .Blob = bun.handleOom(output_file.toBlob(bun.default_allocator, globalThis)) }; var headers = bun.http.Headers{ .allocator = bun.default_allocator }; const content_type = blob.Blob.contentTypeOrMimeType() orelse brk: { bun.debugAssert(false); // should be populated by `output_file.toBlob` break :brk output_file.loader.toMimeType(&.{}).value; }; - headers.append("Content-Type", content_type) catch bun.outOfMemory(); + bun.handleOom(headers.append("Content-Type", content_type)); // Do not apply etags to html. if (output_file.loader != .html and output_file.value == .buffer) { var hashbuf: [64]u8 = undefined; - const etag_str = std.fmt.bufPrint(&hashbuf, "{}", .{bun.fmt.hexIntLower(output_file.hash)}) catch bun.outOfMemory(); - headers.append("ETag", etag_str) catch bun.outOfMemory(); + const etag_str = std.fmt.bufPrint( + &hashbuf, + "{}", + .{bun.fmt.hexIntLower(output_file.hash)}, + ) catch |err| switch (err) { + error.NoSpaceLeft => unreachable, + }; + bun.handleOom(headers.append("ETag", etag_str)); if (!server.config().isDevelopment() and (output_file.output_kind == .chunk)) - headers.append("Cache-Control", "public, max-age=31536000") catch bun.outOfMemory(); + bun.handleOom(headers.append("Cache-Control", "public, max-age=31536000")); } // Add a SourceMap header if we have a source map index @@ -384,7 +390,7 @@ pub const Route = struct { if (strings.hasPrefixComptime(route_path, "./") or strings.hasPrefixComptime(route_path, ".\\")) { route_path = route_path[1..]; } - headers.append("SourceMap", route_path) catch bun.outOfMemory(); + bun.handleOom(headers.append("SourceMap", route_path)); } } @@ -410,14 +416,14 @@ pub const Route = struct { route_path = route_path[1..]; } - server.appendStaticRoute(route_path, .{ .static = static_route }, .any) catch bun.outOfMemory(); + bun.handleOom(server.appendStaticRoute(route_path, .{ .static = static_route }, .any)); } const html_route: *StaticRoute = this_html_route orelse @panic("Internal assertion failure: HTML entry point not found in HTMLBundle."); - const html_route_clone = html_route.clone(globalThis) catch bun.outOfMemory(); + const html_route_clone = bun.handleOom(html_route.clone(globalThis)); this.state = .{ .html = html_route_clone }; - if (!(server.reloadStaticRoutes() catch bun.outOfMemory())) { + if (!bun.handleOom(server.reloadStaticRoutes())) { // Server has shutdown, so it won't receive any new requests // TODO: handle this case } diff --git a/src/bun.js/api/server/NodeHTTPResponse.zig b/src/bun.js/api/server/NodeHTTPResponse.zig index d1f88f847d..2e0f8883ed 100644 --- a/src/bun.js/api/server/NodeHTTPResponse.zig +++ b/src/bun.js/api/server/NodeHTTPResponse.zig @@ -84,13 +84,13 @@ pub const UpgradeCTX = struct { const sec_websocket_extensions = request.header("sec-websocket-extensions") orelse ""; if (sec_websocket_key.len > 0) { - this.sec_websocket_key = bun.default_allocator.dupe(u8, sec_websocket_key) catch bun.outOfMemory(); + this.sec_websocket_key = bun.handleOom(bun.default_allocator.dupe(u8, sec_websocket_key)); } if (sec_websocket_protocol.len > 0) { - this.sec_websocket_protocol = bun.default_allocator.dupe(u8, sec_websocket_protocol) catch bun.outOfMemory(); + this.sec_websocket_protocol = bun.handleOom(bun.default_allocator.dupe(u8, sec_websocket_protocol)); } if (sec_websocket_extensions.len > 0) { - this.sec_websocket_extensions = bun.default_allocator.dupe(u8, sec_websocket_extensions) catch bun.outOfMemory(); + this.sec_websocket_extensions = bun.handleOom(bun.default_allocator.dupe(u8, sec_websocket_extensions)); } } } @@ -490,7 +490,7 @@ pub fn writeHead(this: *NodeHTTPResponse, globalObject: *jsc.JSGlobalObject, cal } const message = if (status_message_slice.len > 0) status_message_slice.slice() else "HM"; - const status_message = std.fmt.allocPrint(allocator, "{d} {s}", .{ status_code, message }) catch bun.outOfMemory(); + const status_message = bun.handleOom(std.fmt.allocPrint(allocator, "{d} {s}", .{ status_code, message })); defer allocator.free(status_message); writeHeadInternal(this.raw_response, globalObject, status_message, headers_object_value); break :do_it; @@ -705,7 +705,7 @@ pub fn abort(this: *NodeHTTPResponse, _: *jsc.JSGlobalObject, _: *jsc.CallFrame) fn onBufferRequestBodyWhilePaused(this: *NodeHTTPResponse, chunk: []const u8, last: bool) void { log("onBufferRequestBodyWhilePaused({d}, {})", .{ chunk.len, last }); - this.buffered_request_body_data_during_pause.append(bun.default_allocator, chunk) catch bun.outOfMemory(); + bun.handleOom(this.buffered_request_body_data_during_pause.append(bun.default_allocator, chunk)); if (last) { this.flags.is_data_buffered_during_pause_last = true; if (this.body_read_ref.has) { diff --git a/src/bun.js/api/server/ServerConfig.zig b/src/bun.js/api/server/ServerConfig.zig index 33cb88f1b9..907e878bf9 100644 --- a/src/bun.js/api/server/ServerConfig.zig +++ b/src/bun.js/api/server/ServerConfig.zig @@ -346,7 +346,7 @@ fn validateRouteName(global: *jsc.JSGlobalObject, path: []const u8) !void { ); } - const entry = duped_route_names.getOrPut(route_name) catch bun.outOfMemory(); + const entry = bun.handleOom(duped_route_names.getOrPut(route_name)); if (entry.found_existing) { return global.throwTODO( \\Support for duplicate route parameter names is not yet implemented. @@ -533,7 +533,7 @@ pub fn fromJS( } while (try iter.next()) |key| { - const path, const is_ascii = key.toOwnedSliceReturningAllASCII(bun.default_allocator) catch bun.outOfMemory(); + const path, const is_ascii = bun.handleOom(key.toOwnedSliceReturningAllASCII(bun.default_allocator)); errdefer bun.default_allocator.free(path); const value: jsc.JSValue = iter.value; @@ -551,9 +551,9 @@ pub fn fromJS( } if (value == .false) { - const duped = bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(); + const duped = bun.handleOom(bun.default_allocator.dupeZ(u8, path)); defer bun.default_allocator.free(path); - args.negative_routes.append(duped) catch bun.outOfMemory(); + bun.handleOom(args.negative_routes.append(duped)); continue; } @@ -561,11 +561,11 @@ pub fn fromJS( try validateRouteName(global, path); args.user_routes_to_build.append(.{ .route = .{ - .path = bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(), + .path = bun.handleOom(bun.default_allocator.dupeZ(u8, path)), .method = .any, }, .callback = .create(value.withAsyncContextIfNeeded(global), global), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); bun.default_allocator.free(path); continue; } else if (value.isObject()) { @@ -591,20 +591,20 @@ pub fn fromJS( if (function.isCallable()) { args.user_routes_to_build.append(.{ .route = .{ - .path = bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(), + .path = bun.handleOom(bun.default_allocator.dupeZ(u8, path)), .method = .{ .specific = method }, }, .callback = .create(function.withAsyncContextIfNeeded(global), global), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } else if (try AnyRoute.fromJS(global, path, function, init_ctx)) |html_route| { var method_set = bun.http.Method.Set.initEmpty(); method_set.insert(method); args.static_routes.append(.{ - .path = bun.default_allocator.dupe(u8, path) catch bun.outOfMemory(), + .path = bun.handleOom(bun.default_allocator.dupe(u8, path)), .route = html_route, .method = .{ .method = method_set }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } } } @@ -659,7 +659,7 @@ pub fn fromJS( args.static_routes.append(.{ .path = path, .route = route, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } // When HTML bundles are provided, ensure DevServer options are ready @@ -936,10 +936,10 @@ pub fn fromJS( return global.throwInvalidArguments("SNI tls object must have a serverName", .{}); } if (args.sni == null) { - args.sni = bun.BabyList(SSLConfig).initCapacity(bun.default_allocator, value_iter.len - 1) catch bun.outOfMemory(); + args.sni = bun.handleOom(bun.BabyList(SSLConfig).initCapacity(bun.default_allocator, value_iter.len - 1)); } - args.sni.?.push(bun.default_allocator, ssl_config) catch bun.outOfMemory(); + bun.handleOom(args.sni.?.push(bun.default_allocator, ssl_config)); } } } diff --git a/src/bun.js/api/server/StaticRoute.zig b/src/bun.js/api/server/StaticRoute.zig index 0e504d0ece..7fbfcd5758 100644 --- a/src/bun.js/api/server/StaticRoute.zig +++ b/src/bun.js/api/server/StaticRoute.zig @@ -28,17 +28,17 @@ pub const InitFromBytesOptions = struct { /// Ownership of `blob` is transferred to this function. pub fn initFromAnyBlob(blob: *const AnyBlob, options: InitFromBytesOptions) *StaticRoute { - var headers = Headers.from(options.headers, bun.default_allocator, .{ .body = blob }) catch bun.outOfMemory(); + var headers = bun.handleOom(Headers.from(options.headers, bun.default_allocator, .{ .body = blob })); if (options.mime_type) |mime_type| { if (headers.getContentType() == null) { - headers.append("Content-Type", mime_type.value) catch bun.outOfMemory(); + bun.handleOom(headers.append("Content-Type", mime_type.value)); } } // Generate ETag if not already present if (headers.get("etag") == null) { if (blob.slice().len > 0) { - ETag.appendToHeaders(blob.slice(), &headers) catch bun.outOfMemory(); + bun.handleOom(ETag.appendToHeaders(blob.slice(), &headers)); } } diff --git a/src/bun.js/bindings/DeferredError.zig b/src/bun.js/bindings/DeferredError.zig index a1a4b6ff3d..17c3e0987e 100644 --- a/src/bun.js/bindings/DeferredError.zig +++ b/src/bun.js/bindings/DeferredError.zig @@ -11,7 +11,7 @@ pub const DeferredError = struct { return .{ .kind = kind, .code = code, - .msg = bun.String.createFormat(fmt, args) catch bun.outOfMemory(), + .msg = bun.handleOom(bun.String.createFormat(fmt, args)), }; } diff --git a/src/bun.js/bindings/HTTPServerAgent.zig b/src/bun.js/bindings/HTTPServerAgent.zig index ac7356281c..7f74625d92 100644 --- a/src/bun.js/bindings/HTTPServerAgent.zig +++ b/src/bun.js/bindings/HTTPServerAgent.zig @@ -15,7 +15,7 @@ pub fn notifyServerStarted(this: *HTTPServerAgent, instance: jsc.API.AnyServer) if (this.agent) |agent| { this.next_server_id = .init(this.next_server_id.get() + 1); instance.setInspectorServerID(this.next_server_id); - var url = instance.getURLAsString() catch bun.outOfMemory(); + var url = bun.handleOom(instance.getURLAsString()); defer url.deref(); agent.notifyServerStarted( diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig index ec80439d46..e5ea83b5d3 100644 --- a/src/bun.js/event_loop.zig +++ b/src/bun.js/event_loop.zig @@ -216,7 +216,7 @@ pub fn tickImmediateTasks(this: *EventLoop, virtual_machine: *VirtualMachine) vo if (this.next_immediate_tasks.capacity > 0) { // this would only occur if we were recursively running tickImmediateTasks. @branchHint(.unlikely); - this.immediate_tasks.appendSlice(bun.default_allocator, this.next_immediate_tasks.items) catch bun.outOfMemory(); + bun.handleOom(this.immediate_tasks.appendSlice(bun.default_allocator, this.next_immediate_tasks.items)); this.next_immediate_tasks.deinit(bun.default_allocator); } @@ -529,7 +529,7 @@ pub fn enqueueTask(this: *EventLoop, task: Task) void { } pub fn enqueueImmediateTask(this: *EventLoop, task: *Timer.ImmediateObject) void { - this.immediate_tasks.append(bun.default_allocator, task) catch bun.outOfMemory(); + bun.handleOom(this.immediate_tasks.append(bun.default_allocator, task)); } pub fn ensureWaker(this: *EventLoop) void { diff --git a/src/bun.js/event_loop/AnyTaskWithExtraContext.zig b/src/bun.js/event_loop/AnyTaskWithExtraContext.zig index 4a5771bcbf..42cc957ca6 100644 --- a/src/bun.js/event_loop/AnyTaskWithExtraContext.zig +++ b/src/bun.js/event_loop/AnyTaskWithExtraContext.zig @@ -19,7 +19,7 @@ pub fn fromCallbackAutoDeinit(ptr: anytype, comptime fieldName: [:0]const u8) *A @field(Ptr, fieldName)(ctx, extra); } }; - const task = bun.default_allocator.create(Wrapper) catch bun.outOfMemory(); + const task = bun.handleOom(bun.default_allocator.create(Wrapper)); task.* = Wrapper{ .any_task = AnyTaskWithExtraContext{ .callback = &Wrapper.function, diff --git a/src/bun.js/event_loop/DeferredTaskQueue.zig b/src/bun.js/event_loop/DeferredTaskQueue.zig index 07fc17c482..9a7d803735 100644 --- a/src/bun.js/event_loop/DeferredTaskQueue.zig +++ b/src/bun.js/event_loop/DeferredTaskQueue.zig @@ -33,7 +33,7 @@ pub const DeferredRepeatingTask = *const (fn (*anyopaque) bool); map: std.AutoArrayHashMapUnmanaged(?*anyopaque, DeferredRepeatingTask) = .{}, pub fn postTask(this: *DeferredTaskQueue, ctx: ?*anyopaque, task: DeferredRepeatingTask) bool { - const existing = this.map.getOrPutValue(bun.default_allocator, ctx, task) catch bun.outOfMemory(); + const existing = bun.handleOom(this.map.getOrPutValue(bun.default_allocator, ctx, task)); return existing.found_existing; } diff --git a/src/bun.js/event_loop/ManagedTask.zig b/src/bun.js/event_loop/ManagedTask.zig index 453face69a..49eba9f72b 100644 --- a/src/bun.js/event_loop/ManagedTask.zig +++ b/src/bun.js/event_loop/ManagedTask.zig @@ -27,7 +27,7 @@ pub fn cancel(this: *ManagedTask) void { pub fn New(comptime Type: type, comptime Callback: anytype) type { return struct { pub fn init(ctx: *Type) Task { - var managed = bun.default_allocator.create(ManagedTask) catch bun.outOfMemory(); + var managed = bun.handleOom(bun.default_allocator.create(ManagedTask)); managed.* = ManagedTask{ .callback = wrap, .ctx = ctx, diff --git a/src/bun.js/event_loop/MiniEventLoop.zig b/src/bun.js/event_loop/MiniEventLoop.zig index 56b407a15e..bcca2bf428 100644 --- a/src/bun.js/event_loop/MiniEventLoop.zig +++ b/src/bun.js/event_loop/MiniEventLoop.zig @@ -43,14 +43,14 @@ pub const ConcurrentTaskQueue = UnboundedQueue(AnyTaskWithExtraContext, .next); pub fn initGlobal(env: ?*bun.DotEnv.Loader) *MiniEventLoop { if (globalInitialized) return global; const loop = MiniEventLoop.init(bun.default_allocator); - global = bun.default_allocator.create(MiniEventLoop) catch bun.outOfMemory(); + global = bun.handleOom(bun.default_allocator.create(MiniEventLoop)); global.* = loop; global.loop.internal_loop_data.setParentEventLoop(bun.jsc.EventLoopHandle.init(global)); global.env = env orelse bun.DotEnv.instance orelse env_loader: { - const map = bun.default_allocator.create(bun.DotEnv.Map) catch bun.outOfMemory(); + const map = bun.handleOom(bun.default_allocator.create(bun.DotEnv.Map)); map.* = bun.DotEnv.Map.init(bun.default_allocator); - const loader = bun.default_allocator.create(bun.DotEnv.Loader) catch bun.outOfMemory(); + const loader = bun.handleOom(bun.default_allocator.create(bun.DotEnv.Loader)); loader.* = bun.DotEnv.Loader.init(map, bun.default_allocator); break :env_loader loader; }; @@ -73,7 +73,7 @@ pub fn throwError(_: *MiniEventLoop, err: bun.sys.Error) void { pub fn pipeReadBuffer(this: *MiniEventLoop) []u8 { return this.pipe_read_buffer orelse { - this.pipe_read_buffer = this.allocator.create(PipeReadBuffer) catch bun.outOfMemory(); + this.pipe_read_buffer = bun.handleOom(this.allocator.create(PipeReadBuffer)); return this.pipe_read_buffer.?; }; } @@ -89,7 +89,7 @@ pub fn onAfterEventLoop(this: *MiniEventLoop) void { pub fn filePolls(this: *MiniEventLoop) *Async.FilePoll.Store { return this.file_polls_ orelse { - this.file_polls_ = this.allocator.create(Async.FilePoll.Store) catch bun.outOfMemory(); + this.file_polls_ = bun.handleOom(this.allocator.create(Async.FilePoll.Store)); this.file_polls_.?.* = Async.FilePoll.Store.init(); return this.file_polls_.?; }; diff --git a/src/bun.js/hot_reloader.zig b/src/bun.js/hot_reloader.zig index e567078278..90a9b74d30 100644 --- a/src/bun.js/hot_reloader.zig +++ b/src/bun.js/hot_reloader.zig @@ -66,7 +66,7 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime tombstones: bun.StringHashMapUnmanaged(*bun.fs.FileSystem.RealFS.EntriesOption) = .{}, pub fn init(ctx: *Ctx, fs: *bun.fs.FileSystem, verbose: bool, clear_screen_flag: bool) *Watcher { - const reloader = bun.default_allocator.create(Reloader) catch bun.outOfMemory(); + const reloader = bun.handleOom(bun.default_allocator.create(Reloader)); reloader.* = .{ .ctx = ctx, .verbose = Environment.enable_logs or verbose, @@ -193,7 +193,7 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime return; } - var reloader = bun.default_allocator.create(Reloader) catch bun.outOfMemory(); + var reloader = bun.handleOom(bun.default_allocator.create(Reloader)); reloader.* = .{ .ctx = this, .verbose = Environment.enable_logs or if (@hasField(Ctx, "log")) this.log.level.atLeast(.info) else false, diff --git a/src/bun.js/ipc.zig b/src/bun.js/ipc.zig index 949038c48e..6ce31d65c4 100644 --- a/src/bun.js/ipc.zig +++ b/src/bun.js/ipc.zig @@ -583,7 +583,7 @@ pub const SendQueue = struct { } // fallback case: append a new message to the queue - self.queue.append(.{ .handle = handle, .callbacks = .init(callback) }) catch bun.outOfMemory(); + bun.handleOom(self.queue.append(.{ .handle = handle, .callbacks = .init(callback) })); return &self.queue.items[self.queue.items.len - 1]; } /// returned pointer is invalidated if the queue is modified @@ -592,11 +592,11 @@ pub const SendQueue = struct { if (Environment.allow_assert) bun.debugAssert(this.has_written_version == 1); if ((this.queue.items.len == 0 or this.queue.items[0].data.cursor == 0) and !this.write_in_progress) { // prepend (we have not started sending the next message yet because we are waiting for the ack/nack) - this.queue.insert(0, message) catch bun.outOfMemory(); + bun.handleOom(this.queue.insert(0, message)); } else { // insert at index 1 (we are in the middle of sending a message to the other process) bun.debugAssert(this.queue.items[0].isAckNack()); - this.queue.insert(1, message) catch bun.outOfMemory(); + bun.handleOom(this.queue.insert(1, message)); } } @@ -745,8 +745,8 @@ pub const SendQueue = struct { bun.debugAssert(this.waiting_for_ack == null); const bytes = getVersionPacket(this.mode); if (bytes.len > 0) { - this.queue.append(.{ .handle = null, .callbacks = .none }) catch bun.outOfMemory(); - this.queue.items[this.queue.items.len - 1].data.write(bytes) catch bun.outOfMemory(); + bun.handleOom(this.queue.append(.{ .handle = null, .callbacks = .none })); + bun.handleOom(this.queue.items[this.queue.items.len - 1].data.write(bytes)); log("IPC call continueSend() from version packet", .{}); this.continueSend(global, .new_message_appended); } @@ -804,7 +804,7 @@ pub const SendQueue = struct { const write_len = @min(data.len, std.math.maxInt(i32)); // create write request - const write_req_slice = bun.default_allocator.dupe(u8, data[0..write_len]) catch bun.outOfMemory(); + const write_req_slice = bun.handleOom(bun.default_allocator.dupe(u8, data[0..write_len])); const write_req = bun.new(WindowsWrite, .{ .owner = this, .write_slice = write_req_slice, @@ -885,7 +885,7 @@ pub const SendQueue = struct { pub fn windowsConfigureClient(this: *SendQueue, pipe_fd: bun.FileDescriptor) !void { log("configureClient", .{}); - const ipc_pipe = bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory(); + const ipc_pipe = bun.handleOom(bun.default_allocator.create(uv.Pipe)); ipc_pipe.init(uv.Loop.get(), true).unwrap() catch |err| { bun.default_allocator.destroy(ipc_pipe); return err; @@ -1068,7 +1068,7 @@ fn handleIPCMessage(send_queue: *SendQueue, message: DecodedIPCMessage, globalTh const packet = if (ack) getAckPacket(send_queue.mode) else getNackPacket(send_queue.mode); var handle = SendHandle{ .data = .{}, .handle = null, .callbacks = .ack_nack }; - handle.data.write(packet) catch bun.outOfMemory(); + bun.handleOom(handle.data.write(packet)); // Insert at appropriate position in send queue send_queue.insertMessage(handle); @@ -1134,7 +1134,7 @@ fn onData2(send_queue: *SendQueue, all_data: []const u8) void { while (true) { const result = decodeIPCMessage(send_queue.mode, data, globalThis) catch |e| switch (e) { error.NotEnoughBytes => { - _ = send_queue.incoming.write(bun.default_allocator, data) catch bun.outOfMemory(); + _ = bun.handleOom(send_queue.incoming.write(bun.default_allocator, data)); log("hit NotEnoughBytes", .{}); return; }, @@ -1159,7 +1159,7 @@ fn onData2(send_queue: *SendQueue, all_data: []const u8) void { } } - _ = send_queue.incoming.write(bun.default_allocator, data) catch bun.outOfMemory(); + _ = bun.handleOom(send_queue.incoming.write(bun.default_allocator, data)); var slice = send_queue.incoming.slice(); while (true) { @@ -1299,7 +1299,7 @@ pub const IPCHandlers = struct { fn onReadAlloc(send_queue: *SendQueue, suggested_size: usize) []u8 { var available = send_queue.incoming.available(); if (available.len < suggested_size) { - send_queue.incoming.ensureUnusedCapacity(bun.default_allocator, suggested_size) catch bun.outOfMemory(); + bun.handleOom(send_queue.incoming.ensureUnusedCapacity(bun.default_allocator, suggested_size)); available = send_queue.incoming.available(); } log("NewNamedPipeIPCHandler#onReadAlloc {d}", .{suggested_size}); diff --git a/src/bun.js/node/node_cluster_binding.zig b/src/bun.js/node/node_cluster_binding.zig index 2d77be20f7..ba6dafd3d4 100644 --- a/src/bun.js/node/node_cluster_binding.zig +++ b/src/bun.js/node/node_cluster_binding.zig @@ -35,7 +35,7 @@ pub fn sendHelperChild(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFram if (callback.isFunction()) { // TODO: remove this strong. This is expensive and would be an easy way to create a memory leak. // These sequence numbers shouldn't exist from JavaScript's perspective at all. - child_singleton.callbacks.put(bun.default_allocator, child_singleton.seq, jsc.Strong.Optional.create(callback, globalThis)) catch bun.outOfMemory(); + bun.handleOom(child_singleton.callbacks.put(bun.default_allocator, child_singleton.seq, jsc.Strong.Optional.create(callback, globalThis))); } // sequence number for InternalMsgHolder @@ -107,7 +107,7 @@ pub const InternalMsgHolder = struct { pub fn enqueue(this: *InternalMsgHolder, message: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { //TODO: .addOne is workaround for .append causing crash/ dependency loop in zig compiler - const new_item_ptr = this.messages.addOne(bun.default_allocator) catch bun.outOfMemory(); + const new_item_ptr = bun.handleOom(this.messages.addOne(bun.default_allocator)); new_item_ptr.* = .create(message, globalThis); } @@ -190,7 +190,7 @@ pub fn sendHelperPrimary(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFr return globalThis.throwInvalidArgumentTypeValue("message", "object", message); } if (callback.isFunction()) { - ipc_data.internal_msg_queue.callbacks.put(bun.default_allocator, ipc_data.internal_msg_queue.seq, jsc.Strong.Optional.create(callback, globalThis)) catch bun.outOfMemory(); + bun.handleOom(ipc_data.internal_msg_queue.callbacks.put(bun.default_allocator, ipc_data.internal_msg_queue.seq, jsc.Strong.Optional.create(callback, globalThis))); } // sequence number for InternalMsgHolder diff --git a/src/bun.js/node/node_crypto_binding.zig b/src/bun.js/node/node_crypto_binding.zig index 0092b7794a..fd3d2a75be 100644 --- a/src/bun.js/node/node_crypto_binding.zig +++ b/src/bun.js/node/node_crypto_binding.zig @@ -488,7 +488,7 @@ pub fn setEngine(global: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { fn forEachHash(_: *const BoringSSL.EVP_MD, maybe_from: ?[*:0]const u8, _: ?[*:0]const u8, ctx: *anyopaque) callconv(.c) void { const from = maybe_from orelse return; const hashes: *bun.CaseInsensitiveASCIIStringArrayHashMap(void) = @alignCast(@ptrCast(ctx)); - hashes.put(bun.span(from), {}) catch bun.outOfMemory(); + bun.handleOom(hashes.put(bun.span(from), {})); } fn getHashes(global: *JSGlobalObject, _: *jsc.CallFrame) JSError!JSValue { diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig index 6f875dbb9d..2198006d15 100644 --- a/src/bun.js/node/node_fs.zig +++ b/src/bun.js/node/node_fs.zig @@ -98,7 +98,7 @@ pub const Async = struct { ); switch (result) { .err => |err| { - this.completion(this.completion_ctx, .{ .err = err.withPath(bun.default_allocator.dupe(u8, err.path) catch bun.outOfMemory()) }); + this.completion(this.completion_ctx, .{ .err = err.withPath(bun.handleOom(bun.default_allocator.dupe(u8, err.path))) }); }, .result => { this.completion(this.completion_ctx, .success); @@ -898,7 +898,7 @@ pub fn NewAsyncCpTask(comptime is_shell: bool) type { var path_buf = bun.default_allocator.alloc( bun.OSPathChar, src_dir_len + 1 + cname.len + 1 + dest_dir_len + 1 + cname.len + 1, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); @memcpy(path_buf[0..src_dir_len], src_buf[0..src_dir_len]); path_buf[src_dir_len] = std.fs.path.sep; @@ -1020,7 +1020,7 @@ pub const AsyncReaddirRecursiveTask = struct { var task = Subtask.new( .{ .readdir_task = readdir_task, - .basename = bun.PathString.init(bun.default_allocator.dupeZ(u8, basename) catch bun.outOfMemory()), + .basename = bun.PathString.init(bun.handleOom(bun.default_allocator.dupeZ(u8, basename))), }, ); bun.assert(readdir_task.subtask_count.fetchAdd(1, .monotonic) > 0); @@ -1039,7 +1039,7 @@ pub const AsyncReaddirRecursiveTask = struct { .globalObject = globalObject, .tracker = jsc.Debugger.AsyncTaskTracker.init(vm), .subtask_count = .{ .raw = 1 }, - .root_path = PathString.init(bun.default_allocator.dupeZ(u8, args.path.slice()) catch bun.outOfMemory()), + .root_path = PathString.init(bun.handleOom(bun.default_allocator.dupeZ(u8, args.path.slice()))), .result_list = switch (args.tag()) { .files => .{ .files = std.ArrayList(bun.String).init(bun.default_allocator) }, .with_file_types => .{ .with_file_types = .init(bun.default_allocator) }, @@ -1124,11 +1124,11 @@ pub const AsyncReaddirRecursiveTask = struct { Buffer => .buffers, else => @compileError("unreachable"), }; - const list = bun.default_allocator.create(ResultListEntry) catch bun.outOfMemory(); + const list = bun.handleOom(bun.default_allocator.create(ResultListEntry)); errdefer { bun.default_allocator.destroy(list); } - var clone = std.ArrayList(ResultType).initCapacity(bun.default_allocator, result.items.len) catch bun.outOfMemory(); + var clone = bun.handleOom(std.ArrayList(ResultType).initCapacity(bun.default_allocator, result.items.len)); clone.appendSliceAssumeCapacity(result.items); _ = this.result_list_count.fetchAdd(clone.items.len, .monotonic); list.* = ResultListEntry{ .next = null, .value = @unionInit(ResultListEntry.Value, @tagName(Field), clone) }; @@ -1171,7 +1171,7 @@ pub const AsyncReaddirRecursiveTask = struct { switch (this.args.tag()) { inline else => |tag| { var results = &@field(this.result_list, @tagName(tag)); - results.ensureTotalCapacityPrecise(this.result_list_count.swap(0, .monotonic)) catch bun.outOfMemory(); + bun.handleOom(results.ensureTotalCapacityPrecise(this.result_list_count.swap(0, .monotonic))); while (iter.next()) |val| { if (to_destroy) |dest| { bun.default_allocator.destroy(dest); @@ -1339,7 +1339,7 @@ pub const Arguments = struct { pub fn toThreadSafe(this: *@This()) void { this.buffers.value.protect(); - const clone = bun.default_allocator.dupe(bun.PlatformIOVec, this.buffers.buffers.items) catch bun.outOfMemory(); + const clone = bun.handleOom(bun.default_allocator.dupe(bun.PlatformIOVec, this.buffers.buffers.items)); this.buffers.buffers.deinit(); this.buffers.buffers.items = clone; this.buffers.buffers.capacity = clone.len; @@ -1393,7 +1393,7 @@ pub const Arguments = struct { pub fn toThreadSafe(this: *@This()) void { this.buffers.value.protect(); - const clone = bun.default_allocator.dupe(bun.PlatformIOVec, this.buffers.buffers.items) catch bun.outOfMemory(); + const clone = bun.handleOom(bun.default_allocator.dupe(bun.PlatformIOVec, this.buffers.buffers.items)); this.buffers.buffers.deinit(); this.buffers.buffers.items = clone; this.buffers.buffers.capacity = clone.len; @@ -4129,14 +4129,14 @@ pub const NodeFS = struct { } }; } return .{ - .result = jsc.ZigString.dupeForJS(bun.sliceTo(req.path, 0), bun.default_allocator) catch bun.outOfMemory(), + .result = bun.handleOom(jsc.ZigString.dupeForJS(bun.sliceTo(req.path, 0), bun.default_allocator)), }; } const rc = c.mkdtemp(prefix_buf); if (rc) |ptr| { return .{ - .result = jsc.ZigString.dupeForJS(bun.sliceTo(ptr, 0), bun.default_allocator) catch bun.outOfMemory(), + .result = bun.handleOom(jsc.ZigString.dupeForJS(bun.sliceTo(ptr, 0), bun.default_allocator)), }; } @@ -4478,13 +4478,13 @@ pub const NodeFS = struct { .name = jsc.WebCore.encoding.toBunString(utf8_name, args.encoding), .path = dirent_path, .kind = current.kind, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); }, Buffer => { - entries.append(Buffer.fromString(utf8_name, bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(entries.append(bun.handleOom(Buffer.fromString(utf8_name, bun.default_allocator)))); }, bun.String => { - entries.append(jsc.WebCore.encoding.toBunString(utf8_name, args.encoding)) catch bun.outOfMemory(); + bun.handleOom(entries.append(jsc.WebCore.encoding.toBunString(utf8_name, args.encoding))); }, else => @compileError("unreachable"), } @@ -4497,16 +4497,16 @@ pub const NodeFS = struct { .name = bun.String.cloneUTF16(utf16_name), .path = dirent_path, .kind = current.kind, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); }, bun.String => switch (args.encoding) { .buffer => unreachable, // in node.js, libuv converts to utf8 before node.js converts those bytes into other stuff // all encodings besides hex, base64, and base64url are mis-interpreting filesystem bytes. - .utf8 => entries.append(bun.String.cloneUTF16(utf16_name)) catch bun.outOfMemory(), + .utf8 => bun.handleOom(entries.append(bun.String.cloneUTF16(utf16_name))), else => |enc| { const utf8_path = bun.strings.fromWPath(re_encoding_buffer.?, utf16_name); - entries.append(jsc.WebCore.encoding.toBunString(utf8_path, enc)) catch bun.outOfMemory(); + bun.handleOom(entries.append(jsc.WebCore.encoding.toBunString(utf8_path, enc))); }, }, else => @compileError("unreachable"), @@ -4638,13 +4638,13 @@ pub const NodeFS = struct { .name = bun.String.cloneUTF8(utf8_name), .path = dirent_path_prev, .kind = current.kind, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); }, Buffer => { - entries.append(Buffer.fromString(name_to_copy, bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(entries.append(bun.handleOom(Buffer.fromString(name_to_copy, bun.default_allocator)))); }, bun.String => { - entries.append(bun.String.cloneUTF8(name_to_copy)) catch bun.outOfMemory(); + bun.handleOom(entries.append(bun.String.cloneUTF8(name_to_copy))); }, else => bun.outOfMemory(), } @@ -4777,13 +4777,13 @@ pub const NodeFS = struct { .name = jsc.WebCore.encoding.toBunString(utf8_name, args.encoding), .path = dirent_path_prev, .kind = current.kind, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); }, Buffer => { - entries.append(Buffer.fromString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), bun.default_allocator) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(entries.append(bun.handleOom(Buffer.fromString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), bun.default_allocator)))); }, bun.String => { - entries.append(jsc.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), args.encoding)) catch bun.outOfMemory(); + bun.handleOom(entries.append(jsc.WebCore.encoding.toBunString(strings.withoutNTPrefix(std.meta.Child(@TypeOf(name_to_copy)), name_to_copy), args.encoding))); }, else => @compileError(unreachable), } @@ -4936,7 +4936,7 @@ pub const NodeFS = struct { return .{ .result = .{ .buffer = Buffer.fromBytes( - bun.default_allocator.dupe(u8, file.contents) catch bun.outOfMemory(), + bun.handleOom(bun.default_allocator.dupe(u8, file.contents)), bun.default_allocator, .Uint8Array, ), @@ -4945,13 +4945,13 @@ pub const NodeFS = struct { } else if (comptime string_type == .default) return .{ .result = .{ - .string = bun.default_allocator.dupe(u8, file.contents) catch bun.outOfMemory(), + .string = bun.handleOom(bun.default_allocator.dupe(u8, file.contents)), }, } else return .{ .result = .{ - .null_terminated = bun.default_allocator.dupeZ(u8, file.contents) catch bun.outOfMemory(), + .null_terminated = bun.handleOom(bun.default_allocator.dupeZ(u8, file.contents)), }, }; } @@ -5860,7 +5860,7 @@ pub const NodeFS = struct { bun.assert(flavor == .sync); const watcher = args.createStatWatcher() catch |err| { - const buf = std.fmt.allocPrint(bun.default_allocator, "Failed to watch file {}", .{bun.fmt.QuotedFormatter{ .text = args.path.slice() }}) catch bun.outOfMemory(); + const buf = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to watch file {}", .{bun.fmt.QuotedFormatter{ .text = args.path.slice() }})); defer bun.default_allocator.free(buf); args.global_this.throwValue((jsc.SystemError{ .message = bun.String.init(buf), diff --git a/src/bun.js/node/node_fs_stat_watcher.zig b/src/bun.js/node/node_fs_stat_watcher.zig index 22277a38e2..c10a391f3f 100644 --- a/src/bun.js/node/node_fs_stat_watcher.zig +++ b/src/bun.js/node/node_fs_stat_watcher.zig @@ -102,7 +102,7 @@ pub const StatWatcherScheduler = struct { self.scheduler.setTimer(self.scheduler.getInterval()); } }; - const holder = bun.default_allocator.create(Holder) catch bun.outOfMemory(); + const holder = bun.handleOom(bun.default_allocator.create(Holder)); holder.* = .{ .scheduler = this, .task = jsc.AnyTask.New(Holder, Holder.updateTimer).init(holder), diff --git a/src/bun.js/node/node_fs_watcher.zig b/src/bun.js/node/node_fs_watcher.zig index ff732fd413..a108be9464 100644 --- a/src/bun.js/node/node_fs_watcher.zig +++ b/src/bun.js/node/node_fs_watcher.zig @@ -275,7 +275,7 @@ pub const FSWatcher = struct { } } - const cloned = event.dupe() catch bun.outOfMemory(); + const cloned = bun.handleOom(event.dupe()); this.current_task.append(cloned, true); } diff --git a/src/bun.js/node/node_process.zig b/src/bun.js/node/node_process.zig index 8d6976bfd7..2ece5bc0f4 100644 --- a/src/bun.js/node/node_process.zig +++ b/src/bun.js/node/node_process.zig @@ -26,7 +26,7 @@ pub fn setTitle(globalObject: *JSGlobalObject, newvalue: *ZigString) callconv(.C title_mutex.lock(); defer title_mutex.unlock(); if (bun.cli.Bun__Node__ProcessTitle) |_| bun.default_allocator.free(bun.cli.Bun__Node__ProcessTitle.?); - bun.cli.Bun__Node__ProcessTitle = newvalue.dupe(bun.default_allocator) catch bun.outOfMemory(); + bun.cli.Bun__Node__ProcessTitle = bun.handleOom(newvalue.dupe(bun.default_allocator)); return newvalue.toJS(globalObject); } @@ -160,7 +160,7 @@ fn createArgv(globalObject: *jsc.JSGlobalObject) callconv(.C) jsc.JSValue { // argv omits "bun" because it could be "bun run" or "bun" and it's kind of ambiguous // argv also omits the script name args_count + 2, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); defer allocator.free(args); var args_list: std.ArrayListUnmanaged(bun.String) = .initBuffer(args); @@ -300,9 +300,9 @@ pub fn Bun__Process__editWindowsEnvVar(k: bun.String, v: bun.String) callconv(.C const wtf1 = k.value.WTFStringImpl; var fixed_stack_allocator = std.heap.stackFallback(1025, bun.default_allocator); const allocator = fixed_stack_allocator.get(); - var buf1 = allocator.alloc(u16, k.utf16ByteLength() + 1) catch bun.outOfMemory(); + var buf1 = bun.handleOom(allocator.alloc(u16, k.utf16ByteLength() + 1)); defer allocator.free(buf1); - var buf2 = allocator.alloc(u16, v.utf16ByteLength() + 1) catch bun.outOfMemory(); + var buf2 = bun.handleOom(allocator.alloc(u16, v.utf16ByteLength() + 1)); defer allocator.free(buf2); const len1: usize = switch (wtf1.is8Bit()) { true => bun.strings.copyLatin1IntoUTF16([]u16, buf1, []const u8, wtf1.latin1Slice()).written, diff --git a/src/bun.js/node/node_util_binding.zig b/src/bun.js/node/node_util_binding.zig index 89fd03cde0..e8e4d96202 100644 --- a/src/bun.js/node/node_util_binding.zig +++ b/src/bun.js/node/node_util_binding.zig @@ -94,7 +94,7 @@ pub fn internalErrorName(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFr if (err_int == -bun.sys.UV_E.UNATCH) return bun.String.static("EUNATCH").toJS(globalThis); if (err_int == -bun.sys.UV_E.NOEXEC) return bun.String.static("ENOEXEC").toJS(globalThis); - var fmtstring = bun.String.createFormat("Unknown system error {d}", .{err_int}) catch bun.outOfMemory(); + var fmtstring = bun.handleOom(bun.String.createFormat("Unknown system error {d}", .{err_int})); return fmtstring.transferToJS(globalThis); } diff --git a/src/bun.js/node/node_zlib_binding.zig b/src/bun.js/node/node_zlib_binding.zig index 1e7394054a..94af72b6d2 100644 --- a/src/bun.js/node/node_zlib_binding.zig +++ b/src/bun.js/node/node_zlib_binding.zig @@ -257,10 +257,10 @@ pub fn CompressionStream(comptime T: type) type { } pub fn emitError(this: *T, globalThis: *jsc.JSGlobalObject, this_value: jsc.JSValue, err_: Error) !void { - var msg_str = bun.String.createFormat("{s}", .{std.mem.sliceTo(err_.msg, 0) orelse ""}) catch bun.outOfMemory(); + var msg_str = bun.handleOom(bun.String.createFormat("{s}", .{std.mem.sliceTo(err_.msg, 0) orelse ""})); const msg_value = msg_str.transferToJS(globalThis); const err_value: jsc.JSValue = .jsNumber(err_.err); - var code_str = bun.String.createFormat("{s}", .{std.mem.sliceTo(err_.code, 0) orelse ""}) catch bun.outOfMemory(); + var code_str = bun.handleOom(bun.String.createFormat("{s}", .{std.mem.sliceTo(err_.code, 0) orelse ""})); const code_value = code_str.transferToJS(globalThis); const callback: jsc.JSValue = T.js.errorCallbackGetCached(this_value) orelse diff --git a/src/bun.js/node/path.zig b/src/bun.js/node/path.zig index 9155228f72..94a90dcb1e 100644 --- a/src/bun.js/node/path.zig +++ b/src/bun.js/node/path.zig @@ -917,7 +917,7 @@ pub fn formatJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator const bufLen: usize = @max(1 + (if (dirLen > 0) dirLen else pathObject.root.len) + (if (baseLen > 0) baseLen else pathObject.name.len + pathObject.ext.len), PATH_SIZE(T)); - const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf); return if (isWindows) formatWindowsJS_T(T, globalObject, pathObject, buf) else formatPosixJS_T(T, globalObject, pathObject, buf); } @@ -1216,9 +1216,9 @@ pub fn joinJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: var bufLen: usize = if (isWindows) 8 else 0; for (paths) |path| bufLen += if (path.len > 0) path.len + 1 else path.len; bufLen = @max(bufLen, PATH_SIZE(T)); - const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf); - const buf2 = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf2 = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf2); return if (isWindows) joinWindowsJS_T(T, globalObject, paths, buf, buf2) else joinPosixJS_T(T, globalObject, paths, buf, buf2); } @@ -1232,7 +1232,7 @@ pub fn join(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*]jsc var stack_fallback = std.heap.stackFallback(stack_fallback_size_large, arena.allocator()); const allocator = stack_fallback.get(); - var paths = allocator.alloc(string, args_len) catch bun.outOfMemory(); + var paths = bun.handleOom(allocator.alloc(string, args_len)); defer allocator.free(paths); for (0..args_len, args_ptr) |i, path_ptr| { @@ -1625,7 +1625,7 @@ pub fn normalizeWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, pub fn normalizeJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { const bufLen = @max(path.len, PATH_SIZE(T)); - const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf); return if (isWindows) normalizeWindowsJS_T(T, globalObject, path, buf) else normalizePosixJS_T(T, globalObject, path, buf); } @@ -2299,11 +2299,11 @@ pub fn relativeWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, pub fn relativeJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, from: []const T, to: []const T) bun.JSError!jsc.JSValue { const bufLen = @max(from.len + to.len, PATH_SIZE(T)); - const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf); - const buf2 = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf2 = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf2); - const buf3 = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf3 = bun.handleOom(allocator.alloc(T, bufLen)); defer allocator.free(buf3); return if (isWindows) relativeWindowsJS_T(T, globalObject, from, to, buf, buf2, buf3) else relativePosixJS_T(T, globalObject, from, to, buf, buf2, buf3); } @@ -2751,9 +2751,9 @@ pub fn resolveJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocato var bufLen: usize = if (isWindows) 8 else 0; for (paths) |path| bufLen += if (bufLen > 0 and path.len > 0) path.len + 1 else path.len; bufLen = @max(bufLen, PATH_SIZE(T)); - const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf = try allocator.alloc(T, bufLen); defer allocator.free(buf); - const buf2 = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf2 = try allocator.alloc(T, bufLen); defer allocator.free(buf2); return if (isWindows) resolveWindowsJS_T(T, globalObject, paths, buf, buf2) else resolvePosixJS_T(T, globalObject, paths, buf, buf2); } @@ -2767,7 +2767,7 @@ pub fn resolve(globalObject: *jsc.JSGlobalObject, isWindows: bool, args_ptr: [*] var stack_fallback = std.heap.stackFallback(stack_fallback_size_large, arena.allocator()); const allocator = stack_fallback.get(); - var paths = allocator.alloc(string, args_len) catch bun.outOfMemory(); + var paths = try allocator.alloc(string, args_len); defer allocator.free(paths); var path_count: usize = 0; @@ -2885,9 +2885,9 @@ pub fn toNamespacedPathWindowsJS_T(comptime T: type, globalObject: *jsc.JSGlobal pub fn toNamespacedPathJS_T(comptime T: type, globalObject: *jsc.JSGlobalObject, allocator: std.mem.Allocator, isWindows: bool, path: []const T) bun.JSError!jsc.JSValue { if (!isWindows or path.len == 0) return bun.String.createUTF8ForJS(globalObject, path); const bufLen = @max(path.len, PATH_SIZE(T)); - const buf = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf = try allocator.alloc(T, bufLen); defer allocator.free(buf); - const buf2 = allocator.alloc(T, bufLen) catch bun.outOfMemory(); + const buf2 = try allocator.alloc(T, bufLen); defer allocator.free(buf2); return toNamespacedPathWindowsJS_T(T, globalObject, path, buf, buf2); } diff --git a/src/bun.js/node/path_watcher.zig b/src/bun.js/node/path_watcher.zig index 6674d6cd5e..3556185f40 100644 --- a/src/bun.js/node/path_watcher.zig +++ b/src/bun.js/node/path_watcher.zig @@ -72,7 +72,7 @@ pub const PathWatcherManager = struct { .err => |file_err| return .{ .err = file_err.withPath(path) }, .result => |r| r, }; - const cloned_path = bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(); + const cloned_path = bun.handleOom(bun.default_allocator.dupeZ(u8, path)); const result = PathInfo{ .fd = file, .is_file = true, @@ -82,13 +82,13 @@ pub const PathWatcherManager = struct { .hash = Watcher.getHash(cloned_path), .refs = 1, }; - _ = this.file_paths.put(cloned_path, result) catch bun.outOfMemory(); + _ = bun.handleOom(this.file_paths.put(cloned_path, result)); return .{ .result = result }; } return .{ .err = e.withPath(path) }; }, .result => |iterable_dir| { - const cloned_path = bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(); + const cloned_path = bun.handleOom(bun.default_allocator.dupeZ(u8, path)); const result = PathInfo{ .fd = iterable_dir, .is_file = false, @@ -97,7 +97,7 @@ pub const PathWatcherManager = struct { .hash = Watcher.getHash(cloned_path), .refs = 1, }; - _ = this.file_paths.put(cloned_path, result) catch bun.outOfMemory(); + _ = bun.handleOom(this.file_paths.put(cloned_path, result)); return .{ .result = result }; }, } @@ -110,9 +110,9 @@ pub const PathWatcherManager = struct { std.Thread.SpawnError; pub fn init(vm: *jsc.VirtualMachine) PathWatcherManagerError!*PathWatcherManager { - const this = bun.default_allocator.create(PathWatcherManager) catch bun.outOfMemory(); + const this = bun.handleOom(bun.default_allocator.create(PathWatcherManager)); errdefer bun.default_allocator.destroy(this); - var watchers = bun.BabyList(?*PathWatcher).initCapacity(bun.default_allocator, 1) catch bun.outOfMemory(); + var watchers = bun.handleOom(bun.BabyList(?*PathWatcher).initCapacity(bun.default_allocator, 1)); errdefer watchers.deinitWithAllocator(bun.default_allocator); const manager = PathWatcherManager{ diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index f1d13d9ea0..d2162a9372 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -399,7 +399,13 @@ pub const Encoding = enum(u8) { }, .hex => { var buf: [size * 4]u8 = undefined; - const out = std.fmt.bufPrint(&buf, "{}", .{std.fmt.fmtSliceHexLower(input)}) catch bun.outOfMemory(); + const out = std.fmt.bufPrint( + &buf, + "{}", + .{std.fmt.fmtSliceHexLower(input)}, + ) catch |err| switch (err) { + error.NoSpaceLeft => unreachable, + }; const result = jsc.ZigString.init(out).toJS(globalObject); return result; }, @@ -417,6 +423,11 @@ pub const Encoding = enum(u8) { } pub fn encodeWithMaxSize(encoding: Encoding, globalObject: *jsc.JSGlobalObject, comptime max_size: usize, input: []const u8) bun.JSError!jsc.JSValue { + bun.assertf( + input.len <= max_size, + "input length ({}) should not exceed max_size ({})", + .{ input.len, max_size }, + ); switch (encoding) { .base64 => { var base64_buf: [std.base64.standard.Encoder.calcSize(max_size * 4)]u8 = undefined; @@ -433,7 +444,13 @@ pub const Encoding = enum(u8) { }, .hex => { var buf: [max_size * 4]u8 = undefined; - const out = std.fmt.bufPrint(&buf, "{}", .{std.fmt.fmtSliceHexLower(input)}) catch bun.outOfMemory(); + const out = std.fmt.bufPrint( + &buf, + "{}", + .{std.fmt.fmtSliceHexLower(input)}, + ) catch |err| switch (err) { + error.NoSpaceLeft => unreachable, + }; const result = jsc.ZigString.init(out).toJS(globalObject); return result; }, @@ -785,7 +802,7 @@ pub const VectorArrayBuffer = struct { var bufferlist = std.ArrayList(bun.PlatformIOVec).init(allocator); var i: usize = 0; const len = try val.getLength(globalObject); - bufferlist.ensureTotalCapacityPrecise(len) catch bun.outOfMemory(); + bun.handleOom(bufferlist.ensureTotalCapacityPrecise(len)); while (i < len) { const element = try val.getIndex(globalObject, @as(u32, @truncate(i))); @@ -799,7 +816,7 @@ pub const VectorArrayBuffer = struct { }; const buf = array_buffer.byteSlice(); - bufferlist.append(bun.platformIOVecCreate(buf)) catch bun.outOfMemory(); + bun.handleOom(bufferlist.append(bun.platformIOVecCreate(buf))); i += 1; } diff --git a/src/bun.js/node/win_watcher.zig b/src/bun.js/node/win_watcher.zig index b67171cd3e..016fa08e36 100644 --- a/src/bun.js/node/win_watcher.zig +++ b/src/bun.js/node/win_watcher.zig @@ -140,7 +140,7 @@ pub const PathWatcher = struct { const ctx: *FSWatcher = @alignCast(@ptrCast(this.handlers.keys()[i])); onPathUpdateFn(ctx, event_type.toEvent(switch (ctx.encoding) { .utf8 => .{ .string = bun.String.cloneUTF8(path) }, - else => .{ .bytes_to_free = bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory() }, + else => .{ .bytes_to_free = bun.handleOom(bun.default_allocator.dupeZ(u8, path)) }, }), is_file); if (comptime bun.Environment.isDebug) debug_count += 1; @@ -176,7 +176,7 @@ pub const PathWatcher = struct { .result => |event_path| event_path, }; - const watchers_entry = manager.watchers.getOrPut(bun.default_allocator, @as([]const u8, event_path)) catch bun.outOfMemory(); + const watchers_entry = bun.handleOom(manager.watchers.getOrPut(bun.default_allocator, @as([]const u8, event_path))); if (watchers_entry.found_existing) { return .{ .result = watchers_entry.value_ptr.* }; } @@ -210,7 +210,7 @@ pub const PathWatcher = struct { uv.uv_unref(@ptrCast(&this.handle)); watchers_entry.value_ptr.* = this; - watchers_entry.key_ptr.* = bun.default_allocator.dupeZ(u8, event_path) catch bun.outOfMemory(); + watchers_entry.key_ptr.* = bun.handleOom(bun.default_allocator.dupeZ(u8, event_path)); return .{ .result = this }; } @@ -285,7 +285,7 @@ pub fn watch( .err => |err| return .{ .err = err }, .result => |watcher| watcher, }; - watcher.handlers.put(bun.default_allocator, ctx, .{}) catch bun.outOfMemory(); + bun.handleOom(watcher.handlers.put(bun.default_allocator, ctx, .{})); return .{ .result = watcher }; } diff --git a/src/bun.js/rare_data.zig b/src/bun.js/rare_data.zig index 261c77e7d2..8f53659842 100644 --- a/src/bun.js/rare_data.zig +++ b/src/bun.js/rare_data.zig @@ -80,7 +80,7 @@ pub const AWSSignatureCache = struct { this.clean(); } this.date = numeric_day; - this.cache.put(bun.default_allocator.dupe(u8, key) catch bun.outOfMemory(), value) catch bun.outOfMemory(); + bun.handleOom(this.cache.put(bun.handleOom(bun.default_allocator.dupe(u8, key)), value)); } pub fn deinit(this: *@This()) void { this.date = 0; @@ -95,7 +95,7 @@ pub fn awsCache(this: *RareData) *AWSSignatureCache { pub fn pipeReadBuffer(this: *RareData) *PipeReadBuffer { return this.temp_pipe_read_buffer orelse { - this.temp_pipe_read_buffer = default_allocator.create(PipeReadBuffer) catch bun.outOfMemory(); + this.temp_pipe_read_buffer = bun.handleOom(default_allocator.create(PipeReadBuffer)); return this.temp_pipe_read_buffer.?; }; } @@ -137,7 +137,7 @@ pub fn mimeTypeFromString(this: *RareData, allocator: std.mem.Allocator, str: [] if (this.mime_types == null) { this.mime_types = bun.http.MimeType.createHashTable( allocator, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (this.mime_types.?.get(str)) |entry| { @@ -183,12 +183,12 @@ pub const HotMap = struct { } pub fn insert(this: *HotMap, key: []const u8, ptr: anytype) void { - const entry = this._map.getOrPut(key) catch bun.outOfMemory(); + const entry = bun.handleOom(this._map.getOrPut(key)); if (entry.found_existing) { @panic("HotMap already contains key"); } - entry.key_ptr.* = this._map.allocator.dupe(u8, key) catch bun.outOfMemory(); + entry.key_ptr.* = bun.handleOom(this._map.allocator.dupe(u8, key)); entry.value_ptr.* = Entry.init(ptr); } @@ -302,7 +302,7 @@ pub fn pushCleanupHook( ctx: ?*anyopaque, func: CleanupHook.Function, ) void { - this.cleanup_hooks.append(bun.default_allocator, CleanupHook.init(globalThis, ctx, func)) catch bun.outOfMemory(); + bun.handleOom(this.cleanup_hooks.append(bun.default_allocator, CleanupHook.init(globalThis, ctx, func))); } pub fn boringEngine(rare: *RareData) *BoringSSL.ENGINE { @@ -479,7 +479,20 @@ pub fn nodeFSStatWatcherScheduler(rare: *RareData, vm: *jsc.VirtualMachine) bun. pub fn s3DefaultClient(rare: *RareData, globalThis: *jsc.JSGlobalObject) jsc.JSValue { return rare.s3_default_client.get() orelse { const vm = globalThis.bunVM(); - var aws_options = bun.S3.S3Credentials.getCredentialsWithOptions(vm.transpiler.env.getS3Credentials(), .{}, null, null, null, globalThis) catch bun.outOfMemory(); + var aws_options = bun.S3.S3Credentials.getCredentialsWithOptions( + vm.transpiler.env.getS3Credentials(), + .{}, + null, + null, + null, + globalThis, + ) catch |err| switch (err) { + error.OutOfMemory => bun.outOfMemory(), + error.JSError => { + globalThis.reportActiveExceptionAsUnhandled(err); + return .js_undefined; + }, + }; defer aws_options.deinit(); const client = jsc.WebCore.S3Client.new(.{ .credentials = aws_options.credentials.dupe(), @@ -502,12 +515,12 @@ pub fn setTLSDefaultCiphers(this: *RareData, ciphers: []const u8) void { if (this.tls_default_ciphers) |old_ciphers| { bun.default_allocator.free(old_ciphers); } - this.tls_default_ciphers = bun.default_allocator.dupeZ(u8, ciphers) catch bun.outOfMemory(); + this.tls_default_ciphers = bun.handleOom(bun.default_allocator.dupeZ(u8, ciphers)); } pub fn defaultCSRFSecret(this: *RareData) []const u8 { if (this.default_csrf_secret.len == 0) { - const secret = bun.default_allocator.alloc(u8, 16) catch bun.outOfMemory(); + const secret = bun.handleOom(bun.default_allocator.alloc(u8, 16)); bun.csprng(secret); this.default_csrf_secret = secret; } diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig index db8383a32b..73ade47ead 100644 --- a/src/bun.js/test/jest.zig +++ b/src/bun.js/test/jest.zig @@ -22,8 +22,8 @@ const CurrentFile = struct { pub fn set(this: *CurrentFile, title: string, prefix: string, repeat_count: u32, repeat_index: u32) void { if (Output.isAIAgent()) { this.freeAndClear(); - this.title = bun.default_allocator.dupe(u8, title) catch bun.outOfMemory(); - this.prefix = bun.default_allocator.dupe(u8, prefix) catch bun.outOfMemory(); + this.title = bun.handleOom(bun.default_allocator.dupe(u8, title)); + this.prefix = bun.handleOom(bun.default_allocator.dupe(u8, prefix)); this.repeat_info.count = repeat_count; this.repeat_info.index = repeat_index; this.has_printed_filename = false; @@ -1527,7 +1527,7 @@ pub const TestRunnerTask = struct { if (this.needs_before_each) { this.needs_before_each = false; - const label = bun.default_allocator.dupe(u8, test_.label) catch bun.outOfMemory(); + const label = bun.handleOom(bun.default_allocator.dupe(u8, test_.label)); defer bun.default_allocator.free(label); if (this.describe.runCallback(globalThis, .beforeEach)) |err| { @@ -2122,9 +2122,9 @@ fn consumeArg( if (should_write) { const owned_slice = try arg.toSliceOrNull(globalThis); defer owned_slice.deinit(); - array_list.appendSlice(allocator, owned_slice.slice()) catch bun.outOfMemory(); + bun.handleOom(array_list.appendSlice(allocator, owned_slice.slice())); } else { - array_list.appendSlice(allocator, fallback) catch bun.outOfMemory(); + bun.handleOom(array_list.appendSlice(allocator, fallback)); } str_idx.* += 1; args_idx.* += 1; @@ -2135,7 +2135,7 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa const allocator = bun.default_allocator; var idx: usize = 0; var args_idx: usize = 0; - var list = std.ArrayListUnmanaged(u8).initCapacity(allocator, label.len) catch bun.outOfMemory(); + var list = bun.handleOom(std.ArrayListUnmanaged(u8).initCapacity(allocator, label.len)); while (idx < label.len) { const char = label[idx]; @@ -2167,9 +2167,9 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa if (!value.isEmptyOrUndefinedOrNull()) { var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); - const value_str = std.fmt.allocPrint(allocator, "{}", .{value.toFmt(&formatter)}) catch bun.outOfMemory(); + const value_str = bun.handleOom(std.fmt.allocPrint(allocator, "{}", .{value.toFmt(&formatter)})); defer allocator.free(value_str); - list.appendSlice(allocator, value_str) catch bun.outOfMemory(); + bun.handleOom(list.appendSlice(allocator, value_str)); idx = var_end; continue; } @@ -2179,8 +2179,8 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa } } - list.append(allocator, '$') catch bun.outOfMemory(); - list.appendSlice(allocator, label[var_start..var_end]) catch bun.outOfMemory(); + bun.handleOom(list.append(allocator, '$')); + bun.handleOom(list.appendSlice(allocator, label[var_start..var_end])); idx = var_end; } else if (char == '%' and (idx + 1 < label.len) and !(args_idx >= function_args.len)) { const current_arg = function_args[args_idx]; @@ -2202,9 +2202,9 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa var str = bun.String.empty; defer str.deref(); try current_arg.jsonStringify(globalThis, 0, &str); - const owned_slice = str.toOwnedSlice(allocator) catch bun.outOfMemory(); + const owned_slice = bun.handleOom(str.toOwnedSlice(allocator)); defer allocator.free(owned_slice); - list.appendSlice(allocator, owned_slice) catch bun.outOfMemory(); + bun.handleOom(list.appendSlice(allocator, owned_slice)); idx += 1; args_idx += 1; }, @@ -2212,27 +2212,27 @@ fn formatLabel(globalThis: *JSGlobalObject, label: string, function_args: []JSVa var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; defer formatter.deinit(); const value_fmt = current_arg.toFmt(&formatter); - const test_index_str = std.fmt.allocPrint(allocator, "{}", .{value_fmt}) catch bun.outOfMemory(); + const test_index_str = bun.handleOom(std.fmt.allocPrint(allocator, "{}", .{value_fmt})); defer allocator.free(test_index_str); - list.appendSlice(allocator, test_index_str) catch bun.outOfMemory(); + bun.handleOom(list.appendSlice(allocator, test_index_str)); idx += 1; args_idx += 1; }, '#' => { - const test_index_str = std.fmt.allocPrint(allocator, "{d}", .{test_idx}) catch bun.outOfMemory(); + const test_index_str = bun.handleOom(std.fmt.allocPrint(allocator, "{d}", .{test_idx})); defer allocator.free(test_index_str); - list.appendSlice(allocator, test_index_str) catch bun.outOfMemory(); + bun.handleOom(list.appendSlice(allocator, test_index_str)); idx += 1; }, '%' => { - list.append(allocator, '%') catch bun.outOfMemory(); + bun.handleOom(list.append(allocator, '%')); idx += 1; }, else => { // ignore unrecognized fmt }, } - } else list.append(allocator, char) catch bun.outOfMemory(); + } else bun.handleOom(list.append(allocator, char)); idx += 1; } diff --git a/src/bun.js/virtual_machine_exports.zig b/src/bun.js/virtual_machine_exports.zig index f3f638a38f..4ae59d4bfc 100644 --- a/src/bun.js/virtual_machine_exports.zig +++ b/src/bun.js/virtual_machine_exports.zig @@ -125,7 +125,7 @@ pub export fn Bun__handleHandledPromise(global: *JSGlobalObject, promise: *jsc.J jsc.markBinding(@src()); const promise_js = promise.toJS(); promise_js.protect(); - const context = bun.default_allocator.create(Context) catch bun.outOfMemory(); + const context = bun.handleOom(bun.default_allocator.create(Context)); context.* = .{ .globalThis = global, .promise = promise_js }; global.bunVM().eventLoop().enqueueTask(jsc.ManagedTask.New(Context, Context.callback).init(context)); } diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index b3b80b8aae..30f5651660 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -156,9 +156,19 @@ fn resolveEntryPointSpecifier( } var resolved_entry_point: bun.resolver.Result = parent.transpiler.resolveEntryPoint(str) catch { - const out = (logger.toJS(parent.global, bun.default_allocator, "Error resolving Worker entry point") catch bun.outOfMemory()).toBunString(parent.global) catch { - error_message.* = bun.String.static("unexpected exception"); - return null; + const out = blk: { + const out = logger.toJS( + parent.global, + bun.default_allocator, + "Error resolving Worker entry point", + ) catch |err| break :blk err; + break :blk out.toBunString(parent.global); + } catch |err| switch (err) { + error.OutOfMemory => bun.outOfMemory(), + error.JSError => { + error_message.* = bun.String.static("unexpected exception"); + return null; + }, }; error_message.* = out; return null; @@ -202,12 +212,12 @@ pub fn create( const preload_modules = if (preload_modules_ptr) |ptr| ptr[0..preload_modules_len] else &.{}; - var preloads = std.ArrayList([]const u8).initCapacity(bun.default_allocator, preload_modules_len) catch bun.outOfMemory(); + var preloads = bun.handleOom(std.ArrayList([]const u8).initCapacity(bun.default_allocator, preload_modules_len)); for (preload_modules) |module| { const utf8_slice = module.toUTF8(bun.default_allocator); defer utf8_slice.deinit(); if (resolveEntryPointSpecifier(parent, utf8_slice.slice(), error_message, &temp_log)) |preload| { - preloads.append(bun.default_allocator.dupe(u8, preload) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(preloads.append(bun.handleOom(bun.default_allocator.dupe(u8, preload)))); } if (!error_message.isEmpty()) { @@ -219,7 +229,7 @@ pub fn create( } } - var worker = bun.default_allocator.create(WebWorker) catch bun.outOfMemory(); + var worker = bun.handleOom(bun.default_allocator.create(WebWorker)); worker.* = WebWorker{ .cpp_worker = cpp_worker, .parent = parent, @@ -227,11 +237,11 @@ pub fn create( .execution_context_id = this_context_id, .mini = mini, .eval_mode = eval_mode, - .unresolved_specifier = (spec_slice.toOwned(bun.default_allocator) catch bun.outOfMemory()).slice(), + .unresolved_specifier = bun.handleOom(spec_slice.toOwned(bun.default_allocator)).slice(), .store_fd = parent.transpiler.resolver.store_fd, .name = brk: { if (!name_str.isEmpty()) { - break :brk std.fmt.allocPrintZ(bun.default_allocator, "{}", .{name_str}) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrintZ(bun.default_allocator, "{}", .{name_str})); } break :brk ""; }, @@ -366,8 +376,15 @@ fn flushLogs(this: *WebWorker) void { jsc.markBinding(@src()); var vm = this.vm orelse return; if (vm.log.msgs.items.len == 0) return; - const err = vm.log.toJS(vm.global, bun.default_allocator, "Error in worker") catch bun.outOfMemory(); - const str = err.toBunString(vm.global) catch @panic("unexpected exception"); + const err, const str = blk: { + const err = vm.log.toJS(vm.global, bun.default_allocator, "Error in worker") catch |e| + break :blk e; + const str = err.toBunString(vm.global) catch |e| break :blk e; + break :blk .{ err, str }; + } catch |err| switch (err) { + error.JSError => @panic("unhandled exception"), + error.OutOfMemory => bun.outOfMemory(), + }; defer str.deref(); bun.jsc.fromJSHostCallGeneric(vm.global, @src(), WebWorker__dispatchError, .{ vm.global, this.cpp_worker, str, err }) catch |e| { _ = vm.global.reportUncaughtException(vm.global.takeException(e).asException(vm.global.vm()).?); @@ -445,7 +462,7 @@ fn spin(this: *WebWorker) void { if (vm.log.errors == 0 and !resolve_error.isEmpty()) { const err = resolve_error.toUTF8(bun.default_allocator); defer err.deinit(); - vm.log.addError(null, .Empty, err.slice()) catch bun.outOfMemory(); + bun.handleOom(vm.log.addError(null, .Empty, err.slice())); } this.flushLogs(); this.exitAndDeinit(); diff --git a/src/bun.js/webcore/ArrayBufferSink.zig b/src/bun.js/webcore/ArrayBufferSink.zig index d5c0521a41..d6ba0bd7c1 100644 --- a/src/bun.js/webcore/ArrayBufferSink.zig +++ b/src/bun.js/webcore/ArrayBufferSink.zig @@ -156,7 +156,7 @@ pub fn endFromJS(this: *ArrayBufferSink, _: *JSGlobalObject) bun.sys.Maybe(Array this.done = true; this.signal.close(null); return .{ .result = ArrayBuffer.fromBytes( - list.toOwnedSlice() catch bun.outOfMemory(), + bun.handleOom(list.toOwnedSlice()), if (this.as_uint8array) .Uint8Array else diff --git a/src/bun.js/webcore/Blob.zig b/src/bun.js/webcore/Blob.zig index 16d0d1ae7a..cb457856b5 100644 --- a/src/bun.js/webcore/Blob.zig +++ b/src/bun.js/webcore/Blob.zig @@ -71,7 +71,7 @@ pub fn getFormDataEncoding(this: *Blob) ?*bun.FormData.AsyncFormData { var content_type_slice: ZigString.Slice = this.getContentType() orelse return null; defer content_type_slice.deinit(); const encoding = bun.FormData.Encoding.get(content_type_slice.slice()) orelse return null; - return bun.FormData.AsyncFormData.init(this.allocator orelse bun.default_allocator, encoding) catch bun.outOfMemory(); + return bun.handleOom(bun.FormData.AsyncFormData.init(this.allocator orelse bun.default_allocator, encoding)); } pub fn hasContentTypeFromUser(this: *const Blob) bool { @@ -141,8 +141,8 @@ pub fn doReadFile(this: *Blob, comptime Function: anytype, global: *JSGlobalObje *Handler, handler, Handler.run, - ) catch bun.outOfMemory(); - var read_file_task = read_file.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); + var read_file_task = bun.handleOom(read_file.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read)); // Create the Promise only after the store has been ref()'d. // The garbage collector runs on memory allocations @@ -179,8 +179,8 @@ pub fn doReadFileInternal(this: *Blob, comptime Handler: type, ctx: Handler, com NewInternalReadFileHandler(Handler, Function).run, this.offset, this.size, - ) catch bun.outOfMemory(); - var read_file_task = read_file.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); + var read_file_task = bun.handleOom(read_file.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read)); read_file_task.schedule(); } @@ -504,7 +504,7 @@ const URLSearchParamsConverter = struct { buf: []u8 = "", globalThis: *jsc.JSGlobalObject, pub fn convert(this: *URLSearchParamsConverter, str: ZigString) void { - var out = str.toSlice(this.allocator).cloneIfNeeded(this.allocator) catch bun.outOfMemory(); + var out = bun.handleOom(str.toSlice(this.allocator).cloneIfNeeded(this.allocator)); this.buf = @constCast(out.slice()); } }; @@ -561,9 +561,9 @@ pub fn fromDOMFormData( context.joiner.pushStatic(boundary); context.joiner.pushStatic("--\r\n"); - const store = Blob.Store.init(context.joiner.done(allocator) catch bun.outOfMemory(), allocator); + const store = Blob.Store.init(bun.handleOom(context.joiner.done(allocator)), allocator); var blob = Blob.initWithStore(store, globalThis); - blob.content_type = std.fmt.allocPrint(allocator, "multipart/form-data; boundary={s}", .{boundary}) catch bun.outOfMemory(); + blob.content_type = std.fmt.allocPrint(allocator, "multipart/form-data; boundary={s}", .{boundary}) catch |err| bun.handleOom(err); blob.content_type_allocated = true; blob.content_type_was_set = true; @@ -1000,7 +1000,7 @@ pub fn writeFileWithSourceDestination(ctx: *jsc.JSGlobalObject, source_blob: *Bl WriteFilePromise.run, options.mkdirp_if_not_exists orelse true, ) catch unreachable; - var task = write_file.WriteFileTask.createOnJSThread(bun.default_allocator, ctx, file_copier) catch bun.outOfMemory(); + var task = bun.handleOom(write_file.WriteFileTask.createOnJSThread(bun.default_allocator, ctx, file_copier)); // Defer promise creation until we're just about to schedule the task var promise = jsc.JSPromise.create(ctx); const promise_value = promise.asValue(ctx); @@ -1717,7 +1717,7 @@ pub fn JSDOMFile__construct_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.Ca switch (store_.data) { .bytes => |*bytes| { bytes.stored_name = bun.PathString.init( - (name_value_str.toUTF8WithoutRef(bun.default_allocator).cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice(), + bun.handleOom(name_value_str.toUTF8WithoutRef(bun.default_allocator).cloneIfNeeded(bun.default_allocator)).slice(), ); }, .s3, .file => { @@ -1730,7 +1730,7 @@ pub fn JSDOMFile__construct_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.Ca .data = .{ .bytes = Blob.Store.Bytes.initEmptyWithName( bun.PathString.init( - (name_value_str.toUTF8WithoutRef(bun.default_allocator).cloneIfNeeded(bun.default_allocator) catch bun.outOfMemory()).slice(), + bun.handleOom(name_value_str.toUTF8WithoutRef(bun.default_allocator).cloneIfNeeded(bun.default_allocator)).slice(), ), allocator, ), @@ -1765,7 +1765,7 @@ pub fn JSDOMFile__construct_(globalThis: *jsc.JSGlobalObject, callframe: *jsc.Ca blob.content_type = mime.value; break :inner; } - const content_type_buf = allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(allocator.alloc(u8, slice.len)); blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } @@ -1866,7 +1866,7 @@ pub fn constructBunFile( blob.content_type = entry.value; break :inner; } - const content_type_buf = allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(allocator.alloc(u8, slice.len)); blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } @@ -1892,7 +1892,7 @@ pub fn findOrCreateFileFromPath(path_or_fd: *jsc.Node.PathOrFileDescriptor, glob const credentials = globalThis.bunVM().transpiler.env.getS3Credentials(); const copy = path_or_fd.*; path_or_fd.* = .{ .path = .{ .string = bun.PathString.empty } }; - return Blob.initWithStore(Blob.Store.initS3(copy.path, null, credentials, allocator) catch bun.outOfMemory(), globalThis); + return Blob.initWithStore(bun.handleOom(Blob.Store.initS3(copy.path, null, credentials, allocator)), globalThis); } } } @@ -1907,7 +1907,7 @@ pub fn findOrCreateFileFromPath(path_or_fd: *jsc.Node.PathOrFileDescriptor, glob path_or_fd.* = .{ .path = .{ // this memory is freed with this allocator in `Blob.Store.deinit` - .string = bun.PathString.init(allocator.dupe(u8, "\\\\.\\NUL") catch bun.outOfMemory()), + .string = bun.PathString.init(bun.handleOom(allocator.dupe(u8, "\\\\.\\NUL"))), }, }; slice = path_or_fd.path.slice(); @@ -1946,7 +1946,7 @@ pub fn findOrCreateFileFromPath(path_or_fd: *jsc.Node.PathOrFileDescriptor, glob } }; - return Blob.initWithStore(Blob.Store.initFile(path, null, allocator) catch bun.outOfMemory(), globalThis); + return Blob.initWithStore(bun.handleOom(Blob.Store.initFile(path, null, allocator)), globalThis); } pub fn getStream( @@ -2263,7 +2263,7 @@ pub fn doWrite(this: *Blob, globalThis: *jsc.JSGlobalObject, callframe: *jsc.Cal if (globalThis.bunVM().mimeType(slice)) |mime| { this.content_type = mime.value; } else { - const content_type_buf = bun.default_allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(bun.default_allocator.alloc(u8, slice.len)); this.content_type = strings.copyLowercase(slice, content_type_buf); this.content_type_allocated = true; } @@ -2468,7 +2468,7 @@ pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *jsc.JSGlobalObject, re store.data.file.pathlike.path.slice(), ).cloneIfNeeded( bun.default_allocator, - ) catch bun.outOfMemory(), + ) catch |err| bun.handleOom(err), }; } }; @@ -2604,7 +2604,7 @@ pub fn getWriter( if (globalThis.bunVM().mimeType(slice)) |mime| { this.content_type = mime.value; } else { - const content_type_buf = bun.default_allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(bun.default_allocator.alloc(u8, slice.len)); this.content_type = strings.copyLowercase(slice, content_type_buf); this.content_type_allocated = true; } @@ -2708,7 +2708,7 @@ pub fn getWriter( store.data.file.pathlike.path.slice(), ).cloneIfNeeded( bun.default_allocator, - ) catch bun.outOfMemory(), + ) catch |err| bun.handleOom(err), }; } }; @@ -2845,7 +2845,7 @@ pub fn getSlice( } content_type_was_allocated = slice.len > 0; - const content_type_buf = allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(allocator.alloc(u8, slice.len)); content_type = strings.copyLowercase(slice, content_type_buf); } } @@ -3034,7 +3034,7 @@ export fn Blob__fromBytes(globalThis: *jsc.JSGlobalObject, ptr: ?[*]const u8, le return blob; } - const bytes = bun.default_allocator.dupe(u8, ptr.?[0..len]) catch bun.outOfMemory(); + const bytes = bun.handleOom(bun.default_allocator.dupe(u8, ptr.?[0..len])); const store = Store.init(bytes, bun.default_allocator); var blob = initWithStore(store, globalThis); blob.allocator = bun.default_allocator; @@ -3191,7 +3191,7 @@ pub fn constructor(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) b blob.content_type = mime.value; break :inner; } - const content_type_buf = allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(allocator.alloc(u8, slice.len)); blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } @@ -3307,7 +3307,7 @@ pub fn create( globalThis: *JSGlobalObject, was_string: bool, ) Blob { - return tryCreate(bytes_, allocator_, globalThis, was_string) catch bun.outOfMemory(); + return bun.handleOom(tryCreate(bytes_, allocator_, globalThis, was_string)); } pub fn initWithStore(store: *Blob.Store, globalThis: *JSGlobalObject) Blob { @@ -3372,7 +3372,7 @@ pub fn dupeWithContentType(this: *const Blob, include_content_type: bool) Blob { duped.content_type_was_set = duped.content_type.len > 0; } } else if (duped.content_type_allocated and duped.allocator != null and include_content_type) { - duped.content_type = bun.default_allocator.dupe(u8, this.content_type) catch bun.outOfMemory(); + duped.content_type = bun.handleOom(bun.default_allocator.dupe(u8, this.content_type)); } duped.name = duped.name.dupeRef(); diff --git a/src/bun.js/webcore/Body.zig b/src/bun.js/webcore/Body.zig index e221843314..9dc2de6f1f 100644 --- a/src/bun.js/webcore/Body.zig +++ b/src/bun.js/webcore/Body.zig @@ -790,7 +790,7 @@ pub const Value = union(Tag) { ); } else { new_blob = Blob.init( - bun.default_allocator.dupe(u8, wtf.latin1Slice()) catch bun.outOfMemory(), + bun.handleOom(bun.default_allocator.dupe(u8, wtf.latin1Slice())), bun.default_allocator, jsc.VirtualMachine.get().global, ); @@ -930,7 +930,7 @@ pub const Value = union(Tag) { return this.toErrorInstance(.{ .Message = bun.String.createFormat( "Error reading file {s}", .{@errorName(err)}, - ) catch bun.outOfMemory() }, global); + ) catch |e| bun.handleOom(e) }, global); } pub fn deinit(this: *Value) void { @@ -1450,7 +1450,7 @@ pub const ValueBufferer = struct { const chunk = stream.slice(); log("onStreamPipe chunk {}", .{chunk.len}); - _ = sink.stream_buffer.write(chunk) catch bun.outOfMemory(); + _ = bun.handleOom(sink.stream_buffer.write(chunk)); if (stream.isDone()) { const bytes = sink.stream_buffer.list.items; log("onStreamPipe done {}", .{bytes.len}); @@ -1607,7 +1607,7 @@ pub const ValueBufferer = struct { sink.byte_stream = byte_stream; log("byte stream pre-buffered {}", .{bytes.len}); - _ = sink.stream_buffer.write(bytes) catch bun.outOfMemory(); + _ = bun.handleOom(sink.stream_buffer.write(bytes)); return; }, } diff --git a/src/bun.js/webcore/ByteBlobLoader.zig b/src/bun.js/webcore/ByteBlobLoader.zig index f109051b2c..350cab17f0 100644 --- a/src/bun.js/webcore/ByteBlobLoader.zig +++ b/src/bun.js/webcore/ByteBlobLoader.zig @@ -42,7 +42,7 @@ pub fn setup( const content_type, const content_type_allocated = brk: { if (blob.content_type_was_set) { if (blob.content_type_allocated) { - break :brk .{ bun.default_allocator.dupe(u8, blob.content_type) catch bun.outOfMemory(), true }; + break :brk .{ bun.handleOom(bun.default_allocator.dupe(u8, blob.content_type)), true }; } break :brk .{ blob.content_type, false }; @@ -167,7 +167,7 @@ pub fn drain(this: *ByteBlobLoader) bun.ByteList { temporary = temporary[0..@min(16384, @min(temporary.len, this.remain))]; var byte_list = bun.ByteList.init(temporary); - const cloned = byte_list.listManaged(bun.default_allocator).clone() catch bun.outOfMemory(); + const cloned = bun.handleOom(byte_list.listManaged(bun.default_allocator).clone()); this.offset +|= @as(Blob.SizeType, @truncate(cloned.items.len)); this.remain -|= @as(Blob.SizeType, @truncate(cloned.items.len)); diff --git a/src/bun.js/webcore/ByteStream.zig b/src/bun.js/webcore/ByteStream.zig index 91cdf6e395..25d4d3036a 100644 --- a/src/bun.js/webcore/ByteStream.zig +++ b/src/bun.js/webcore/ByteStream.zig @@ -145,13 +145,13 @@ pub fn onData( } log("ByteStream.onData appendSlice and action.fulfill()", .{}); - this.buffer.appendSlice(chunk) catch bun.outOfMemory(); + bun.handleOom(this.buffer.appendSlice(chunk)); var blob = this.toAnyBlob().?; action.fulfill(this.parent().globalThis, &blob); return; } else { - this.buffer.appendSlice(chunk) catch bun.outOfMemory(); + bun.handleOom(this.buffer.appendSlice(chunk)); if (stream == .owned_and_done or stream == .owned) { allocator.free(stream.slice()); diff --git a/src/bun.js/webcore/FileReader.zig b/src/bun.js/webcore/FileReader.zig index 3d700aef92..0807d0bf54 100644 --- a/src/bun.js/webcore/FileReader.zig +++ b/src/bun.js/webcore/FileReader.zig @@ -340,12 +340,12 @@ pub fn onReadChunk(this: *@This(), init_buf: []const u8, state: bun.io.ReadState } else if (in_progress.len > 0 and !hasMore) { this.read_inside_on_pull = .{ .temporary = buf }; } else if (hasMore and !bun.isSliceInBuffer(buf, this.buffered.allocatedSlice())) { - this.buffered.appendSlice(bun.default_allocator, buf) catch bun.outOfMemory(); + bun.handleOom(this.buffered.appendSlice(bun.default_allocator, buf)); this.read_inside_on_pull = .{ .use_buffered = buf.len }; } }, .use_buffered => |original| { - this.buffered.appendSlice(bun.default_allocator, buf) catch bun.outOfMemory(); + bun.handleOom(this.buffered.appendSlice(bun.default_allocator, buf)); this.read_inside_on_pull = .{ .use_buffered = buf.len + original }; }, .none => unreachable, @@ -452,7 +452,7 @@ pub fn onReadChunk(this: *@This(), init_buf: []const u8, state: bun.io.ReadState this.pending.run(); return !was_done; } else if (!bun.isSliceInBuffer(buf, this.buffered.allocatedSlice())) { - this.buffered.appendSlice(bun.default_allocator, buf) catch bun.outOfMemory(); + bun.handleOom(this.buffered.appendSlice(bun.default_allocator, buf)); if (bun.isSliceInBuffer(buf, this.reader.buffer().allocatedSlice())) { this.reader.buffer().clearRetainingCapacity(); } diff --git a/src/bun.js/webcore/ObjectURLRegistry.zig b/src/bun.js/webcore/ObjectURLRegistry.zig index 314ce7a5f3..82f1dbba5d 100644 --- a/src/bun.js/webcore/ObjectURLRegistry.zig +++ b/src/bun.js/webcore/ObjectURLRegistry.zig @@ -25,7 +25,7 @@ pub fn register(this: *ObjectURLRegistry, vm: *jsc.VirtualMachine, blob: *const this.lock.lock(); defer this.lock.unlock(); - this.map.put(uuid, entry) catch bun.outOfMemory(); + bun.handleOom(this.map.put(uuid, entry)); return uuid; } @@ -98,7 +98,7 @@ fn Bun__createObjectURL_(globalObject: *jsc.JSGlobalObject, callframe: *jsc.Call }; const registry = ObjectURLRegistry.singleton(); const uuid = registry.register(globalObject.bunVM(), blob); - var str = bun.String.createFormat("blob:{}", .{uuid}) catch bun.outOfMemory(); + var str = bun.handleOom(bun.String.createFormat("blob:{}", .{uuid})); return str.transferToJS(globalObject); } diff --git a/src/bun.js/webcore/Response.zig b/src/bun.js/webcore/Response.zig index 2453ca8825..0913ce7339 100644 --- a/src/bun.js/webcore/Response.zig +++ b/src/bun.js/webcore/Response.zig @@ -31,7 +31,7 @@ pub fn getFormDataEncoding(this: *Response) bun.JSError!?*bun.FormData.AsyncForm var content_type_slice: ZigString.Slice = (try this.getContentType()) orelse return null; defer content_type_slice.deinit(); const encoding = bun.FormData.Encoding.get(content_type_slice.slice()) orelse return null; - return bun.FormData.AsyncFormData.init(bun.default_allocator, encoding) catch bun.outOfMemory(); + return bun.handleOom(bun.FormData.AsyncFormData.init(bun.default_allocator, encoding)); } pub fn estimatedSize(this: *Response) callconv(.C) usize { @@ -142,38 +142,38 @@ pub fn writeFormat(this: *Response, comptime Formatter: type, formatter: *Format try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("ok: ", enable_ansi_colors)); try formatter.printAs(.Boolean, Writer, writer, jsc.JSValue.jsBoolean(this.isOK()), .BooleanObject, enable_ansi_colors); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("url: \"", enable_ansi_colors)); try writer.print(comptime Output.prettyFmt("{}", enable_ansi_colors), .{this.url}); try writer.writeAll("\""); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("status: ", enable_ansi_colors)); try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(this.init.status_code), .NumberObject, enable_ansi_colors); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("statusText: ", enable_ansi_colors)); try writer.print(comptime Output.prettyFmt("\"{}\"", enable_ansi_colors), .{this.init.status_text}); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("headers: ", enable_ansi_colors)); try formatter.printAs(.Private, Writer, writer, try this.getHeaders(formatter.globalThis), .DOMWrapper, enable_ansi_colors); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("redirected: ", enable_ansi_colors)); try formatter.printAs(.Boolean, Writer, writer, jsc.JSValue.jsBoolean(this.redirected), .BooleanObject, enable_ansi_colors); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); formatter.resetLine(); diff --git a/src/bun.js/webcore/S3Client.zig b/src/bun.js/webcore/S3Client.zig index efd1f30fbe..5a6a239f5b 100644 --- a/src/bun.js/webcore/S3Client.zig +++ b/src/bun.js/webcore/S3Client.zig @@ -12,21 +12,21 @@ pub fn writeFormatCredentials(credentials: *S3Credentials, options: bun.S3.Multi try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("endpoint: \"", enable_ansi_colors)); try writer.print(comptime bun.Output.prettyFmt("{s}\"", enable_ansi_colors), .{endpoint}); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); const region = if (credentials.region.len > 0) credentials.region else S3Credentials.guessRegion(credentials.endpoint); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("region: \"", enable_ansi_colors)); try writer.print(comptime bun.Output.prettyFmt("{s}\"", enable_ansi_colors), .{region}); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); // PS: We don't want to print the credentials if they are empty just signal that they are there without revealing them if (credentials.accessKeyId.len > 0) { try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("accessKeyId: \"[REDACTED]\"", enable_ansi_colors)); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); } @@ -34,7 +34,7 @@ pub fn writeFormatCredentials(credentials: *S3Credentials, options: bun.S3.Multi if (credentials.secretAccessKey.len > 0) { try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("secretAccessKey: \"[REDACTED]\"", enable_ansi_colors)); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); } @@ -42,7 +42,7 @@ pub fn writeFormatCredentials(credentials: *S3Credentials, options: bun.S3.Multi if (credentials.sessionToken.len > 0) { try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("sessionToken: \"[REDACTED]\"", enable_ansi_colors)); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); } @@ -51,7 +51,7 @@ pub fn writeFormatCredentials(credentials: *S3Credentials, options: bun.S3.Multi try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("acl: ", enable_ansi_colors)); try writer.print(comptime bun.Output.prettyFmt("{s}\"", enable_ansi_colors), .{acl_value.toString()}); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); } @@ -59,14 +59,14 @@ pub fn writeFormatCredentials(credentials: *S3Credentials, options: bun.S3.Multi try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("partSize: ", enable_ansi_colors)); try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(options.partSize), .NumberObject, enable_ansi_colors); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime bun.Output.prettyFmt("queueSize: ", enable_ansi_colors)); try formatter.printAs(.Double, Writer, writer, jsc.JSValue.jsNumber(options.queueSize), .NumberObject, enable_ansi_colors); - formatter.printComma(Writer, writer, enable_ansi_colors) catch bun.outOfMemory(); + bun.handleOom(formatter.printComma(Writer, writer, enable_ansi_colors)); try writer.writeAll("\n"); try formatter.writeIndent(Writer, writer); diff --git a/src/bun.js/webcore/S3File.zig b/src/bun.js/webcore/S3File.zig index f2bab413a1..b8dfbb73a9 100644 --- a/src/bun.js/webcore/S3File.zig +++ b/src/bun.js/webcore/S3File.zig @@ -257,9 +257,9 @@ pub fn constructS3FileWithS3CredentialsAndOptions( const store = brk: { if (aws_options.changed_credentials) { - break :brk Blob.Store.initS3(path, null, aws_options.credentials, bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(Blob.Store.initS3(path, null, aws_options.credentials, bun.default_allocator)); } else { - break :brk Blob.Store.initS3WithReferencedCredentials(path, null, default_credentials, bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(Blob.Store.initS3WithReferencedCredentials(path, null, default_credentials, bun.default_allocator)); } }; errdefer store.deinit(); @@ -285,7 +285,7 @@ pub fn constructS3FileWithS3CredentialsAndOptions( blob.content_type = entry.value; break :inner; } - const content_type_buf = allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(allocator.alloc(u8, slice.len)); blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } @@ -304,7 +304,7 @@ pub fn constructS3FileWithS3Credentials( ) bun.JSError!Blob { var aws_options = try S3.S3Credentials.getCredentialsWithOptions(existing_credentials, .{}, options, null, null, globalObject); defer aws_options.deinit(); - const store = Blob.Store.initS3(path, null, aws_options.credentials, bun.default_allocator) catch bun.outOfMemory(); + const store = bun.handleOom(Blob.Store.initS3(path, null, aws_options.credentials, bun.default_allocator)); errdefer store.deinit(); store.data.s3.options = aws_options.options; store.data.s3.acl = aws_options.acl; @@ -328,7 +328,7 @@ pub fn constructS3FileWithS3Credentials( blob.content_type = entry.value; break :inner; } - const content_type_buf = allocator.alloc(u8, slice.len) catch bun.outOfMemory(); + const content_type_buf = bun.handleOom(allocator.alloc(u8, slice.len)); blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } diff --git a/src/bun.js/webcore/blob/Store.zig b/src/bun.js/webcore/blob/Store.zig index 342af63345..c8347b3dd0 100644 --- a/src/bun.js/webcore/blob/Store.zig +++ b/src/bun.js/webcore/blob/Store.zig @@ -418,7 +418,7 @@ pub const S3 = struct { var aws_options = try this.getCredentialsWithOptions(extra_options, globalThis); defer aws_options.deinit(); - const options = bun.S3.getListObjectsOptionsFromJS(globalThis, listOptions) catch bun.outOfMemory(); + const options = try bun.S3.getListObjectsOptionsFromJS(globalThis, listOptions); store.ref(); bun.S3.listObjects(&aws_options.credentials, options, @ptrCast(&Wrapper.resolve), bun.new(Wrapper, .{ diff --git a/src/bun.js/webcore/blob/copy_file.zig b/src/bun.js/webcore/blob/copy_file.zig index aea5ca46bd..74bbc8a1c1 100644 --- a/src/bun.js/webcore/blob/copy_file.zig +++ b/src/bun.js/webcore/blob/copy_file.zig @@ -44,7 +44,7 @@ pub const CopyFile = struct { }); store.ref(); source_store.ref(); - return CopyFilePromiseTask.createOnJSThread(allocator, globalThis, read_file) catch bun.outOfMemory(); + return bun.handleOom(CopyFilePromiseTask.createOnJSThread(allocator, globalThis, read_file)); } const linux = std.os.linux; @@ -593,7 +593,7 @@ pub const CopyFileWindows = struct { uv_buf: libuv.uv_buf_t = .{ .base = undefined, .len = 0 }, pub fn start(read_write_loop: *ReadWriteLoop, this: *CopyFileWindows) bun.sys.Maybe(void) { - read_write_loop.read_buf.ensureTotalCapacityPrecise(64 * 1024) catch bun.outOfMemory(); + bun.handleOom(read_write_loop.read_buf.ensureTotalCapacityPrecise(64 * 1024)); return read(read_write_loop, this); } diff --git a/src/bun.js/webcore/blob/read_file.zig b/src/bun.js/webcore/blob/read_file.zig index 0758c872de..ece0bcc56d 100644 --- a/src/bun.js/webcore/blob/read_file.zig +++ b/src/bun.js/webcore/blob/read_file.zig @@ -442,9 +442,9 @@ pub const ReadFile = struct { // We need to allocate a new buffer // In this case, we want to use `ensureTotalCapacityPrecis` so that it's an exact amount // We want to avoid over-allocating incase it's a large amount of data sent in a single chunk followed by a 0 byte chunk. - this.buffer.ensureTotalCapacityPrecise(bun.default_allocator, read.len) catch bun.outOfMemory(); + bun.handleOom(this.buffer.ensureTotalCapacityPrecise(bun.default_allocator, read.len)); } else { - this.buffer.ensureUnusedCapacity(bun.default_allocator, read.len) catch bun.outOfMemory(); + bun.handleOom(this.buffer.ensureUnusedCapacity(bun.default_allocator, read.len)); } this.buffer.appendSliceAssumeCapacity(read); } else { diff --git a/src/bun.js/webcore/fetch.zig b/src/bun.js/webcore/fetch.zig index 6c113a30c3..a0c8d7dc90 100644 --- a/src/bun.js/webcore/fetch.zig +++ b/src/bun.js/webcore/fetch.zig @@ -642,7 +642,7 @@ pub const FetchTasklet = struct { prom.reject(self.globalObject, res); } }; - var holder = bun.default_allocator.create(Holder) catch bun.outOfMemory(); + var holder = bun.handleOom(bun.default_allocator.create(Holder)); holder.* = .{ .held = result, // we need the promise to be alive until the task is done @@ -849,7 +849,7 @@ pub const FetchTasklet = struct { else => |e| bun.String.createFormat("{s} fetching \"{}\". For more information, pass `verbose: true` in the second argument to fetch()", .{ @errorName(e), path, - }) catch bun.outOfMemory(), + }) catch |err| bun.handleOom(err), }, .path = path, }; @@ -1203,8 +1203,14 @@ pub const FetchTasklet = struct { needs_schedule = stream_buffer.isEmpty(); //16 is the max size of a hex number size that represents 64 bits + 2 for the \r\n var formated_size_buffer: [18]u8 = undefined; - const formated_size = std.fmt.bufPrint(formated_size_buffer[0..], "{x}\r\n", .{data.len}) catch bun.outOfMemory(); - stream_buffer.ensureUnusedCapacity(formated_size.len + data.len + 2) catch bun.outOfMemory(); + const formated_size = std.fmt.bufPrint( + formated_size_buffer[0..], + "{x}\r\n", + .{data.len}, + ) catch |err| switch (err) { + error.NoSpaceLeft => unreachable, + }; + bun.handleOom(stream_buffer.ensureUnusedCapacity(formated_size.len + data.len + 2)); stream_buffer.writeAssumeCapacity(formated_size); stream_buffer.writeAssumeCapacity(data); stream_buffer.writeAssumeCapacity("\r\n"); @@ -1353,7 +1359,7 @@ pub const FetchTasklet = struct { } } else { if (success) { - _ = task.scheduled_response_buffer.write(task.response_buffer.list.items) catch bun.outOfMemory(); + _ = bun.handleOom(task.scheduled_response_buffer.write(task.response_buffer.list.items)); } // reset for reuse task.response_buffer.reset(); @@ -1437,7 +1443,7 @@ pub fn Bun__fetchPreconnect_( return globalObject.ERR(.INVALID_ARG_TYPE, fetch_error_blank_url, .{}).throw(); } - const url = ZigURL.parse(url_str.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory()); + const url = ZigURL.parse(bun.handleOom(url_str.toOwnedSlice(bun.default_allocator))); if (!url.isHTTP() and !url.isHTTPS() and !url.isS3()) { bun.default_allocator.free(url.href); return globalObject.throwInvalidArguments("URL must be HTTP or HTTPS", .{}); @@ -1485,7 +1491,7 @@ pub fn Bun__fetch_( bun.analytics.Features.fetch += 1; const vm = jsc.VirtualMachine.get(); - var memory_reporter = bun.default_allocator.create(bun.MemoryReportingAllocator) catch bun.outOfMemory(); + var memory_reporter = bun.handleOom(bun.default_allocator.create(bun.MemoryReportingAllocator)); // used to clean up dynamically allocated memory on error (a poor man's errdefer) var is_error = false; var allocator = memory_reporter.wrap(bun.default_allocator); @@ -1618,7 +1624,7 @@ pub fn Bun__fetch_( if (url_str_optional) |str| break :extract_url str; if (request) |req| { - req.ensureURL() catch bun.outOfMemory(); + bun.handleOom(req.ensureURL()); break :extract_url req.url.dupeRef(); } @@ -1781,7 +1787,7 @@ pub fn Bun__fetch_( is_error = true; return .zero; }) |config| { - const ssl_config_object = bun.default_allocator.create(SSLConfig) catch bun.outOfMemory(); + const ssl_config_object = bun.handleOom(bun.default_allocator.create(SSLConfig)); ssl_config_object.* = config; break :extract_ssl_config ssl_config_object; } @@ -2180,7 +2186,7 @@ pub fn Bun__fetch_( hostname = null; allocator.free(host); } - hostname = _hostname.toOwnedSliceZ(allocator) catch bun.outOfMemory(); + hostname = bun.handleOom(_hostname.toOwnedSliceZ(allocator)); } if (url.isS3()) { if (headers_.fastGet(bun.webcore.FetchHeaders.HTTPHeaderName.Range)) |_range| { @@ -2188,11 +2194,11 @@ pub fn Bun__fetch_( range = null; allocator.free(range_); } - range = _range.toOwnedSliceZ(allocator) catch bun.outOfMemory(); + range = bun.handleOom(_range.toOwnedSliceZ(allocator)); } } - break :extract_headers Headers.from(headers_, allocator, .{ .body = body.getAnyBlob() }) catch bun.outOfMemory(); + break :extract_headers Headers.from(headers_, allocator, .{ .body = body.getAnyBlob() }) catch |err| bun.handleOom(err); } break :extract_headers headers; @@ -2242,7 +2248,7 @@ pub fn Bun__fetch_( // Support blob: urls if (url_type == URLType.blob) { if (jsc.WebCore.ObjectURLRegistry.singleton().resolveAndDupe(url_path_decoded)) |blob| { - url_string = bun.String.createFormat("blob:{s}", .{url_path_decoded}) catch bun.outOfMemory(); + url_string = bun.String.createFormat("blob:{s}", .{url_path_decoded}) catch |err| bun.handleOom(err); break :blob blob; } else { // Consistent with what Node.js does - it rejects, not a 404. @@ -2338,7 +2344,7 @@ pub fn Bun__fetch_( null, allocator, .{ .body = body.getAnyBlob() }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } var http_body = body; @@ -2504,7 +2510,7 @@ pub fn Bun__fetch_( .body = .{ .value = .{ .InternalBlob = .{ - .bytes = std.ArrayList(u8).fromOwnedSlice(bun.default_allocator, bun.default_allocator.dupe(u8, err.message) catch bun.outOfMemory()), + .bytes = std.ArrayList(u8).fromOwnedSlice(bun.default_allocator, bun.handleOom(bun.default_allocator.dupe(u8, err.message))), .was_string = true, }, }, @@ -2573,7 +2579,7 @@ pub fn Bun__fetch_( // proxy and url are in the same buffer lets replace it const old_buffer = url_proxy_buffer; defer allocator.free(old_buffer); - var buffer = allocator.alloc(u8, result.url.len + proxy_.href.len) catch bun.outOfMemory(); + var buffer = bun.handleOom(allocator.alloc(u8, result.url.len + proxy_.href.len)); bun.copy(u8, buffer[0..result.url.len], result.url); bun.copy(u8, buffer[proxy_.href.len..], proxy_.href); url_proxy_buffer = buffer; @@ -2652,7 +2658,7 @@ pub fn Bun__fetch_( // will leak it // see https://github.com/oven-sh/bun/issues/2985 promise, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); if (Environment.isDebug) { if (body.store()) |store| { @@ -2683,7 +2689,7 @@ pub fn Bun__fetch_( } fn setHeaders(headers: *?Headers, new_headers: []const picohttp.Header, allocator: std.mem.Allocator) void { var old = headers.*; - headers.* = Headers.fromPicoHttpHeaders(new_headers, allocator) catch bun.outOfMemory(); + headers.* = bun.handleOom(Headers.fromPicoHttpHeaders(new_headers, allocator)); if (old) |*headers_| { headers_.deinit(); diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 9617807a44..b88ae0708c 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -1505,7 +1505,7 @@ pub const NetworkSink = struct { this.ended = true; // flush everything and send EOF if (this.task) |task| { - _ = task.writeBytes("", true) catch bun.outOfMemory(); + _ = bun.handleOom(task.writeBytes("", true)); } this.signal.close(err); @@ -1524,7 +1524,7 @@ pub const NetworkSink = struct { if (!this.ended) { this.ended = true; // we need to send EOF - _ = task.writeBytes("", true) catch bun.outOfMemory(); + _ = bun.handleOom(task.writeBytes("", true)); this.signal.close(null); } return .{ .result = value }; diff --git a/src/bun.zig b/src/bun.zig index 1c5ca65260..0d13f4ac57 100644 --- a/src/bun.zig +++ b/src/bun.zig @@ -2625,39 +2625,7 @@ pub noinline fn outOfMemory() noreturn { crash_handler.crashHandler(.out_of_memory, null, @returnAddress()); } -/// If `error_union` is `error.OutOfMemory`, calls `bun.outOfMemory`. Otherwise: -/// -/// * If that was the only possible error, returns the non-error payload. -/// * If other errors are possible, returns the same error union, but without `error.OutOfMemory` -/// in the error set. -/// -/// Prefer this method over `catch bun.outOfMemory()`, since that could mistakenly catch -/// non-OOM-related errors. -pub fn handleOom(error_union: anytype) blk: { - const error_union_info = @typeInfo(@TypeOf(error_union)).error_union; - const ErrorSet = error_union_info.error_set; - const oom_is_only_error = for (@typeInfo(ErrorSet).error_set orelse &.{}) |err| { - if (!std.mem.eql(u8, err.name, "OutOfMemory")) break false; - } else true; - - break :blk @TypeOf(error_union catch |err| if (comptime oom_is_only_error) - unreachable - else switch (err) { - error.OutOfMemory => unreachable, - else => |other_error| other_error, - }); -} { - const error_union_info = @typeInfo(@TypeOf(error_union)).error_union; - const Payload = error_union_info.payload; - const ReturnType = @TypeOf(handleOom(error_union)); - return error_union catch |err| - if (comptime ReturnType == Payload) - bun.outOfMemory() - else switch (err) { - error.OutOfMemory => bun.outOfMemory(), - else => |other_error| other_error, - }; -} +pub const handleOom = @import("./handle_oom.zig").handleOom; pub fn todoPanic( src: std.builtin.SourceLocation, diff --git a/src/bundler/AstBuilder.zig b/src/bundler/AstBuilder.zig index 24e718a45b..419285bbe7 100644 --- a/src/bundler/AstBuilder.zig +++ b/src/bundler/AstBuilder.zig @@ -290,7 +290,7 @@ pub const AstBuilder = struct { // stub methods for ImportScanner duck typing pub fn generateTempRef(ab: *AstBuilder, name: ?[]const u8) Ref { - return ab.newSymbol(.other, name orelse "temp") catch bun.outOfMemory(); + return bun.handleOom(ab.newSymbol(.other, name orelse "temp")); } pub fn recordExport(p: *AstBuilder, _: Logger.Loc, alias: []const u8, ref: Ref) !void { diff --git a/src/bundler/BundleThread.zig b/src/bundler/BundleThread.zig index cc33ea7908..f64665e94f 100644 --- a/src/bundler/BundleThread.zig +++ b/src/bundler/BundleThread.zig @@ -41,7 +41,7 @@ pub fn BundleThread(CompletionStruct: type) type { // Blocks the calling thread until the bun build thread is created. // std.once also blocks other callers of this function until the first caller is done. fn loadOnceImpl() void { - const bundle_thread = bun.default_allocator.create(Self) catch bun.outOfMemory(); + const bundle_thread = bun.handleOom(bun.default_allocator.create(Self)); bundle_thread.* = uninitialized; instance = bundle_thread; @@ -145,7 +145,7 @@ pub fn BundleThread(CompletionStruct: type) type { this.linker.source_maps.quoted_contents_wait_group.wait(); var out_log = Logger.Log.init(bun.default_allocator); - this.transpiler.log.appendToWithRecycled(&out_log, true) catch bun.outOfMemory(); + bun.handleOom(this.transpiler.log.appendToWithRecycled(&out_log, true)); completion.log = out_log; } @@ -154,7 +154,7 @@ pub fn BundleThread(CompletionStruct: type) type { } }; var out_log = Logger.Log.init(bun.default_allocator); - this.transpiler.log.appendToWithRecycled(&out_log, true) catch bun.outOfMemory(); + bun.handleOom(this.transpiler.log.appendToWithRecycled(&out_log, true)); completion.log = out_log; completion.completeOnBundleThread(); } diff --git a/src/bundler/Chunk.zig b/src/bundler/Chunk.zig index 261e3d8032..2abc1e462b 100644 --- a/src/bundler/Chunk.zig +++ b/src/bundler/Chunk.zig @@ -349,7 +349,12 @@ pub const Chunk = struct { remain, "\n//# debugId={}\n", .{bun.sourcemap.DebugIDFormatter{ .id = chunk.isolated_hash }}, - ) catch bun.outOfMemory()).len..]; + ) catch |err| switch (err) { + error.NoSpaceLeft => std.debug.panic( + "unexpected NoSpaceLeft error from bufPrint", + .{}, + ), + }).len..]; } bun.assert(remain.len == 0); @@ -377,7 +382,7 @@ pub const Chunk = struct { graph.heap.allocator(), "\n//# debugId={}\n", .{bun.sourcemap.DebugIDFormatter{ .id = chunk.isolated_hash }}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); break :brk try joiner.doneWithEnd(allocator, debug_id_fmt); } diff --git a/src/bundler/LinkerContext.zig b/src/bundler/LinkerContext.zig index 68d98eb407..8ccbc6bc58 100644 --- a/src/bundler/LinkerContext.zig +++ b/src/bundler/LinkerContext.zig @@ -162,7 +162,7 @@ pub const LinkerContext = struct { const source: *const Logger.Source = &this.parse_graph.input_files.items(.source)[source_index]; var mutable = MutableString.initEmpty(bun.default_allocator); - js_printer.quoteForJSON(source.contents, &mutable, false) catch bun.outOfMemory(); + bun.handleOom(js_printer.quoteForJSON(source.contents, &mutable, false)); quoted_source_contents.* = mutable.toDefaultOwned().toOptional(); } }; @@ -308,7 +308,7 @@ pub const LinkerContext = struct { @panic("Assertion failed: HTML import file not found in pathToSourceIndexMap"); }; - html_source_indices.push(this.allocator(), source_index) catch bun.outOfMemory(); + bun.handleOom(html_source_indices.push(this.allocator(), source_index)); // S.LazyExport is a call to __jsonParse. const original_ref = parts[html_import] @@ -332,7 +332,7 @@ pub const LinkerContext = struct { actual_ref, 1, Index.runtime, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } @@ -497,7 +497,7 @@ pub const LinkerContext = struct { this.allocator(), "Cannot import a \".{s}\" file into a CSS file", .{@tagName(loader)}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); }, .css, .file, .toml, .wasm, .base64, .dataurl, .text, .bunsh => {}, } @@ -840,7 +840,7 @@ pub const LinkerContext = struct { // Use the pretty path as the file name since it should be platform- // independent (relative paths and the "/" path separator) if (source.path.text.ptr == source.path.pretty.ptr) { - source.path = c.pathWithPrettyInitialized(source.path) catch bun.outOfMemory(); + source.path = bun.handleOom(c.pathWithPrettyInitialized(source.path)); } source.path.assertPrettyIsValid(); @@ -981,9 +981,9 @@ pub const LinkerContext = struct { const source = &input_files[other_source_index]; tla_pretty_path = source.path.pretty; notes.append(Logger.Data{ - .text = std.fmt.allocPrint(c.allocator(), "The top-level await in {s} is here:", .{tla_pretty_path}) catch bun.outOfMemory(), + .text = bun.handleOom(std.fmt.allocPrint(c.allocator(), "The top-level await in {s} is here:", .{tla_pretty_path})), .location = .initOrNull(source, parent_result_tla_keyword), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break; } @@ -1346,7 +1346,7 @@ pub const LinkerContext = struct { break :ref ref; }; - const entry = local_css_names.getOrPut(ref) catch bun.outOfMemory(); + const entry = bun.handleOom(local_css_names.getOrPut(ref)); if (entry.found_existing) continue; const source = all_sources[ref.source_index]; @@ -1360,8 +1360,8 @@ pub const LinkerContext = struct { false, ); - const final_generated_name = std.fmt.allocPrint(c.allocator(), "{s}_{s}", .{ original_name, path_hash }) catch bun.outOfMemory(); - c.mangled_props.put(c.allocator(), ref, final_generated_name) catch bun.outOfMemory(); + const final_generated_name = bun.handleOom(std.fmt.allocPrint(c.allocator(), "{s}_{s}", .{ original_name, path_hash })); + bun.handleOom(c.mangled_props.put(c.allocator(), ref, final_generated_name)); } } } @@ -1761,7 +1761,7 @@ pub const LinkerContext = struct { } const prev_source_index = tracker.source_index.get(); - c.cycle_detector.append(tracker) catch bun.outOfMemory(); + bun.handleOom(c.cycle_detector.append(tracker)); // Resolve the import by one step const advanced = c.advanceImportTracker(&tracker); @@ -2051,7 +2051,7 @@ pub const LinkerContext = struct { // Generate a dummy part that depends on the "__commonJS" symbol. const dependencies: []js_ast.Dependency = if (c.options.output_format != .internal_bake_dev) brk: { - const dependencies = c.allocator().alloc(js_ast.Dependency, common_js_parts.len) catch bun.outOfMemory(); + const dependencies = bun.handleOom(c.allocator().alloc(js_ast.Dependency, common_js_parts.len)); for (common_js_parts, dependencies) |part, *cjs| { cjs.* = .{ .part_index = part, @@ -2061,7 +2061,7 @@ pub const LinkerContext = struct { break :brk dependencies; } else &.{}; var symbol_uses: Part.SymbolUseMap = .empty; - symbol_uses.put(c.allocator(), wrapper_ref, .{ .count_estimate = 1 }) catch bun.outOfMemory(); + bun.handleOom(symbol_uses.put(c.allocator(), wrapper_ref, .{ .count_estimate = 1 })); const part_index = c.graph.addPartToFile( source_index, .{ @@ -2119,7 +2119,7 @@ pub const LinkerContext = struct { } var symbol_uses: Part.SymbolUseMap = .empty; - symbol_uses.put(c.allocator(), wrapper_ref, .{ .count_estimate = 1 }) catch bun.outOfMemory(); + bun.handleOom(symbol_uses.put(c.allocator(), wrapper_ref, .{ .count_estimate = 1 })); const part_index = c.graph.addPartToFile( source_index, .{ @@ -2139,7 +2139,7 @@ pub const LinkerContext = struct { c.esm_runtime_ref, 1, Index.runtime, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } }, else => {}, @@ -2280,7 +2280,7 @@ pub const LinkerContext = struct { imports_to_bind: *RefImportData, source_index: Index.Int, ) void { - var named_imports = named_imports_ptr.clone(c.allocator()) catch bun.outOfMemory(); + var named_imports = bun.handleOom(named_imports_ptr.clone(c.allocator())); defer named_imports_ptr.* = named_imports; const Sorter = struct { diff --git a/src/bundler/LinkerGraph.zig b/src/bundler/LinkerGraph.zig index c1fdba66df..ee7f200be8 100644 --- a/src/bundler/LinkerGraph.zig +++ b/src/bundler/LinkerGraph.zig @@ -129,7 +129,7 @@ pub fn addPartToFile( entry.value_ptr.* = .init(list.items); } else { - entry.value_ptr.* = BabyList(u32).fromSlice(self.graph.allocator, &.{self.part_id}) catch bun.outOfMemory(); + entry.value_ptr.* = BabyList(u32).fromSlice(self.graph.allocator, &.{self.part_id}) catch |err| bun.handleOom(err); } } else { entry.value_ptr.push(self.graph.allocator, self.part_id) catch unreachable; @@ -346,9 +346,9 @@ pub fn load( { var input_symbols = js_ast.Symbol.Map.initList(js_ast.Symbol.NestedList.init(this.ast.items(.symbols))); - var symbols = input_symbols.symbols_for_source.clone(this.allocator) catch bun.outOfMemory(); + var symbols = bun.handleOom(input_symbols.symbols_for_source.clone(this.allocator)); for (symbols.slice(), input_symbols.symbols_for_source.slice()) |*dest, src| { - dest.* = src.clone(this.allocator) catch bun.outOfMemory(); + dest.* = bun.handleOom(src.clone(this.allocator)); } this.symbols = js_ast.Symbol.Map.initList(symbols); } diff --git a/src/bundler/ParseTask.zig b/src/bundler/ParseTask.zig index f6908bf6dd..caa9d18f39 100644 --- a/src/bundler/ParseTask.zig +++ b/src/bundler/ParseTask.zig @@ -343,7 +343,7 @@ fn getAST( defer trace.end(); var temp_log = bun.logger.Log.init(allocator); defer { - temp_log.cloneToWithRecycled(log, true) catch bun.outOfMemory(); + bun.handleOom(temp_log.cloneToWithRecycled(log, true)); temp_log.msgs.clearAndFree(); } const root = try TOML.parse(source, &temp_log, allocator, false); @@ -354,7 +354,7 @@ fn getAST( defer trace.end(); var temp_log = bun.logger.Log.init(allocator); defer { - temp_log.cloneToWithRecycled(log, true) catch bun.outOfMemory(); + bun.handleOom(temp_log.cloneToWithRecycled(log, true)); temp_log.msgs.clearAndFree(); } const root = try YAML.parse(source, &temp_log, allocator); @@ -375,7 +375,7 @@ fn getAST( source, Logger.Loc.Empty, "To use the \"sqlite\" loader, set target to \"bun\"", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return error.ParserError; } @@ -442,7 +442,7 @@ fn getAST( source, Logger.Loc.Empty, "Loading .node files won't work in the browser. Make sure to set target to \"bun\" or \"node\"", - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return error.ParserError; } @@ -525,7 +525,7 @@ fn getAST( const source_code = source.contents; var temp_log = bun.logger.Log.init(allocator); defer { - temp_log.appendToMaybeRecycled(log, source) catch bun.outOfMemory(); + bun.handleOom(temp_log.appendToMaybeRecycled(log, source)); } const css_module_suffix = ".module.css"; @@ -832,10 +832,10 @@ const OnBeforeParsePlugin = struct { @max(this.line, -1), @max(this.column, -1), @max(this.column_end - this.column, 0), - if (source_line_text.len > 0) allocator.dupe(u8, source_line_text) catch bun.outOfMemory() else null, + if (source_line_text.len > 0) bun.handleOom(allocator.dupe(u8, source_line_text)) else null, null, ); - var msg = Logger.Msg{ .data = .{ .location = location, .text = allocator.dupe(u8, this.message()) catch bun.outOfMemory() } }; + var msg = Logger.Msg{ .data = .{ .location = location, .text = bun.handleOom(allocator.dupe(u8, this.message())) } }; switch (this.level) { .err => msg.kind = .err, .warn => msg.kind = .warn, @@ -848,7 +848,7 @@ const OnBeforeParsePlugin = struct { } else if (msg.kind == .warn) { log.warnings += 1; } - log.addMsg(msg) catch bun.outOfMemory(); + bun.handleOom(log.addMsg(msg)); } pub fn logFn( @@ -1007,10 +1007,10 @@ const OnBeforeParsePlugin = struct { var msg = Logger.Msg{ .data = .{ .location = null, .text = bun.default_allocator.dupe( u8, "Native plugin set the `free_plugin_source_code_context` field without setting the `plugin_source_code_context` field.", - ) catch bun.outOfMemory() } }; + ) catch |err| bun.handleOom(err) } }; msg.kind = .err; args.context.log.errors += 1; - args.context.log.addMsg(msg) catch bun.outOfMemory(); + bun.handleOom(args.context.log.addMsg(msg)); return error.InvalidNativePlugin; } @@ -1344,7 +1344,7 @@ pub fn runFromThreadPool(this: *ParseTask) void { } }; - const result = bun.default_allocator.create(Result) catch bun.outOfMemory(); + const result = bun.handleOom(bun.default_allocator.create(Result)); result.* = .{ .ctx = this.ctx, diff --git a/src/bundler/ServerComponentParseTask.zig b/src/bundler/ServerComponentParseTask.zig index 6da3484259..9190243fa4 100644 --- a/src/bundler/ServerComponentParseTask.zig +++ b/src/bundler/ServerComponentParseTask.zig @@ -31,7 +31,7 @@ fn taskCallbackWrap(thread_pool_task: *ThreadPoolLib.Task) void { defer worker.unget(); var log = Logger.Log.init(worker.allocator); - const result = bun.default_allocator.create(ParseTask.Result) catch bun.outOfMemory(); + const result = bun.handleOom(bun.default_allocator.create(ParseTask.Result)); result.* = .{ .ctx = task.ctx, .task = undefined, diff --git a/src/bundler/bundle_v2.zig b/src/bundler/bundle_v2.zig index fbf0dd04c6..2d9fc0a529 100644 --- a/src/bundler/bundle_v2.zig +++ b/src/bundler/bundle_v2.zig @@ -172,7 +172,7 @@ pub const BundleV2 = struct { fn ensureClientTranspiler(this: *BundleV2) void { if (this.client_transpiler == null) { - _ = this.initializeClientTranspiler() catch bun.outOfMemory(); + _ = bun.handleOom(this.initializeClientTranspiler()); } } @@ -227,7 +227,7 @@ pub const BundleV2 = struct { pub inline fn transpilerForTarget(noalias this: *BundleV2, target: options.Target) *Transpiler { if (!this.transpiler.options.server_components and this.linker.dev_server == null) { if (target == .browser and this.transpiler.options.target.isServerSide()) { - return this.client_transpiler orelse this.initializeClientTranspiler() catch bun.outOfMemory(); + return this.client_transpiler orelse bun.handleOom(this.initializeClientTranspiler()); } return this.transpiler; @@ -245,7 +245,7 @@ pub const BundleV2 = struct { /// it is called on. Function must be called on the bundle thread. pub fn logForResolutionFailures(this: *BundleV2, abs_path: []const u8, bake_graph: bake.Graph) *bun.logger.Log { if (this.transpiler.options.dev_server) |dev| { - return dev.getLogForResolutionFailures(abs_path, bake_graph) catch bun.outOfMemory(); + return bun.handleOom(dev.getLogForResolutionFailures(abs_path, bake_graph)); } return this.transpiler.log; } @@ -499,7 +499,7 @@ pub const BundleV2 = struct { import_record.specifier, target.bakeGraph(), this.graph.input_files.items(.loader)[import_record.importer_source_index], - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); // Turn this into an invalid AST, so that incremental mode skips it when printing. this.graph.ast.items(.parts)[import_record.importer_source_index].len = 0; @@ -590,7 +590,7 @@ pub const BundleV2 = struct { if (path.pretty.ptr == path.text.ptr) { // TODO: outbase const rel = bun.path.relativePlatform(transpiler.fs.top_level_dir, path.text, .loose, false); - path.pretty = this.allocator().dupe(u8, rel) catch bun.outOfMemory(); + path.pretty = bun.handleOom(this.allocator().dupe(u8, rel)); } path.assertPrettyIsValid(); @@ -600,13 +600,13 @@ pub const BundleV2 = struct { secondary != path and !strings.eqlLong(secondary.text, path.text, true)) { - secondary_path_to_copy = secondary.dupeAlloc(this.allocator()) catch bun.outOfMemory(); + secondary_path_to_copy = bun.handleOom(secondary.dupeAlloc(this.allocator())); } } - const entry = this.pathToSourceIndexMap(target).getOrPut(this.allocator(), path.hashKey()) catch bun.outOfMemory(); + const entry = bun.handleOom(this.pathToSourceIndexMap(target).getOrPut(this.allocator(), path.hashKey())); if (!entry.found_existing) { - path.* = this.pathWithPrettyInitialized(path.*, target) catch bun.outOfMemory(); + path.* = bun.handleOom(this.pathWithPrettyInitialized(path.*, target)); const loader: Loader = brk: { const record: *ImportRecord = &this.graph.ast.items(.import_records)[import_record.importer_source_index].slice()[import_record.import_record_index]; if (record.loader) |out_loader| { @@ -623,7 +623,7 @@ pub const BundleV2 = struct { }, loader, import_record.original_target, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); entry.value_ptr.* = idx; out_source_index = Index.init(idx); @@ -636,9 +636,9 @@ pub const BundleV2 = struct { .browser => .{ this.pathToSourceIndexMap(this.transpiler.options.target), this.pathToSourceIndexMap(.bake_server_components_ssr) }, .bake_server_components_ssr => .{ this.pathToSourceIndexMap(this.transpiler.options.target), this.pathToSourceIndexMap(.browser) }, }; - a.put(this.allocator(), entry.key_ptr.*, entry.value_ptr.*) catch bun.outOfMemory(); + bun.handleOom(a.put(this.allocator(), entry.key_ptr.*, entry.value_ptr.*)); if (this.framework.?.server_components.?.separate_ssr_graph) - b.put(this.allocator(), entry.key_ptr.*, entry.value_ptr.*) catch bun.outOfMemory(); + bun.handleOom(b.put(this.allocator(), entry.key_ptr.*, entry.value_ptr.*)); } } else { out_source_index = Index.init(entry.value_ptr.*); @@ -671,10 +671,10 @@ pub const BundleV2 = struct { break :brk default; }; - path = this.pathWithPrettyInitialized(path, target) catch bun.outOfMemory(); + path = bun.handleOom(this.pathWithPrettyInitialized(path, target)); path.assertPrettyIsValid(); entry.value_ptr.* = source_index.get(); - this.graph.ast.append(this.allocator(), JSAst.empty) catch bun.outOfMemory(); + bun.handleOom(this.graph.ast.append(this.allocator(), JSAst.empty)); try this.graph.input_files.append(this.allocator(), .{ .source = .{ @@ -732,10 +732,10 @@ pub const BundleV2 = struct { break :brk loader; }; - path.* = this.pathWithPrettyInitialized(path.*, target) catch bun.outOfMemory(); + path.* = bun.handleOom(this.pathWithPrettyInitialized(path.*, target)); path.assertPrettyIsValid(); entry.value_ptr.* = source_index.get(); - this.graph.ast.append(this.allocator(), JSAst.empty) catch bun.outOfMemory(); + bun.handleOom(this.graph.ast.append(this.allocator(), JSAst.empty)); try this.graph.input_files.append(this.allocator(), .{ .source = .{ @@ -1007,7 +1007,7 @@ pub const BundleV2 = struct { abs_path, transpiler.log, this, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); transpiler.log.reset(); continue; }; @@ -1206,8 +1206,8 @@ pub const BundleV2 = struct { .source = source.*, .loader = loader, .side_effects = loader.sideEffects(), - }) catch bun.outOfMemory(); - var task = this.allocator().create(ParseTask) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); + var task = bun.handleOom(this.allocator().create(ParseTask)); task.* = ParseTask.init(resolve_result, source_index, this); task.loader = loader; task.jsx = this.transpilerForTarget(known_target).options.jsx; @@ -1246,8 +1246,8 @@ pub const BundleV2 = struct { .source = source.*, .loader = loader, .side_effects = loader.sideEffects(), - }) catch bun.outOfMemory(); - var task = this.allocator().create(ParseTask) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); + var task = bun.handleOom(this.allocator().create(ParseTask)); task.* = .{ .ctx = this, .path = source.path, @@ -1559,7 +1559,7 @@ pub const BundleV2 = struct { if (template.needs(.target)) { template.placeholder.target = @tagName(target); } - break :brk std.fmt.allocPrint(bun.default_allocator, "{}", .{template}) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{}", .{template})); }; const loader = loaders[index]; @@ -1572,7 +1572,7 @@ pub const BundleV2 = struct { } }, .size = source.contents.len, .output_path = output_path, - .input_path = bun.default_allocator.dupe(u8, source.path.text) catch bun.outOfMemory(), + .input_path = bun.handleOom(bun.default_allocator.dupe(u8, source.path.text)), .input_loader = .file, .output_kind = .asset, .loader = loader, @@ -1808,9 +1808,9 @@ pub const BundleV2 = struct { // Add .exe extension for Windows targets if not already present if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) { - full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch bun.outOfMemory(); + full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch |err| bun.handleOom(err); } else { - full_outfile_path = bun.default_allocator.dupe(u8, full_outfile_path) catch bun.outOfMemory(); + full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path)); } const dirname = std.fs.path.dirname(full_outfile_path) orelse "."; @@ -1825,7 +1825,7 @@ pub const BundleV2 = struct { if (!(dirname.len == 0 or strings.eqlComptime(dirname, "."))) { root_dir = root_dir.makeOpenPath(dirname, .{}) catch |err| { - return bun.StandaloneModuleGraph.CompileResult.fail(std.fmt.allocPrint(bun.default_allocator, "Failed to open output directory {s}: {s}", .{ dirname, @errorName(err) }) catch bun.outOfMemory()); + return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to open output directory {s}: {s}", .{ dirname, @errorName(err) }))); }; } @@ -1871,7 +1871,7 @@ pub const BundleV2 = struct { else null, ) catch |err| { - return bun.StandaloneModuleGraph.CompileResult.fail(std.fmt.allocPrint(bun.default_allocator, "{s}", .{@errorName(err)}) catch bun.outOfMemory()); + return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s}", .{@errorName(err)}))); }; if (result == .success) { @@ -1966,7 +1966,7 @@ pub const BundleV2 = struct { defer compile_result.deinit(); if (compile_result != .success) { - this.log.addError(null, Logger.Loc.Empty, this.log.msgs.allocator.dupe(u8, compile_result.error_message) catch bun.outOfMemory()) catch bun.outOfMemory(); + bun.handleOom(this.log.addError(null, Logger.Loc.Empty, bun.handleOom(this.log.msgs.allocator.dupe(u8, compile_result.error_message)))); this.result.value.deinit(); this.result = .{ .err = error.CompilationFailed }; } @@ -2189,9 +2189,9 @@ pub const BundleV2 = struct { source.path.keyForIncrementalGraph(), &temp_log, this, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { - log.msgs.append(msg) catch bun.outOfMemory(); + bun.handleOom(log.msgs.append(msg)); log.errors += @intFromBool(msg.kind == .err); log.warnings += @intFromBool(msg.kind == .warn); } @@ -2266,7 +2266,7 @@ pub const BundleV2 = struct { if (!existing.found_existing) { this.free_list.appendSlice(&.{ result.namespace, result.path }) catch {}; - path = this.pathWithPrettyInitialized(path, resolve.import_record.original_target) catch bun.outOfMemory(); + path = bun.handleOom(this.pathWithPrettyInitialized(path, resolve.import_record.original_target)); // We need to parse this const source_index = Index.init(@as(u32, @intCast(this.graph.ast.len))); @@ -2333,7 +2333,7 @@ pub const BundleV2 = struct { const entry = this.resolve_tasks_waiting_for_import_source_index.getOrPut( this.allocator(), resolve.import_record.importer_source_index, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); if (!entry.found_existing) { entry.value_ptr.* = .{}; } @@ -2343,7 +2343,7 @@ pub const BundleV2 = struct { .to_source_index = source_index, .import_record_index = resolve.import_record.import_record_index, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { const import_record: *ImportRecord = &source_import_records.slice()[resolve.import_record.import_record_index]; import_record.source_index = source_index; @@ -2762,7 +2762,7 @@ pub const BundleV2 = struct { const maybe_data_url = DataURL.parse(parse.path.text) catch return false; const data_url = maybe_data_url orelse return false; const maybe_decoded = data_url.decodeData(bun.default_allocator) catch return false; - this.free_list.append(maybe_decoded) catch bun.outOfMemory(); + bun.handleOom(this.free_list.append(maybe_decoded)); parse.contents_or_fd = .{ .contents = maybe_decoded, }; @@ -2785,7 +2785,7 @@ pub const BundleV2 = struct { parse.path.namespace, parse.path.text, }); - const load = bun.default_allocator.create(jsc.API.JSBundler.Load) catch bun.outOfMemory(); + const load = bun.handleOom(bun.default_allocator.create(jsc.API.JSBundler.Load)); load.* = jsc.API.JSBundler.Load.init(this, parse); load.dispatch(); return true; @@ -2856,7 +2856,7 @@ pub const BundleV2 = struct { estimated_resolve_queue_count += @as(usize, @intFromBool(!(import_record.is_internal or import_record.is_unused or import_record.source_index.isValid()))); } var resolve_queue = ResolveQueue.init(this.allocator()); - resolve_queue.ensureTotalCapacity(estimated_resolve_queue_count) catch bun.outOfMemory(); + bun.handleOom(resolve_queue.ensureTotalCapacity(estimated_resolve_queue_count)); var last_error: ?anyerror = null; @@ -3032,7 +3032,7 @@ pub const BundleV2 = struct { import_record.path.text, ast.target.bakeGraph(), // use the source file target not the altered one loader, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } } } @@ -3066,7 +3066,7 @@ pub const BundleV2 = struct { "", }, import_record.kind, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } else if (!ast.target.isBun() and strings.eqlComptime(import_record.path.text, "bun")) { addError( log, @@ -3083,7 +3083,7 @@ pub const BundleV2 = struct { "", }, import_record.kind, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } else if (!ast.target.isBun() and strings.hasPrefixComptime(import_record.path.text, "bun:")) { addError( log, @@ -3100,7 +3100,7 @@ pub const BundleV2 = struct { "", }, import_record.kind, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } else { addError( log, @@ -3110,7 +3110,7 @@ pub const BundleV2 = struct { "Could not resolve: \"{s}\". Maybe you need to \"bun install\"?", .{import_record.path.text}, import_record.kind, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } } else { const buf = bun.path_buffer_pool.get(); @@ -3130,7 +3130,7 @@ pub const BundleV2 = struct { "Could not resolve: \"{s}\"", .{specifier_to_use}, import_record.kind, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } } }, @@ -3172,7 +3172,7 @@ pub const BundleV2 = struct { this.allocator(), "Browser builds cannot import HTML files.", .{}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); continue; } @@ -3194,12 +3194,12 @@ pub const BundleV2 = struct { import_record.path.pretty = std.fmt.allocPrint(this.allocator(), bun.bake.DevServer.asset_prefix ++ "/{s}{s}", .{ &std.fmt.bytesToHex(std.mem.asBytes(&hash), .lower), std.fs.path.extension(path.text), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); import_record.path.is_disabled = false; } else { import_record.path.text = path.text; import_record.path.pretty = rel; - import_record.path = this.pathWithPrettyInitialized(path.*, target) catch bun.outOfMemory(); + import_record.path = bun.handleOom(this.pathWithPrettyInitialized(path.*, target)); if (loader == .html or entry.kind == .css) { import_record.path.is_disabled = true; } @@ -3228,13 +3228,13 @@ pub const BundleV2 = struct { import_record.kind = .html_manifest; } - const resolve_entry = resolve_queue.getOrPut(hash_key) catch bun.outOfMemory(); + const resolve_entry = bun.handleOom(resolve_queue.getOrPut(hash_key)); if (resolve_entry.found_existing) { import_record.path = resolve_entry.value_ptr.*.path; continue; } - path.* = this.pathWithPrettyInitialized(path.*, target) catch bun.outOfMemory(); + path.* = bun.handleOom(this.pathWithPrettyInitialized(path.*, target)); var secondary_path_to_copy: ?Fs.Path = null; if (resolve_result.path_pair.secondary) |*secondary| { @@ -3242,13 +3242,13 @@ pub const BundleV2 = struct { secondary != path and !strings.eqlLong(secondary.text, path.text, true)) { - secondary_path_to_copy = secondary.dupeAlloc(this.allocator()) catch bun.outOfMemory(); + secondary_path_to_copy = bun.handleOom(secondary.dupeAlloc(this.allocator())); } } import_record.path = path.*; debug("created ParseTask: {s}", .{path.text}); - const resolve_task = bun.default_allocator.create(ParseTask) catch bun.outOfMemory(); + const resolve_task = bun.handleOom(bun.default_allocator.create(ParseTask)); resolve_task.* = ParseTask.init(&resolve_result, Index.invalid, this); resolve_task.secondary_path_for_commonjs_interop = secondary_path_to_copy; @@ -3365,7 +3365,7 @@ pub const BundleV2 = struct { }; const loader: Loader = graph.input_files.items(.loader)[source]; if (!loader.shouldCopyForBundling()) { - this.finalizers.append(bun.default_allocator, parse_result.external) catch bun.outOfMemory(); + bun.handleOom(this.finalizers.append(bun.default_allocator, parse_result.external)); } else { graph.input_files.items(.allocator)[source] = ExternalFreeFunctionAllocator.create(parse_result.external.function.?, parse_result.external.ctx.?); } @@ -3446,7 +3446,7 @@ pub const BundleV2 = struct { // contents are allocated by bun.default_allocator &.fromOwnedSlice(bun.default_allocator, @constCast(result.source.contents)), result.content_hash_for_additional_file, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -3595,28 +3595,28 @@ pub const BundleV2 = struct { .named_exports = result.ast.named_exports, } }, result.source, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const ssr_source = &result.source; ssr_source.path.pretty = ssr_source.path.text; - ssr_source.path = this.pathWithPrettyInitialized(ssr_source.path, .bake_server_components_ssr) catch bun.outOfMemory(); + ssr_source.path = bun.handleOom(this.pathWithPrettyInitialized(ssr_source.path, .bake_server_components_ssr)); const ssr_index = this.enqueueParseTask2( ssr_source, graph.input_files.items(.loader)[result.source.index.get()], .bake_server_components_ssr, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); break :brk .{ reference_source_index, ssr_index }; } else brk: { // Enqueue only one file const server_source = &result.source; server_source.path.pretty = server_source.path.text; - server_source.path = this.pathWithPrettyInitialized(server_source.path, this.transpiler.options.target) catch bun.outOfMemory(); + server_source.path = bun.handleOom(this.pathWithPrettyInitialized(server_source.path, this.transpiler.options.target)); const server_index = this.enqueueParseTask2( server_source, graph.input_files.items(.loader)[result.source.index.get()], .browser, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); break :brk .{ server_index, Index.invalid.get() }; }; @@ -3625,7 +3625,7 @@ pub const BundleV2 = struct { this.allocator(), result.source.path.hashKey(), reference_source_index, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); graph.server_component_boundaries.put( this.allocator(), @@ -3633,7 +3633,7 @@ pub const BundleV2 = struct { result.use_directive, reference_source_index, ssr_index, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } }, .err => |*err| { @@ -3649,7 +3649,7 @@ pub const BundleV2 = struct { graph.input_files.items(.source)[err.source_index.get()].path.text, &err.log, this, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } else if (err.log.msgs.items.len > 0) { err.log.cloneToWithRecycled(this.transpiler.log, true) catch unreachable; } else { diff --git a/src/bundler/linker_context/computeChunks.zig b/src/bundler/linker_context/computeChunks.zig index a7ba643eee..7f73e32e9d 100644 --- a/src/bundler/linker_context/computeChunks.zig +++ b/src/bundler/linker_context/computeChunks.zig @@ -94,7 +94,7 @@ pub noinline fn computeChunks( .content = .{ .css = .{ .imports_in_chunk_in_order = order, - .asts = this.allocator().alloc(bun.css.BundlerStyleSheet, order.len) catch bun.outOfMemory(), + .asts = bun.handleOom(this.allocator().alloc(bun.css.BundlerStyleSheet, order.len)), }, }, .output_source_map = sourcemap.SourceMapPieces.init(this.allocator()), @@ -156,7 +156,7 @@ pub noinline fn computeChunks( var css_files_with_parts_in_chunk = std.AutoArrayHashMapUnmanaged(Index.Int, void){}; for (order.slice()) |entry| { if (entry.kind == .source_index) { - css_files_with_parts_in_chunk.put(this.allocator(), entry.kind.source_index.get(), {}) catch bun.outOfMemory(); + bun.handleOom(css_files_with_parts_in_chunk.put(this.allocator(), entry.kind.source_index.get(), {})); } } css_chunk_entry.value_ptr.* = .{ @@ -169,7 +169,7 @@ pub noinline fn computeChunks( .content = .{ .css = .{ .imports_in_chunk_in_order = order, - .asts = this.allocator().alloc(bun.css.BundlerStyleSheet, order.len) catch bun.outOfMemory(), + .asts = bun.handleOom(this.allocator().alloc(bun.css.BundlerStyleSheet, order.len)), }, }, .files_with_parts_in_chunk = css_files_with_parts_in_chunk, diff --git a/src/bundler/linker_context/doStep5.zig b/src/bundler/linker_context/doStep5.zig index 744f23c6cb..4b1d2520ac 100644 --- a/src/bundler/linker_context/doStep5.zig +++ b/src/bundler/linker_context/doStep5.zig @@ -226,11 +226,11 @@ pub fn createExportsForFile( defer Expr.Disabler.enable(); // 1 property per export - var properties = std.ArrayList(js_ast.G.Property) - .initCapacity(allocator, export_aliases.len) catch bun.outOfMemory(); + var properties = bun.handleOom(std.ArrayList(js_ast.G.Property) + .initCapacity(allocator, export_aliases.len)); var ns_export_symbol_uses = Part.SymbolUseMap{}; - ns_export_symbol_uses.ensureTotalCapacity(allocator, export_aliases.len) catch bun.outOfMemory(); + bun.handleOom(ns_export_symbol_uses.ensureTotalCapacity(allocator, export_aliases.len)); const initial_flags = c.graph.meta.items(.flags)[id]; const needs_exports_variable = initial_flags.needs_exports_variable; @@ -246,11 +246,11 @@ pub fn createExportsForFile( // + 1 if we need to do module.exports = __toCommonJS(exports) @as(usize, @intFromBool(force_include_exports_for_entry_point)); - var stmts = js_ast.Stmt.Batcher.init(allocator, stmts_count) catch bun.outOfMemory(); + var stmts = bun.handleOom(js_ast.Stmt.Batcher.init(allocator, stmts_count)); defer stmts.done(); const loc = Logger.Loc.Empty; // todo: investigate if preallocating this array is faster - var ns_export_dependencies = std.ArrayList(js_ast.Dependency).initCapacity(allocator, re_exports_count) catch bun.outOfMemory(); + var ns_export_dependencies = bun.handleOom(std.ArrayList(js_ast.Dependency).initCapacity(allocator, re_exports_count)); for (export_aliases) |alias| { var exp = resolved_exports.getPtr(alias).?.*; @@ -261,7 +261,7 @@ pub fn createExportsForFile( if (imports_to_bind[exp.data.source_index.get()].get(exp.data.import_ref)) |import_data| { exp.data.import_ref = import_data.data.import_ref; exp.data.source_index = import_data.data.source_index; - ns_export_dependencies.appendSlice(import_data.re_exports.slice()) catch bun.outOfMemory(); + bun.handleOom(ns_export_dependencies.appendSlice(import_data.re_exports.slice())); } // Exports of imports need EImportIdentifier in case they need to be re- diff --git a/src/bundler/linker_context/findAllImportedPartsInJSOrder.zig b/src/bundler/linker_context/findAllImportedPartsInJSOrder.zig index c797dc1279..1d9a702ec4 100644 --- a/src/bundler/linker_context/findAllImportedPartsInJSOrder.zig +++ b/src/bundler/linker_context/findAllImportedPartsInJSOrder.zig @@ -144,7 +144,7 @@ pub fn findImportedPartsInJSOrder( v.c.graph.files.items(.entry_point_chunk_index)[source_index] = v.chunk_index; } - v.files.append(source_index) catch bun.outOfMemory(); + bun.handleOom(v.files.append(source_index)); // CommonJS files are all-or-nothing so all parts must be contiguous if (!can_be_split) { @@ -154,7 +154,7 @@ pub fn findImportedPartsInJSOrder( .part_index_begin = 0, .part_index_end = @as(u32, @truncate(parts.len)), }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } diff --git a/src/bundler/linker_context/findImportedCSSFilesInJSOrder.zig b/src/bundler/linker_context/findImportedCSSFilesInJSOrder.zig index ac9b001940..5d4e995e80 100644 --- a/src/bundler/linker_context/findImportedCSSFilesInJSOrder.zig +++ b/src/bundler/linker_context/findImportedCSSFilesInJSOrder.zig @@ -16,7 +16,7 @@ /// to determine since the imports happen at run-time instead of compile-time. /// In this case we just pick an arbitrary but consistent order. pub fn findImportedCSSFilesInJSOrder(this: *LinkerContext, temp_allocator: std.mem.Allocator, entry_point: Index) BabyList(Index) { - var visited = BitSet.initEmpty(temp_allocator, this.graph.files.len) catch bun.outOfMemory(); + var visited = bun.handleOom(BitSet.initEmpty(temp_allocator, this.graph.files.len)); var order: BabyList(Index) = .{}; const all_import_records = this.graph.ast.items(.import_records); @@ -68,7 +68,7 @@ pub fn findImportedCSSFilesInJSOrder(this: *LinkerContext, temp_allocator: std.m } if (is_css and source_index.isValid()) { - o.push(temp, source_index) catch bun.outOfMemory(); + bun.handleOom(o.push(temp, source_index)); } } }.visit; diff --git a/src/bundler/linker_context/findImportedFilesInCSSOrder.zig b/src/bundler/linker_context/findImportedFilesInCSSOrder.zig index 3ea0d50749..926179da68 100644 --- a/src/bundler/linker_context/findImportedFilesInCSSOrder.zig +++ b/src/bundler/linker_context/findImportedFilesInCSSOrder.zig @@ -66,7 +66,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem visitor.visited.push( visitor.temp_allocator, source_index, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); const repr: *const bun.css.BundlerStyleSheet = visitor.css_asts[source_index.get()] orelse return; // Sanity check const top_level_rules = &repr.rules; @@ -100,10 +100,10 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem if (rule.import.hasConditions()) { // Fork our state var nested_conditions = wrapping_conditions.deepCloneInfallible(visitor.allocator); - var nested_import_records = wrapping_import_records.clone(visitor.allocator) catch bun.outOfMemory(); + var nested_import_records = bun.handleOom(wrapping_import_records.clone(visitor.allocator)); // Clone these import conditions and append them to the state - nested_conditions.push(visitor.allocator, rule.import.conditionsWithImportRecords(visitor.allocator, &nested_import_records)) catch bun.outOfMemory(); + bun.handleOom(nested_conditions.push(visitor.allocator, rule.import.conditionsWithImportRecords(visitor.allocator, &nested_import_records))); visitor.visit(record.source_index, &nested_conditions, wrapping_import_records); continue; } @@ -114,14 +114,14 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem // Record external depednencies if (!record.is_internal) { var all_conditions = wrapping_conditions.deepCloneInfallible(visitor.allocator); - var all_import_records = wrapping_import_records.clone(visitor.allocator) catch bun.outOfMemory(); + var all_import_records = bun.handleOom(wrapping_import_records.clone(visitor.allocator)); // If this import has conditions, append it to the list of overall // conditions for this external import. Note that an external import // may actually have multiple sets of conditions that can't be // merged. When this happens we need to generate a nested imported // CSS file using a data URL. if (rule.import.hasConditions()) { - all_conditions.push(visitor.allocator, rule.import.conditionsWithImportRecords(visitor.allocator, &all_import_records)) catch bun.outOfMemory(); + bun.handleOom(all_conditions.push(visitor.allocator, rule.import.conditionsWithImportRecords(visitor.allocator, &all_import_records))); visitor.order.push( visitor.allocator, Chunk.CssImportOrder{ @@ -131,7 +131,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem .conditions = all_conditions, .condition_import_records = all_import_records, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { visitor.order.push( visitor.allocator, @@ -142,7 +142,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem .conditions = wrapping_conditions.*, .condition_import_records = wrapping_import_records.*, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } debug( "Push external: {d}={s}", @@ -172,7 +172,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem visitor.order.push(visitor.allocator, Chunk.CssImportOrder{ .kind = .{ .source_index = source_index }, .conditions = wrapping_conditions.*, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } }; @@ -181,7 +181,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem .temp_allocator = temp_allocator, .graph = &this.graph, .parse_graph = this.parse_graph, - .visited = BabyList(Index).initCapacity(temp_allocator, 16) catch bun.outOfMemory(), + .visited = bun.handleOom(BabyList(Index).initCapacity(temp_allocator, 16)), .css_asts = this.graph.ast.items(.css), .all_import_records = this.graph.ast.items(.import_records), }; @@ -193,7 +193,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem } var order = visitor.order; - var wip_order = BabyList(Chunk.CssImportOrder).initCapacity(temp_allocator, order.len) catch bun.outOfMemory(); + var wip_order = bun.handleOom(BabyList(Chunk.CssImportOrder).initCapacity(temp_allocator, order.len)); const css_asts: []const ?*bun.css.BundlerStyleSheet = this.graph.ast.items(.css); @@ -208,7 +208,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem var is_at_layer_prefix = true; for (order.slice()) |*entry| { if ((entry.kind == .layers and is_at_layer_prefix) or entry.kind == .external_path) { - wip_order.push(temp_allocator, entry.*) catch bun.outOfMemory(); + bun.handleOom(wip_order.push(temp_allocator, entry.*)); } if (entry.kind != .layers) { is_at_layer_prefix = false; @@ -219,7 +219,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem is_at_layer_prefix = true; for (order.slice()) |*entry| { if ((entry.kind != .layers or !is_at_layer_prefix) and entry.kind != .external_path) { - wip_order.push(temp_allocator, entry.*) catch bun.outOfMemory(); + bun.handleOom(wip_order.push(temp_allocator, entry.*)); } if (entry.kind != .layers) { is_at_layer_prefix = false; @@ -246,7 +246,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem const entry = visitor.order.at(i); switch (entry.kind) { .source_index => |idx| { - const gop = source_index_duplicates.getOrPut(idx.get()) catch bun.outOfMemory(); + const gop = bun.handleOom(source_index_duplicates.getOrPut(idx.get())); if (!gop.found_existing) { gop.value_ptr.* = BabyList(u32){}; } @@ -261,10 +261,10 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem continue :next_backward; } } - gop.value_ptr.push(temp_allocator, i) catch bun.outOfMemory(); + bun.handleOom(gop.value_ptr.push(temp_allocator, i)); }, .external_path => |p| { - const gop = external_path_duplicates.getOrPut(p.text) catch bun.outOfMemory(); + const gop = bun.handleOom(external_path_duplicates.getOrPut(p.text)); if (!gop.found_existing) { gop.value_ptr.* = BabyList(u32){}; } @@ -279,7 +279,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem continue :next_backward; } } - gop.value_ptr.push(temp_allocator, i) catch bun.outOfMemory(); + bun.handleOom(gop.value_ptr.push(temp_allocator, i)); }, .layers => {}, } @@ -407,7 +407,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem // Allocate a new set of duplicate indices to track this combination. layer_duplicates.push(temp_allocator, DuplicateEntry{ .layers = layers_key, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } var duplicates = layer_duplicates.at(index).indices.slice(); var j = duplicates.len; @@ -449,7 +449,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem // Non-layer entries still need to be present because they have // other side effects beside inserting things in the layer order - wip_order.push(temp_allocator, entry.*) catch bun.outOfMemory(); + bun.handleOom(wip_order.push(temp_allocator, entry.*)); } // Don't add this to the duplicate list below because it's redundant @@ -460,8 +460,8 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem layer_duplicates.mut(index).indices.push( temp_allocator, wip_order.len, - ) catch bun.outOfMemory(); - wip_order.push(temp_allocator, entry.*) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); + bun.handleOom(wip_order.push(temp_allocator, entry.*)); } debugCssOrder(this, &wip_order, .WHILE_OPTIMIZING_REDUNDANT_LAYER_RULES); @@ -487,7 +487,7 @@ pub fn findImportedFilesInCSSOrder(this: *LinkerContext, temp_allocator: std.mem wip_order.mut(prev_index).kind.layers.toOwned(temp_allocator).append( temp_allocator, entry.kind.layers.inner().sliceConst(), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } diff --git a/src/bundler/linker_context/generateChunksInParallel.zig b/src/bundler/linker_context/generateChunksInParallel.zig index de82516eec..183b25e007 100644 --- a/src/bundler/linker_context/generateChunksInParallel.zig +++ b/src/bundler/linker_context/generateChunksInParallel.zig @@ -46,7 +46,7 @@ pub fn generateChunksInParallel( defer debug(" DONE {d} prepare CSS ast (total count)", .{total_count}); var batch = ThreadPoolLib.Batch{}; - const tasks = c.allocator().alloc(LinkerContext.PrepareCssAstTask, total_count) catch bun.outOfMemory(); + const tasks = bun.handleOom(c.allocator().alloc(LinkerContext.PrepareCssAstTask, total_count)); var i: usize = 0; for (chunks) |*chunk| { if (chunk.content == .css) { @@ -71,7 +71,7 @@ pub fn generateChunksInParallel( } { - const chunk_contexts = c.allocator().alloc(GenerateChunkCtx, chunks.len) catch bun.outOfMemory(); + const chunk_contexts = bun.handleOom(c.allocator().alloc(GenerateChunkCtx, chunks.len)); defer c.allocator().free(chunk_contexts); { @@ -81,28 +81,28 @@ pub fn generateChunksInParallel( .javascript => { chunk_ctx.* = .{ .c = c, .chunks = chunks, .chunk = chunk }; total_count += chunk.content.javascript.parts_in_chunk_in_order.len; - chunk.compile_results_for_chunk = c.allocator().alloc(CompileResult, chunk.content.javascript.parts_in_chunk_in_order.len) catch bun.outOfMemory(); + chunk.compile_results_for_chunk = bun.handleOom(c.allocator().alloc(CompileResult, chunk.content.javascript.parts_in_chunk_in_order.len)); has_js_chunk = true; }, .css => { has_css_chunk = true; chunk_ctx.* = .{ .c = c, .chunks = chunks, .chunk = chunk }; total_count += chunk.content.css.imports_in_chunk_in_order.len; - chunk.compile_results_for_chunk = c.allocator().alloc(CompileResult, chunk.content.css.imports_in_chunk_in_order.len) catch bun.outOfMemory(); + chunk.compile_results_for_chunk = bun.handleOom(c.allocator().alloc(CompileResult, chunk.content.css.imports_in_chunk_in_order.len)); }, .html => { has_html_chunk = true; // HTML gets only one chunk. chunk_ctx.* = .{ .c = c, .chunks = chunks, .chunk = chunk }; total_count += 1; - chunk.compile_results_for_chunk = c.allocator().alloc(CompileResult, 1) catch bun.outOfMemory(); + chunk.compile_results_for_chunk = bun.handleOom(c.allocator().alloc(CompileResult, 1)); }, } } debug(" START {d} compiling part ranges", .{total_count}); defer debug(" DONE {d} compiling part ranges", .{total_count}); - const combined_part_ranges = c.allocator().alloc(PendingPartRange, total_count) catch bun.outOfMemory(); + const combined_part_ranges = bun.handleOom(c.allocator().alloc(PendingPartRange, total_count)); defer c.allocator().free(combined_part_ranges); var remaining_part_ranges = combined_part_ranges; var batch = ThreadPoolLib.Batch{}; @@ -227,7 +227,7 @@ pub fn generateChunksInParallel( chunk_visit_map.setAll(false); chunk.template.placeholder.hash = hash.digest(); - const rel_path = std.fmt.allocPrint(c.allocator(), "{any}", .{chunk.template}) catch bun.outOfMemory(); + const rel_path = bun.handleOom(std.fmt.allocPrint(c.allocator(), "{any}", .{chunk.template})); bun.path.platformToPosixInPlace(u8, rel_path); if ((try path_names_map.getOrPut(rel_path)).found_existing) { @@ -242,7 +242,7 @@ pub fn generateChunksInParallel( // use resolvePosix since we asserted above all seps are '/' if (Environment.isWindows and std.mem.indexOf(u8, rel_path, "/./") != null) { var buf: bun.PathBuffer = undefined; - const rel_path_fixed = c.allocator().dupe(u8, bun.path.normalizeBuf(rel_path, &buf, .posix)) catch bun.outOfMemory(); + const rel_path_fixed = bun.handleOom(c.allocator().dupe(u8, bun.path.normalizeBuf(rel_path, &buf, .posix))); chunk.final_rel_path = rel_path_fixed; continue; } @@ -315,7 +315,7 @@ pub fn generateChunksInParallel( } const bundler = @as(*bun.bundle_v2.BundleV2, @fieldParentPtr("linker", c)); - var static_route_visitor = StaticRouteVisitor{ .c = c, .visited = bun.bit_set.AutoBitSet.initEmpty(bun.default_allocator, c.graph.files.len) catch bun.outOfMemory() }; + var static_route_visitor = StaticRouteVisitor{ .c = c, .visited = bun.handleOom(bun.bit_set.AutoBitSet.initEmpty(bun.default_allocator, c.graph.files.len)) }; defer static_route_visitor.deinit(); // Don't write to disk if compile mode is enabled - we need buffer values for compilation @@ -356,7 +356,7 @@ pub fn generateChunksInParallel( switch (chunk.content.sourcemap(c.options.source_maps)) { .external, .linked => |tag| { const output_source_map = chunk.output_source_map.finalize(bun.default_allocator, code_result.shifts) catch @panic("Failed to allocate memory for external source map"); - var source_map_final_rel_path = bun.default_allocator.alloc(u8, chunk.final_rel_path.len + ".map".len) catch bun.outOfMemory(); + var source_map_final_rel_path = bun.handleOom(bun.default_allocator.alloc(u8, chunk.final_rel_path.len + ".map".len)); bun.copy(u8, source_map_final_rel_path, chunk.final_rel_path); bun.copy(u8, source_map_final_rel_path[chunk.final_rel_path.len..], ".map"); @@ -445,8 +445,8 @@ pub fn generateChunksInParallel( fdpath[chunk.final_rel_path.len..][0..bun.bytecode_extension.len].* = bun.bytecode_extension.*; break :brk options.OutputFile.init(.{ - .output_path = bun.default_allocator.dupe(u8, source_provider_url_str.slice()) catch bun.outOfMemory(), - .input_path = std.fmt.allocPrint(bun.default_allocator, "{s}" ++ bun.bytecode_extension, .{chunk.final_rel_path}) catch bun.outOfMemory(), + .output_path = bun.handleOom(bun.default_allocator.dupe(u8, source_provider_url_str.slice())), + .input_path = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s}" ++ bun.bytecode_extension, .{chunk.final_rel_path})), .input_loader = .js, .hash = if (chunk.template.placeholder.hash != null) bun.hash(bytecode) else null, .output_kind = .bytecode, @@ -464,7 +464,7 @@ pub fn generateChunksInParallel( // an error c.log.addErrorFmt(null, Logger.Loc.Empty, bun.default_allocator, "Failed to generate bytecode for {s}", .{ chunk.final_rel_path, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } } } diff --git a/src/bundler/linker_context/generateCodeForFileInChunkJS.zig b/src/bundler/linker_context/generateCodeForFileInChunkJS.zig index 9fb99b10df..171b1cedf8 100644 --- a/src/bundler/linker_context/generateCodeForFileInChunkJS.zig +++ b/src/bundler/linker_context/generateCodeForFileInChunkJS.zig @@ -43,7 +43,7 @@ pub fn generateCodeForFileInChunkJS( const main_stmts_len = stmts.inside_wrapper_prefix.items.len + stmts.inside_wrapper_suffix.items.len; const all_stmts_len = main_stmts_len + stmts.outside_wrapper_prefix.items.len + 1; - stmts.all_stmts.ensureUnusedCapacity(all_stmts_len) catch bun.outOfMemory(); + bun.handleOom(stmts.all_stmts.ensureUnusedCapacity(all_stmts_len)); stmts.all_stmts.appendSliceAssumeCapacity(stmts.inside_wrapper_prefix.items); stmts.all_stmts.appendSliceAssumeCapacity(stmts.inside_wrapper_suffix.items); @@ -71,7 +71,7 @@ pub fn generateCodeForFileInChunkJS( } stmts.all_stmts.appendAssumeCapacity(Stmt.allocateExpr(temp_allocator, Expr.init(E.Function, .{ .func = .{ - .args = temp_allocator.dupe(G.Arg, clousure_args.slice()) catch bun.outOfMemory(), + .args = bun.handleOom(temp_allocator.dupe(G.Arg, clousure_args.slice())), .body = .{ .stmts = inner, .loc = Logger.Loc.Empty, @@ -90,7 +90,7 @@ pub fn generateCodeForFileInChunkJS( c.options.target, c.resolver.fs.top_level_dir, allocator, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } return c.printCodeForFileInChunkJS( @@ -419,7 +419,7 @@ pub fn generateCodeForFileInChunkJS( ), .value = null, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return Expr.initIdentifier(ref, loc); } @@ -446,7 +446,7 @@ pub fn generateCodeForFileInChunkJS( if (can_be_moved) { // if the value can be moved, move the decl directly to preserve destructuring // ie `const { main } = class { static main() {} }` => `var {main} = class { static main() {} }` - hoist.decls.append(hoist.allocator, decl.*) catch bun.outOfMemory(); + bun.handleOom(hoist.decls.append(hoist.allocator, decl.*)); } else { // if the value cannot be moved, add every destructuring key separately // ie `var { append } = { append() {} }` => `var append; __esm(() => ({ append } = { append() {} }))` @@ -468,12 +468,12 @@ pub fn generateCodeForFileInChunkJS( break :stmt Stmt.allocateExpr(temp_allocator, value); }, .s_function => { - stmts.outside_wrapper_prefix.append(stmt) catch bun.outOfMemory(); + bun.handleOom(stmts.outside_wrapper_prefix.append(stmt)); continue; }, .s_class => |class| stmt: { if (class.class.canBeMoved()) { - stmts.outside_wrapper_prefix.append(stmt) catch bun.outOfMemory(); + bun.handleOom(stmts.outside_wrapper_prefix.append(stmt)); continue; } @@ -516,7 +516,7 @@ pub fn generateCodeForFileInChunkJS( bun.assert(!ast.wrapper_ref.isEmpty()); // js_parser's needsWrapperRef thought wrapper was not needed // "__esm(() => { ... })" - var esm_args = temp_allocator.alloc(Expr, 1) catch bun.outOfMemory(); + var esm_args = bun.handleOom(temp_allocator.alloc(Expr, 1)); esm_args[0] = Expr.init(E.Arrow, .{ .args = &.{}, .is_async = is_async, @@ -532,7 +532,7 @@ pub fn generateCodeForFileInChunkJS( .args = bun.BabyList(Expr).init(esm_args), }, Logger.Loc.Empty); - var decls = temp_allocator.alloc(G.Decl, 1) catch bun.outOfMemory(); + var decls = bun.handleOom(temp_allocator.alloc(G.Decl, 1)); decls[0] = G.Decl{ .binding = Binding.alloc( temp_allocator, @@ -548,7 +548,7 @@ pub fn generateCodeForFileInChunkJS( Stmt.alloc(S.Local, .{ .decls = G.Decl.List.init(decls), }, Logger.Loc.Empty), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { // // If this fails, then there will be places we reference // // `init_foo` without it actually existing. @@ -588,9 +588,9 @@ pub fn generateCodeForFileInChunkJS( Logger.Loc.Empty, ), .value = value, - }}) catch bun.outOfMemory(), + }}) catch |err| bun.handleOom(err), }, Logger.Loc.Empty), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } }, diff --git a/src/bundler/linker_context/generateCodeForLazyExport.zig b/src/bundler/linker_context/generateCodeForLazyExport.zig index bd098d78a5..8e8d3746bf 100644 --- a/src/bundler/linker_context/generateCodeForLazyExport.zig +++ b/src/bundler/linker_context/generateCodeForLazyExport.zig @@ -89,7 +89,7 @@ pub fn generateCodeForLazyExport(this: *LinkerContext, source_index: Index.Int) .cooked = E.String.init(" "), }, .tail_loc = visitor.loc, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); if (from_this_file) { visitor.inner_visited.set(ref.innerIndex()); @@ -121,7 +121,7 @@ pub fn generateCodeForLazyExport(this: *LinkerContext, source_index: Index.Int) .{ .loc = loc, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } fn visitComposes(visitor: *@This(), ast: *bun.css.BundlerStyleSheet, css_ref: bun.css.CssRef, idx: Index.Int) void { @@ -146,7 +146,7 @@ pub fn generateCodeForLazyExport(this: *LinkerContext, source_index: Index.Int) visitor.allocator, "Cannot use the \"composes\" property with the {} file (it is not a CSS file)", .{bun.fmt.quote(visitor.all_sources[import_record.source_index.get()].path.pretty)}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); continue; }; for (compose.names.slice()) |name| { @@ -177,7 +177,7 @@ pub fn generateCodeForLazyExport(this: *LinkerContext, source_index: Index.Int) }, .tail_loc = visitor.loc, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } else { @@ -193,7 +193,7 @@ pub fn generateCodeForLazyExport(this: *LinkerContext, source_index: Index.Int) bun.fmt.quote(name.v), bun.fmt.quote(visitor.all_sources[idx].path.pretty), }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); continue; }; const name_ref = name_entry.ref; @@ -240,7 +240,7 @@ pub fn generateCodeForLazyExport(this: *LinkerContext, source_index: Index.Int) .value = value, .tail_loc = stmt.loc, .tail = .{ .cooked = E.String.init("") }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); value = Expr.init( E.Template, E.Template{ diff --git a/src/bundler/linker_context/generateCompileResultForHtmlChunk.zig b/src/bundler/linker_context/generateCompileResultForHtmlChunk.zig index 2f4626fe3f..89d9afc263 100644 --- a/src/bundler/linker_context/generateCompileResultForHtmlChunk.zig +++ b/src/bundler/linker_context/generateCompileResultForHtmlChunk.zig @@ -51,7 +51,7 @@ fn generateCompileResultForHTMLChunkImpl(worker: *ThreadPool.Worker, c: *LinkerC added_head_tags: bool, pub fn onWriteHTML(this: *@This(), bytes: []const u8) void { - this.output.appendSlice(bytes) catch bun.outOfMemory(); + bun.handleOom(this.output.appendSlice(bytes)); } pub fn onHTMLParseError(_: *@This(), err: []const u8) void { @@ -81,11 +81,15 @@ fn generateCompileResultForHTMLChunkImpl(worker: *ThreadPool.Worker, c: *LinkerC if (this.linker.dev_server != null) { if (unique_key_for_additional_files.len > 0) { - element.setAttribute(url_attribute, unique_key_for_additional_files) catch bun.outOfMemory(); + element.setAttribute(url_attribute, unique_key_for_additional_files) catch { + std.debug.panic("unexpected error from Element.setAttribute", .{}); + }; } else if (import_record.path.is_disabled or loader.isJavaScriptLike() or loader.isCSS()) { element.remove(); } else { - element.setAttribute(url_attribute, import_record.path.pretty) catch bun.outOfMemory(); + element.setAttribute(url_attribute, import_record.path.pretty) catch { + std.debug.panic("unexpected error from Element.setAttribute", .{}); + }; } return; } @@ -102,7 +106,9 @@ fn generateCompileResultForHTMLChunkImpl(worker: *ThreadPool.Worker, c: *LinkerC } if (unique_key_for_additional_files.len > 0) { // Replace the external href/src with the unique key so that we later will rewrite it to the final URL or pathname - element.setAttribute(url_attribute, unique_key_for_additional_files) catch bun.outOfMemory(); + element.setAttribute(url_attribute, unique_key_for_additional_files) catch { + std.debug.panic("unexpected error from Element.setAttribute", .{}); + }; return; } } @@ -140,12 +146,12 @@ fn generateCompileResultForHTMLChunkImpl(worker: *ThreadPool.Worker, c: *LinkerC var array: std.BoundedArray([]const u8, 2) = .{}; // Put CSS before JS to reduce changes of flash of unstyled content if (this.chunk.getCSSChunkForHTML(this.chunks)) |css_chunk| { - const link_tag = std.fmt.allocPrintZ(allocator, "", .{css_chunk.unique_key}) catch bun.outOfMemory(); + const link_tag = bun.handleOom(std.fmt.allocPrintZ(allocator, "", .{css_chunk.unique_key})); array.appendAssumeCapacity(link_tag); } if (this.chunk.getJSChunkForHTML(this.chunks)) |js_chunk| { // type="module" scripts do not block rendering, so it is okay to put them in head - const script = std.fmt.allocPrintZ(allocator, "", .{js_chunk.unique_key}) catch bun.outOfMemory(); + const script = bun.handleOom(std.fmt.allocPrintZ(allocator, "", .{js_chunk.unique_key})); array.appendAssumeCapacity(script); } return array; @@ -208,7 +214,7 @@ fn generateCompileResultForHTMLChunkImpl(worker: *ThreadPool.Worker, c: *LinkerC HTMLScanner.HTMLProcessor(HTMLLoader, true).run( &html_loader, sources[chunk.entry_point.source_index].contents, - ) catch bun.outOfMemory(); + ) catch std.debug.panic("unexpected error from HTMLProcessor.run", .{}); // There are some cases where invalid HTML will make it so is // never emitted, even if the literal text DOES appear. These cases are @@ -233,7 +239,7 @@ fn generateCompileResultForHTMLChunkImpl(worker: *ThreadPool.Worker, c: *LinkerC const allocator = html_appender.get(); const slices = html_loader.getHeadTags(allocator); for (slices.slice()) |slice| { - html_loader.output.appendSlice(slice) catch bun.outOfMemory(); + bun.handleOom(html_loader.output.appendSlice(slice)); allocator.free(slice); } } diff --git a/src/bundler/linker_context/postProcessCSSChunk.zig b/src/bundler/linker_context/postProcessCSSChunk.zig index 5e58ce3df5..c969b53c0e 100644 --- a/src/bundler/linker_context/postProcessCSSChunk.zig +++ b/src/bundler/linker_context/postProcessCSSChunk.zig @@ -31,7 +31,7 @@ pub fn postProcessCSSChunk(ctx: GenerateChunkCtx, worker: *ThreadPool.Worker, ch const compile_results = chunk.compile_results_for_chunk; var compile_results_for_source_map: std.MultiArrayList(CompileResultForSourceMap) = .{}; - compile_results_for_source_map.setCapacity(worker.allocator, compile_results.len) catch bun.outOfMemory(); + bun.handleOom(compile_results_for_source_map.setCapacity(worker.allocator, compile_results.len)); const sources: []const Logger.Source = c.parse_graph.input_files.items(.source); for (compile_results) |compile_result| { @@ -93,7 +93,7 @@ pub fn postProcessCSSChunk(ctx: GenerateChunkCtx, worker: *ThreadPool.Worker, ch worker.allocator, &j, @as(u32, @truncate(ctx.chunks.len)), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); // TODO: meta contents chunk.isolated_hash = c.generateIsolatedHash(chunk); diff --git a/src/bundler/linker_context/postProcessHTMLChunk.zig b/src/bundler/linker_context/postProcessHTMLChunk.zig index 7a2cb84002..65ff00a67c 100644 --- a/src/bundler/linker_context/postProcessHTMLChunk.zig +++ b/src/bundler/linker_context/postProcessHTMLChunk.zig @@ -20,7 +20,7 @@ pub fn postProcessHTMLChunk(ctx: GenerateChunkCtx, worker: *ThreadPool.Worker, c worker.allocator, &j, @as(u32, @truncate(ctx.chunks.len)), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); chunk.isolated_hash = c.generateIsolatedHash(chunk); } diff --git a/src/bundler/linker_context/postProcessJSChunk.zig b/src/bundler/linker_context/postProcessJSChunk.zig index c95f1d4ac7..2328af78f4 100644 --- a/src/bundler/linker_context/postProcessJSChunk.zig +++ b/src/bundler/linker_context/postProcessJSChunk.zig @@ -210,7 +210,7 @@ pub fn postProcessJSChunk(ctx: GenerateChunkCtx, worker: *ThreadPool.Worker, chu var prev_filename_comment: Index.Int = 0; var compile_results_for_source_map: std.MultiArrayList(CompileResultForSourceMap) = .{}; - compile_results_for_source_map.setCapacity(worker.allocator, compile_results.len) catch bun.outOfMemory(); + bun.handleOom(compile_results_for_source_map.setCapacity(worker.allocator, compile_results.len)); const show_comments = c.options.mode == .bundle and !c.options.minify_whitespace; @@ -355,7 +355,7 @@ pub fn postProcessJSChunk(ctx: GenerateChunkCtx, worker: *ThreadPool.Worker, chu { const input = c.parse_graph.input_files.items(.source)[chunk.entry_point.source_index].path; var buf = MutableString.initEmpty(worker.allocator); - js_printer.quoteForJSON(input.pretty, &buf, true) catch bun.outOfMemory(); + bun.handleOom(js_printer.quoteForJSON(input.pretty, &buf, true)); const str = buf.slice(); // worker.allocator is an arena j.pushStatic(str); line_offset.advance(str); diff --git a/src/bundler/linker_context/prepareCssAstsForChunk.zig b/src/bundler/linker_context/prepareCssAstsForChunk.zig index 98bff1ef14..3c217eb563 100644 --- a/src/bundler/linker_context/prepareCssAstsForChunk.zig +++ b/src/bundler/linker_context/prepareCssAstsForChunk.zig @@ -33,7 +33,7 @@ fn prepareCssAstsForChunkImpl(c: *LinkerContext, chunk: *Chunk, allocator: std.m .names = bun.css.SmallList(bun.css.LayerName, 1).fromBabyListNoDeinit(layers.inner().*), .loc = bun.css.Location.dummy(), }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } var ast = bun.css.BundlerStyleSheet{ .rules = rules, @@ -53,7 +53,7 @@ fn prepareCssAstsForChunkImpl(c: *LinkerContext, chunk: *Chunk, allocator: std.m entry.condition_import_records.push( allocator, bun.ImportRecord{ .kind = .at, .path = p.*, .range = Logger.Range{} }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); // Handling a chain of nested conditions is complicated. We can't // necessarily join them together because a) there may be multiple @@ -82,7 +82,7 @@ fn prepareCssAstsForChunkImpl(c: *LinkerContext, chunk: *Chunk, allocator: std.m import_rule.conditionsMut().* = entry.conditions.at(j).*; rules.v.append(allocator, bun.css.BundlerCssRule{ .import = import_rule, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break :rules rules; }, .composes = .{}, @@ -107,7 +107,7 @@ fn prepareCssAstsForChunkImpl(c: *LinkerContext, chunk: *Chunk, allocator: std.m )) { .result => |v| v, .err => |e| { - c.log.addErrorFmt(null, Loc.Empty, c.allocator(), "Error generating CSS for import: {}", .{e}) catch bun.outOfMemory(); + bun.handleOom(c.log.addErrorFmt(null, Loc.Empty, c.allocator(), "Error generating CSS for import: {}", .{e})); continue; }, }; @@ -122,7 +122,7 @@ fn prepareCssAstsForChunkImpl(c: *LinkerContext, chunk: *Chunk, allocator: std.m .kind = .at, .path = p.*, .range = Logger.Range.none, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); chunk.content.css.asts[i] = bun.css.BundlerStyleSheet{ .rules = rules: { @@ -131,7 +131,7 @@ fn prepareCssAstsForChunkImpl(c: *LinkerContext, chunk: *Chunk, allocator: std.m import_rule.conditionsMut().* = actual_conditions.*; rules.v.append(allocator, bun.css.BundlerCssRule{ .import = import_rule, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break :rules rules; }, .sources = .{}, @@ -221,7 +221,7 @@ fn wrapRulesWithConditions( .loc = bun.css.Location.dummy(), }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); break :brk new_rules; }; @@ -242,7 +242,7 @@ fn wrapRulesWithConditions( .rules = ast.rules, .loc = bun.css.Location.dummy(), }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break :brk new_rules; }; } @@ -259,7 +259,7 @@ fn wrapRulesWithConditions( .rules = ast.rules, .loc = bun.css.Location.dummy(), }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break :brk new_rules; }; } diff --git a/src/bundler/linker_context/scanImportsAndExports.zig b/src/bundler/linker_context/scanImportsAndExports.zig index da0c0cd2c2..64bd1f6cb4 100644 --- a/src/bundler/linker_context/scanImportsAndExports.zig +++ b/src/bundler/linker_context/scanImportsAndExports.zig @@ -568,7 +568,7 @@ pub fn scanImportsAndExports(this: *LinkerContext) !void { const extra_count = @as(usize, @intFromBool(force_include_exports)) + @as(usize, @intFromBool(add_wrapper)); - var dependencies = std.ArrayList(js_ast.Dependency).initCapacity(this.allocator(), extra_count) catch bun.outOfMemory(); + var dependencies = bun.handleOom(std.ArrayList(js_ast.Dependency).initCapacity(this.allocator(), extra_count)); var resolved_exports_list: *ResolvedExports = &this.graph.meta.items(.resolved_exports)[id]; for (aliases) |alias| { @@ -581,12 +581,12 @@ pub fn scanImportsAndExports(this: *LinkerContext) !void { target_source_index = import_data.data.source_index; target_ref = import_data.data.import_ref; - dependencies.appendSlice(import_data.re_exports.slice()) catch bun.outOfMemory(); + bun.handleOom(dependencies.appendSlice(import_data.re_exports.slice())); } // Pull in all declarations of this symbol const top_to_parts = this.topLevelSymbolsToParts(target_source_index.get(), target_ref); - dependencies.ensureUnusedCapacity(top_to_parts.len) catch bun.outOfMemory(); + bun.handleOom(dependencies.ensureUnusedCapacity(top_to_parts.len)); for (top_to_parts) |part_index| { dependencies.appendAssumeCapacity(.{ .source_index = target_source_index, @@ -595,7 +595,7 @@ pub fn scanImportsAndExports(this: *LinkerContext) !void { } } - dependencies.ensureUnusedCapacity(extra_count) catch bun.outOfMemory(); + bun.handleOom(dependencies.ensureUnusedCapacity(extra_count)); // Ensure "exports" is included if the current output format needs it if (force_include_exports) { @@ -621,7 +621,7 @@ pub fn scanImportsAndExports(this: *LinkerContext) !void { .dependencies = js_ast.Dependency.List.fromList(dependencies), .can_be_removed_if_unused = false, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); parts = parts_list[id].slice(); this.graph.meta.items(.entry_point_part_index)[id] = Index.part(entry_point_part_index); @@ -959,7 +959,7 @@ const ExportStarContext = struct { if (i == source_index) return; } - this.source_index_stack.append(source_index) catch bun.outOfMemory(); + bun.handleOom(this.source_index_stack.append(source_index)); const stack_end_pos = this.source_index_stack.items.len; defer this.source_index_stack.shrinkRetainingCapacity(stack_end_pos - 1); @@ -999,7 +999,7 @@ const ExportStarContext = struct { } } - const gop = resolved_exports.getOrPut(this.allocator, alias) catch bun.outOfMemory(); + const gop = bun.handleOom(resolved_exports.getOrPut(this.allocator, alias)); if (!gop.found_existing) { // Initialize the re-export gop.value_ptr.* = .{ @@ -1017,7 +1017,7 @@ const ExportStarContext = struct { .import_ref = name.ref, .source_index = Index.source(other_source_index), }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } else if (gop.value_ptr.data.source_index.get() != other_source_index) { // Two different re-exports colliding makes it potentially ambiguous gop.value_ptr.potentially_ambiguous_export_star_refs.push(this.allocator, .{ @@ -1026,7 +1026,7 @@ const ExportStarContext = struct { .import_ref = name.ref, .name_loc = name.alias_loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } } @@ -1090,7 +1090,7 @@ fn validateComposesFromProperties( } fn addPropertyOrWarn(v: *@This(), local: Ref, property_name: []const u8, source_index: Index.Int, range: bun.logger.Range) void { - const entry = v.properties.getOrPut(property_name) catch bun.outOfMemory(); + const entry = bun.handleOom(v.properties.getOrPut(property_name)); if (!entry.found_existing) { entry.value_ptr.* = .{ @@ -1115,15 +1115,15 @@ fn validateComposesFromProperties( v.allocator, "The value of {s} in the class {s} is undefined.", .{ property_name, local_original_name }, - ) catch bun.outOfMemory(), - ).cloneLineText(v.log.clone_line_text, v.log.msgs.allocator) catch bun.outOfMemory(), + ) catch |err| bun.handleOom(err), + ).cloneLineText(v.log.clone_line_text, v.log.msgs.allocator) catch |err| bun.handleOom(err), .notes = v.allocator.dupe( Logger.Data, &.{ bun.logger.rangeData( &v.all_sources[entry.value_ptr.source_index], entry.value_ptr.range, - Logger.Log.allocPrint(v.allocator, "The first definition of {s} is in this style rule:", .{property_name}) catch bun.outOfMemory(), + bun.handleOom(Logger.Log.allocPrint(v.allocator, "The first definition of {s} is in this style rule:", .{property_name})), ), .{ .text = std.fmt.allocPrint( v.allocator, @@ -1131,10 +1131,10 @@ fn validateComposesFromProperties( "The value of the {} property for {} may change unpredictably as the code is edited. " ++ "Make sure that all definitions of {} for {} are in a single file.", .{ bun.fmt.quote(property_name), bun.fmt.quote(local_original_name), bun.fmt.quote(property_name), bun.fmt.quote(local_original_name) }, - ) catch bun.outOfMemory() }, + ) catch |err| bun.handleOom(err) }, }, - ) catch bun.outOfMemory(), - }) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err), + }) catch |err| bun.handleOom(err); // Don't warn more than once entry.value_ptr.source_index = Index.invalid.get(); diff --git a/src/bunfig.zig b/src/bunfig.zig index 0bda8a7fbc..91d705a864 100644 --- a/src/bunfig.zig +++ b/src/bunfig.zig @@ -751,7 +751,7 @@ pub const Bunfig = struct { .values = values, }; } - this.bunfig.bunfig_path = bun.default_allocator.dupe(u8, this.source.path.text) catch bun.outOfMemory(); + this.bunfig.bunfig_path = bun.handleOom(bun.default_allocator.dupe(u8, this.source.path.text)); if (serve_obj.get("publicPath")) |public_path| { if (public_path.asString(allocator)) |value| { diff --git a/src/cli.zig b/src/cli.zig index 4640b5277c..4f943e1d5d 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -1482,7 +1482,7 @@ pub const Command = struct { 'z' => FirstLetter.z, else => break :outer, }; - AddCompletions.init(bun.default_allocator) catch bun.outOfMemory(); + bun.handleOom(AddCompletions.init(bun.default_allocator)); const results = AddCompletions.getPackages(first_letter); var prefilled_i: usize = 0; diff --git a/src/cli/bunx_command.zig b/src/cli/bunx_command.zig index 5124a2e08e..5f56f9cf6c 100644 --- a/src/cli/bunx_command.zig +++ b/src/cli/bunx_command.zig @@ -336,7 +336,7 @@ pub const BunxCommand = struct { var opts = try Options.parse(ctx, argv); defer opts.deinit(); - var requests_buf = UpdateRequest.Array.initCapacity(ctx.allocator, 64) catch bun.outOfMemory(); + var requests_buf = bun.handleOom(UpdateRequest.Array.initCapacity(ctx.allocator, 64)); defer requests_buf.deinit(ctx.allocator); const update_requests = UpdateRequest.parse( ctx.allocator, @@ -743,7 +743,7 @@ pub const BunxCommand = struct { const argv_to_use = args.slice(); debug("installing package: {s}", .{bun.fmt.fmtSlice(argv_to_use, " ")}); - this_transpiler.env.map.put("BUN_INTERNAL_BUNX_INSTALL", "true") catch bun.outOfMemory(); + bun.handleOom(this_transpiler.env.map.put("BUN_INTERNAL_BUNX_INSTALL", "true")); const spawn_result = switch ((bun.spawnSync(&.{ .argv = argv_to_use, diff --git a/src/cli/create_command.zig b/src/cli/create_command.zig index e90ec614bd..de8ca03b43 100644 --- a/src/cli/create_command.zig +++ b/src/cli/create_command.zig @@ -1701,7 +1701,7 @@ pub const CreateCommand = struct { const extension = std.fs.path.extension(positional); if (Example.Tag.fromFileExtension(extension)) |tag| { example_tag = tag; - break :brk bun.default_allocator.dupe(u8, outdir_path) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.default_allocator.dupe(u8, outdir_path)); } // Show a warning when the local file exists and it's not a .js file // A lot of create-* npm packages have .js in the name, so you could end up with that warning. diff --git a/src/cli/filter_run.zig b/src/cli/filter_run.zig index 251961558f..62843379a4 100644 --- a/src/cli/filter_run.zig +++ b/src/cli/filter_run.zig @@ -58,8 +58,8 @@ pub const ProcessHandle = struct { var arena = std.heap.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); const original_path = this.state.env.map.get("PATH") orelse ""; - this.state.env.map.put("PATH", this.config.PATH) catch bun.outOfMemory(); - defer this.state.env.map.put("PATH", original_path) catch bun.outOfMemory(); + bun.handleOom(this.state.env.map.put("PATH", this.config.PATH)); + defer bun.handleOom(this.state.env.map.put("PATH", original_path)); const envp = try this.state.env.map.createNullDelimitedEnvMap(arena.allocator()); break :brk try (try bun.spawn.spawnProcess(&this.options, argv[0..], envp)).unwrap(); @@ -161,7 +161,7 @@ const State = struct { fn readChunk(this: *This, handle: *ProcessHandle, chunk: []const u8) !void { if (this.pretty_output) { - handle.buffer.appendSlice(chunk) catch bun.outOfMemory(); + bun.handleOom(handle.buffer.appendSlice(chunk)); this.redraw(false) catch {}; } else { var content = chunk; diff --git a/src/cli/install_command.zig b/src/cli/install_command.zig index 2dd5524580..e8d5baece2 100644 --- a/src/cli/install_command.zig +++ b/src/cli/install_command.zig @@ -27,7 +27,7 @@ fn install(ctx: Command.Context) !void { cli: *CommandLineArguments, pub fn onAnalyze(this: *@This(), result: *bun.bundle_v2.BundleV2.DependenciesScanner.Result) anyerror!void { // TODO: add separate argument that makes it so positionals[1..] is not done and instead the positionals are passed - var positionals = bun.default_allocator.alloc(string, result.dependencies.keys().len + 1) catch bun.outOfMemory(); + var positionals = bun.handleOom(bun.default_allocator.alloc(string, result.dependencies.keys().len + 1)); positionals[0] = "install"; bun.copy(string, positionals[1..], result.dependencies.keys()); this.cli.positionals = positionals; diff --git a/src/cli/outdated_command.zig b/src/cli/outdated_command.zig index df801aab49..ae9bb6dc25 100644 --- a/src/cli/outdated_command.zig +++ b/src/cli/outdated_command.zig @@ -88,13 +88,13 @@ pub const OutdatedCommand = struct { original_cwd, manager, filters, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); defer bun.default_allocator.free(workspace_pkg_ids); try updateManifestsIfNecessary(manager, workspace_pkg_ids); try printOutdatedInfoTable(manager, workspace_pkg_ids, true, enable_ansi_colors); } else if (manager.options.do.recursive) { - const all_workspaces = getAllWorkspaces(bun.default_allocator, manager) catch bun.outOfMemory(); + const all_workspaces = bun.handleOom(getAllWorkspaces(bun.default_allocator, manager)); defer bun.default_allocator.free(all_workspaces); try updateManifestsIfNecessary(manager, all_workspaces); @@ -342,7 +342,7 @@ pub const OutdatedCommand = struct { var at_least_one_greater_than_zero = false; - const patterns_buf = bun.default_allocator.alloc(FilterType, args.len) catch bun.outOfMemory(); + const patterns_buf = bun.handleOom(bun.default_allocator.alloc(FilterType, args.len)); for (args, patterns_buf) |arg, *converted| { if (arg.len == 0) { converted.* = FilterType.init(&.{}, false); @@ -459,15 +459,15 @@ pub const OutdatedCommand = struct { if (package_name_len > max_name) max_name = package_name_len; - version_writer.print("{}", .{resolution.value.npm.version.fmt(string_buf)}) catch bun.outOfMemory(); + bun.handleOom(version_writer.print("{}", .{resolution.value.npm.version.fmt(string_buf)})); if (version_buf.items.len > max_current) max_current = version_buf.items.len; version_buf.clearRetainingCapacity(); - version_writer.print("{}", .{update_version.version.fmt(manifest.string_buf)}) catch bun.outOfMemory(); + bun.handleOom(version_writer.print("{}", .{update_version.version.fmt(manifest.string_buf)})); if (version_buf.items.len > max_update) max_update = version_buf.items.len; version_buf.clearRetainingCapacity(); - version_writer.print("{}", .{latest.version.fmt(manifest.string_buf)}) catch bun.outOfMemory(); + bun.handleOom(version_writer.print("{}", .{latest.version.fmt(manifest.string_buf)})); if (version_buf.items.len > max_latest) max_latest = version_buf.items.len; version_buf.clearRetainingCapacity(); @@ -482,7 +482,7 @@ pub const OutdatedCommand = struct { .workspace_pkg_id = workspace_pkg_id, .is_catalog = dep.version.tag == .catalog, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -603,7 +603,7 @@ pub const OutdatedCommand = struct { Output.pretty("{s}", .{table.symbols.verticalEdge()}); for (0..column_left_pad) |_| Output.pretty(" ", .{}); - version_writer.print("{}", .{resolution.value.npm.version.fmt(string_buf)}) catch bun.outOfMemory(); + bun.handleOom(version_writer.print("{}", .{resolution.value.npm.version.fmt(string_buf)})); Output.pretty("{s}", .{version_buf.items}); for (version_buf.items.len..current_column_inside_length + column_right_pad) |_| Output.pretty(" ", .{}); version_buf.clearRetainingCapacity(); @@ -614,7 +614,7 @@ pub const OutdatedCommand = struct { Output.pretty("{s}", .{table.symbols.verticalEdge()}); for (0..column_left_pad) |_| Output.pretty(" ", .{}); - version_writer.print("{}", .{update.version.fmt(manifest.string_buf)}) catch bun.outOfMemory(); + bun.handleOom(version_writer.print("{}", .{update.version.fmt(manifest.string_buf)})); Output.pretty("{s}", .{update.version.diffFmt(resolution.value.npm.version, manifest.string_buf, string_buf)}); for (version_buf.items.len..update_column_inside_length + column_right_pad) |_| Output.pretty(" ", .{}); version_buf.clearRetainingCapacity(); @@ -625,7 +625,7 @@ pub const OutdatedCommand = struct { Output.pretty("{s}", .{table.symbols.verticalEdge()}); for (0..column_left_pad) |_| Output.pretty(" ", .{}); - version_writer.print("{}", .{latest.version.fmt(manifest.string_buf)}) catch bun.outOfMemory(); + bun.handleOom(version_writer.print("{}", .{latest.version.fmt(manifest.string_buf)})); Output.pretty("{s}", .{latest.version.diffFmt(resolution.value.npm.version, manifest.string_buf, string_buf)}); for (version_buf.items.len..latest_column_inside_length + column_right_pad) |_| Output.pretty(" ", .{}); version_buf.clearRetainingCapacity(); diff --git a/src/cli/pack_command.zig b/src/cli/pack_command.zig index 50aaef2987..383a5cd8e2 100644 --- a/src/cli/pack_command.zig +++ b/src/cli/pack_command.zig @@ -2518,7 +2518,7 @@ pub const bindings = struct { defer sha1.deinit(); sha1.update(tarball); sha1.final(&sha1_digest); - const shasum_str = String.createFormat("{s}", .{std.fmt.bytesToHex(sha1_digest, .lower)}) catch bun.outOfMemory(); + const shasum_str = bun.handleOom(String.createFormat("{s}", .{std.fmt.bytesToHex(sha1_digest, .lower)})); var sha512_digest: sha.SHA512.Digest = undefined; var sha512 = sha.SHA512.init(); @@ -2591,7 +2591,7 @@ pub const bindings = struct { const pathname_string = if (bun.Environment.isWindows) blk: { const pathname_w = archive_entry.pathnameW(); const list = std.ArrayList(u8).init(bun.default_allocator); - var result = bun.strings.toUTF8ListWithType(list, []const u16, pathname_w) catch bun.outOfMemory(); + var result = bun.handleOom(bun.strings.toUTF8ListWithType(list, []const u16, pathname_w)); defer result.deinit(); break :blk String.cloneUTF8(result.items); } else String.cloneUTF8(archive_entry.pathname()); @@ -2607,7 +2607,7 @@ pub const bindings = struct { if (kind == .file) { const size: usize = @intCast(archive_entry.size()); - read_buf.resize(size) catch bun.outOfMemory(); + bun.handleOom(read_buf.resize(size)); defer read_buf.clearRetainingCapacity(); const read = archive.readData(read_buf.items); @@ -2623,7 +2623,7 @@ pub const bindings = struct { entry_info.contents = String.cloneUTF8(read_buf.items); } - entries_info.append(entry_info) catch bun.outOfMemory(); + bun.handleOom(entries_info.append(entry_info)); }, } } diff --git a/src/cli/run_command.zig b/src/cli/run_command.zig index 06488fbee9..45e9cc1a1d 100644 --- a/src/cli/run_command.zig +++ b/src/cli/run_command.zig @@ -622,7 +622,10 @@ pub const RunCommand = struct { return try allocator.dupeZ(u8, target_path_buffer[0 .. converted.len + file_name.len :0]); } - pub fn createFakeTemporaryNodeExecutable(PATH: *std.ArrayList(u8), optional_bun_path: *string) !void { + pub fn createFakeTemporaryNodeExecutable( + PATH: *std.ArrayList(u8), + optional_bun_path: *string, + ) (OOM || std.fs.SelfExePathError)!void { // If we are already running as "node", the path should exist if (CLI.pretend_to_be_node) return; @@ -890,11 +893,21 @@ pub const RunCommand = struct { var new_path = try std.ArrayList(u8).initCapacity(ctx.allocator, new_path_len); if (needs_to_force_bun) { - createFakeTemporaryNodeExecutable(&new_path, &optional_bun_self_path) catch bun.outOfMemory(); + createFakeTemporaryNodeExecutable( + &new_path, + &optional_bun_self_path, + ) catch |err| switch (err) { + error.OutOfMemory => bun.outOfMemory(), + else => |other| std.debug.panic( + "unexpected error from createFakeTemporaryNodeExecutable: {}", + .{other}, + ), + }; + if (!force_using_bun) { - this_transpiler.env.map.put("NODE", bun_node_exe) catch bun.outOfMemory(); - this_transpiler.env.map.put("npm_node_execpath", bun_node_exe) catch bun.outOfMemory(); - this_transpiler.env.map.put("npm_execpath", optional_bun_self_path) catch bun.outOfMemory(); + bun.handleOom(this_transpiler.env.map.put("NODE", bun_node_exe)); + bun.handleOom(this_transpiler.env.map.put("npm_node_execpath", bun_node_exe)); + bun.handleOom(this_transpiler.env.map.put("npm_execpath", optional_bun_self_path)); } needs_to_force_bun = false; @@ -943,7 +956,7 @@ pub const RunCommand = struct { } const new_path = try configurePathForRunWithPackageJsonDir(ctx, package_json_dir, this_transpiler, ORIGINAL_PATH, cwd, force_using_bun); - this_transpiler.env.map.put("PATH", new_path) catch bun.outOfMemory(); + bun.handleOom(this_transpiler.env.map.put("PATH", new_path)); } pub fn completions(ctx: Command.Context, default_completions: ?[]const string, reject_list: []const string, comptime filter: Filter) !ShellCompletions { diff --git a/src/cli/test/Scanner.zig b/src/cli/test/Scanner.zig index 73a1634530..4397af32e2 100644 --- a/src/cli/test/Scanner.zig +++ b/src/cli/test/Scanner.zig @@ -65,8 +65,8 @@ pub fn scan(this: *Scanner, path_literal: []const u8) Error!void { switch (err) { error.NotDir, error.ENOTDIR => { if (this.isTestFile(path)) { - const rel_path = bun.PathString.init(this.fs.filename_store.append([]const u8, path) catch bun.outOfMemory()); - this.test_files.append(this.allocator(), rel_path) catch bun.outOfMemory(); + const rel_path = bun.PathString.init(bun.handleOom(this.fs.filename_store.append([]const u8, path))); + bun.handleOom(this.test_files.append(this.allocator(), rel_path)); } }, error.ENOENT => return error.DoesNotExist, diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig index a23dfdcd40..d0737a1f40 100644 --- a/src/cli/test_command.zig +++ b/src/cli/test_command.zig @@ -364,7 +364,7 @@ pub const JunitReporter = struct { this.getHostname() orelse "", }); - this.contents.insertSlice(bun.default_allocator, suite_info.offset_of_attributes, summary) catch bun.outOfMemory(); + bun.handleOom(this.contents.insertSlice(bun.default_allocator, suite_info.offset_of_attributes, summary)); const indent = getIndent(this.current_depth); try this.contents.appendSlice(bun.default_allocator, indent); @@ -548,8 +548,8 @@ pub const JunitReporter = struct { metrics.skipped, elapsed_time, }); - this.contents.insertSlice(bun.default_allocator, this.offset_of_testsuites_value, summary) catch bun.outOfMemory(); - this.contents.appendSlice(bun.default_allocator, "\n") catch bun.outOfMemory(); + bun.handleOom(this.contents.insertSlice(bun.default_allocator, this.offset_of_testsuites_value, summary)); + bun.handleOom(this.contents.appendSlice(bun.default_allocator, "\n")); } var junit_path_buf: bun.PathBuffer = undefined; @@ -686,14 +686,14 @@ pub const CommandLineReporter = struct { if (!strings.eql(junit.current_file, filename)) { while (junit.suite_stack.items.len > 0 and !junit.suite_stack.items[junit.suite_stack.items.len - 1].is_file_suite) { - junit.endTestSuite() catch bun.outOfMemory(); + bun.handleOom(junit.endTestSuite()); } if (junit.current_file.len > 0) { - junit.endTestSuite() catch bun.outOfMemory(); + bun.handleOom(junit.endTestSuite()); } - junit.beginTestSuite(filename) catch bun.outOfMemory(); + bun.handleOom(junit.beginTestSuite(filename)); } // To make the juint reporter generate nested suites, we need to find the needed suites and create/print them. @@ -705,7 +705,7 @@ pub const CommandLineReporter = struct { const index = (scopes.len - 1) - i; const scope = scopes[index]; if (scope.label.len > 0) { - needed_suites.append(scope) catch bun.outOfMemory(); + bun.handleOom(needed_suites.append(scope)); } } @@ -720,7 +720,7 @@ pub const CommandLineReporter = struct { while (current_suite_depth > needed_suites.items.len) { if (junit.suite_stack.items.len > 0 and !junit.suite_stack.items[junit.suite_stack.items.len - 1].is_file_suite) { - junit.endTestSuite() catch bun.outOfMemory(); + bun.handleOom(junit.endTestSuite()); current_suite_depth -= 1; } else { break; @@ -747,7 +747,7 @@ pub const CommandLineReporter = struct { while (suites_to_close > 0) { if (junit.suite_stack.items.len > 0 and !junit.suite_stack.items[junit.suite_stack.items.len - 1].is_file_suite) { - junit.endTestSuite() catch bun.outOfMemory(); + bun.handleOom(junit.endTestSuite()); current_suite_depth -= 1; suites_to_close -= 1; } else { @@ -764,7 +764,7 @@ pub const CommandLineReporter = struct { while (describe_suite_index < needed_suites.items.len) { const scope = needed_suites.items[describe_suite_index]; - junit.beginTestSuiteWithLine(scope.label, scope.line_number, false) catch bun.outOfMemory(); + bun.handleOom(junit.beginTestSuiteWithLine(scope.label, scope.line_number, false)); describe_suite_index += 1; } @@ -779,15 +779,15 @@ pub const CommandLineReporter = struct { for (scopes) |scope| { if (scope.label.len > 0) { if (initial_length != concatenated_describe_scopes.items.len) { - concatenated_describe_scopes.appendSlice(" > ") catch bun.outOfMemory(); + bun.handleOom(concatenated_describe_scopes.appendSlice(" > ")); } - escapeXml(scope.label, concatenated_describe_scopes.writer()) catch bun.outOfMemory(); + bun.handleOom(escapeXml(scope.label, concatenated_describe_scopes.writer())); } } } - junit.writeTestCase(status, filename, display_label, concatenated_describe_scopes.items, assertions, elapsed_ns, line_number) catch bun.outOfMemory(); + bun.handleOom(junit.writeTestCase(status, filename, display_label, concatenated_describe_scopes.items, assertions, elapsed_ns, line_number)); }, } } @@ -1424,7 +1424,7 @@ pub const TestCommand = struct { // try vm.ensureDebugger(false); - var scanner = Scanner.init(ctx.allocator, &vm.transpiler, ctx.positionals.len) catch bun.outOfMemory(); + var scanner = bun.handleOom(Scanner.init(ctx.allocator, &vm.transpiler, ctx.positionals.len)); defer scanner.deinit(); const has_relative_path = for (ctx.positionals) |arg| { if (std.fs.path.isAbsolute(arg) or @@ -1487,7 +1487,7 @@ pub const TestCommand = struct { }; } - const test_files = scanner.takeFoundTestFiles() catch bun.outOfMemory(); + const test_files = bun.handleOom(scanner.takeFoundTestFiles()); defer ctx.allocator.free(test_files); const search_count = scanner.search_count; diff --git a/src/cli/update_interactive_command.zig b/src/cli/update_interactive_command.zig index 256bd55536..19939d6117 100644 --- a/src/cli/update_interactive_command.zig +++ b/src/cli/update_interactive_command.zig @@ -370,14 +370,14 @@ pub const UpdateInteractiveCommand = struct { original_cwd, manager, filters, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else if (manager.options.do.recursive) blk: { - break :blk getAllWorkspaces(bun.default_allocator, manager) catch bun.outOfMemory(); + break :blk bun.handleOom(getAllWorkspaces(bun.default_allocator, manager)); } else blk: { const root_pkg_id = manager.root_package_id.get(manager.lockfile, manager.workspace_name_hash); if (root_pkg_id == invalid_package_id) return; - const ids = bun.default_allocator.alloc(PackageID, 1) catch bun.outOfMemory(); + const ids = bun.handleOom(bun.default_allocator.alloc(PackageID, 1)); ids[0] = root_pkg_id; break :blk ids; }; diff --git a/src/cli/upgrade_command.zig b/src/cli/upgrade_command.zig index 0d8893fb3f..202888d377 100644 --- a/src/cli/upgrade_command.zig +++ b/src/cli/upgrade_command.zig @@ -27,7 +27,7 @@ pub const Version = struct { ), ), }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } return this.tag; } @@ -820,7 +820,7 @@ pub const UpgradeCommand = struct { "completions", }; - env_loader.map.put("IS_BUN_AUTO_UPDATE", "true") catch bun.outOfMemory(); + bun.handleOom(env_loader.map.put("IS_BUN_AUTO_UPDATE", "true")); var std_map = try env_loader.map.stdEnvMap(ctx.allocator); defer std_map.deinit(); _ = std.process.Child.run(.{ diff --git a/src/codegen/generate-node-errors.ts b/src/codegen/generate-node-errors.ts index c3f10c0bc0..3eedd43170 100644 --- a/src/codegen/generate-node-errors.ts +++ b/src/codegen/generate-node-errors.ts @@ -137,7 +137,7 @@ zig += ` return toJS(this, globalThis, &message); } - var message = bun.String.createFormat(fmt_str, args) catch bun.outOfMemory(); + var message = bun.handleOom(bun.String.createFormat(fmt_str, args)); return toJS(this, globalThis, &message); } diff --git a/src/collections/hive_array.zig b/src/collections/hive_array.zig index 9386e4a1ee..cf1d45b4e5 100644 --- a/src/collections/hive_array.zig +++ b/src/collections/hive_array.zig @@ -100,7 +100,7 @@ pub fn HiveArray(comptime T: type, comptime capacity: u16) type { } } - return self.allocator.create(T) catch bun.outOfMemory(); + return bun.handleOom(self.allocator.create(T)); } pub fn getAndSeeIfNew(self: *This, new: *bool) *T { @@ -111,7 +111,7 @@ pub fn HiveArray(comptime T: type, comptime capacity: u16) type { } } - return self.allocator.create(T) catch bun.outOfMemory(); + return bun.handleOom(self.allocator.create(T)); } pub fn tryGet(self: *This) OOM!*T { diff --git a/src/create/SourceFileProjectGenerator.zig b/src/create/SourceFileProjectGenerator.zig index e8f33a52bb..761204aa66 100644 --- a/src/create/SourceFileProjectGenerator.zig +++ b/src/create/SourceFileProjectGenerator.zig @@ -531,7 +531,7 @@ fn findReactComponentExport(bundler: *BundleV2) ?[]const u8 { } if (filename[0] >= 'a' and filename[0] <= 'z') { - const duped = default_allocator.dupe(u8, filename) catch bun.outOfMemory(); + const duped = bun.handleOom(default_allocator.dupe(u8, filename)); duped[0] = duped[0] - 32; if (bun.js_lexer.isIdentifier(duped)) { if (exports.contains(duped)) { diff --git a/src/css/context.zig b/src/css/context.zig index 1bb7a5906e..6bdc1bbdd1 100644 --- a/src/css/context.zig +++ b/src/css/context.zig @@ -72,7 +72,7 @@ pub const PropertyHandlerContext = struct { } pub fn addDarkRule(this: *@This(), allocator: Allocator, property: css.Property) void { - this.dark.append(allocator, property) catch bun.outOfMemory(); + bun.handleOom(this.dark.append(allocator, property)); } pub fn addLogicalRule(this: *@This(), allocator: Allocator, ltr: css.Property, rtl: css.Property) void { @@ -100,7 +100,7 @@ pub const PropertyHandlerContext = struct { var dest = ArrayList(css.CssRule(T)).initCapacity( this.allocator, this.supports.items.len, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); for (this.supports.items) |*entry| { dest.appendAssumeCapacity(css.CssRule(T){ @@ -108,7 +108,7 @@ pub const PropertyHandlerContext = struct { .condition = entry.condition.deepClone(this.allocator), .rules = css.CssRuleList(T){ .v = v: { - var v = ArrayList(css.CssRule(T)).initCapacity(this.allocator, 1) catch bun.outOfMemory(); + var v = bun.handleOom(ArrayList(css.CssRule(T)).initCapacity(this.allocator, 1)); v.appendAssumeCapacity(.{ .style = css.StyleRule(T){ .selectors = style_rule.selectors.deepClone(this.allocator), @@ -156,7 +156,7 @@ pub const PropertyHandlerContext = struct { var list = ArrayList(MediaQuery).initCapacity( this.allocator, 1, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); list.appendAssumeCapacity(MediaQuery{ .qualifier = null, @@ -188,13 +188,13 @@ pub const PropertyHandlerContext = struct { .rules = .{}, .loc = style_rule.loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); break :brk list; }, .loc = style_rule.loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } return dest; @@ -227,7 +227,7 @@ pub const PropertyHandlerContext = struct { .loc = sty.loc, }; - dest.append(this.allocator, .{ .style = rule }) catch bun.outOfMemory(); + bun.handleOom(dest.append(this.allocator, .{ .style = rule })); } pub fn reset(this: *@This()) void { @@ -262,23 +262,23 @@ pub const PropertyHandlerContext = struct { break :brk null; }) |entry| { if (this.is_important) { - entry.important_declarations.append(this.allocator, property) catch bun.outOfMemory(); + bun.handleOom(entry.important_declarations.append(this.allocator, property)); } else { - entry.declarations.append(this.allocator, property) catch bun.outOfMemory(); + bun.handleOom(entry.declarations.append(this.allocator, property)); } } else { var important_declarations = ArrayList(css.Property){}; var declarations = ArrayList(css.Property){}; if (this.is_important) { - important_declarations.append(this.allocator, property) catch bun.outOfMemory(); + bun.handleOom(important_declarations.append(this.allocator, property)); } else { - declarations.append(this.allocator, property) catch bun.outOfMemory(); + bun.handleOom(declarations.append(this.allocator, property)); } this.supports.append(this.allocator, SupportsEntry{ .condition = condition, .declarations = declarations, .important_declarations = important_declarations, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } } diff --git a/src/css/css_modules.zig b/src/css/css_modules.zig index 8758be25c1..953034ccf0 100644 --- a/src/css/css_modules.zig +++ b/src/css/css_modules.zig @@ -19,7 +19,7 @@ pub const CssModule = struct { ) CssModule { // TODO: this is BAAAAAAAAAAD we are going to remove it const hashes = hashes: { - var hashes = ArrayList([]const u8).initCapacity(allocator, sources.items.len) catch bun.outOfMemory(); + var hashes = bun.handleOom(ArrayList([]const u8).initCapacity(allocator, sources.items.len)); for (sources.items) |path| { var alloced = false; const source = source: { @@ -27,7 +27,7 @@ pub const CssModule = struct { if (project_root) |root| { if (bun.path.Platform.auto.isAbsolute(root)) { alloced = true; - break :source allocator.dupe(u8, bun.path.relative(root, path)) catch bun.outOfMemory(); + break :source bun.handleOom(allocator.dupe(u8, bun.path.relative(root, path))); } } break :source path; @@ -43,7 +43,7 @@ pub const CssModule = struct { break :hashes hashes; }; const exports_by_source_index = exports_by_source_index: { - var exports_by_source_index = ArrayList(CssModuleExports).initCapacity(allocator, sources.items.len) catch bun.outOfMemory(); + var exports_by_source_index = bun.handleOom(ArrayList(CssModuleExports).initCapacity(allocator, sources.items.len)); exports_by_source_index.appendNTimesAssumeCapacity(CssModuleExports{}, sources.items.len); break :exports_by_source_index exports_by_source_index; }; @@ -62,7 +62,7 @@ pub const CssModule = struct { } pub fn getReference(this: *CssModule, allocator: Allocator, name: []const u8, source_index: u32) void { - const gop = this.exports_by_source_index.items[source_index].getOrPut(allocator, name) catch bun.outOfMemory(); + const gop = bun.handleOom(this.exports_by_source_index.items[source_index].getOrPut(allocator, name)); if (gop.found_existing) { gop.value_ptr.is_referenced = true; } else { @@ -99,12 +99,12 @@ pub const CssModule = struct { }, } else { // Local export. Mark as used. - const gop = this.exports_by_source_index.items[source_index].getOrPut(allocator, name) catch bun.outOfMemory(); + const gop = bun.handleOom(this.exports_by_source_index.items[source_index].getOrPut(allocator, name)); if (gop.found_existing) { gop.value_ptr.is_referenced = true; } else { var res = ArrayList(u8){}; - res.appendSlice(allocator, "--") catch bun.outOfMemory(); + bun.handleOom(res.appendSlice(allocator, "--")); gop.value_ptr.* = CssModuleExport{ .name = this.config.pattern.writeToString( allocator, @@ -124,9 +124,9 @@ pub const CssModule = struct { this.references.put( allocator, - std.fmt.allocPrint(allocator, "--{s}", .{the_hash}) catch bun.outOfMemory(), + bun.handleOom(std.fmt.allocPrint(allocator, "--{s}", .{the_hash})), reference, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return the_hash; } @@ -153,7 +153,7 @@ pub const CssModule = struct { } pub fn addDashed(this: *CssModule, allocator: Allocator, local: []const u8, source_index: u32) void { - const gop = this.exports_by_source_index.items[source_index].getOrPut(allocator, local) catch bun.outOfMemory(); + const gop = bun.handleOom(this.exports_by_source_index.items[source_index].getOrPut(allocator, local)); if (!gop.found_existing) { gop.value_ptr.* = CssModuleExport{ // todo_stuff.depth @@ -171,7 +171,7 @@ pub const CssModule = struct { } pub fn addLocal(this: *CssModule, allocator: Allocator, exported: []const u8, local: []const u8, source_index: u32) void { - const gop = this.exports_by_source_index.items[source_index].getOrPut(allocator, exported) catch bun.outOfMemory(); + const gop = bun.handleOom(this.exports_by_source_index.items[source_index].getOrPut(allocator, exported)); if (!gop.found_existing) { gop.value_ptr.* = CssModuleExport{ // todo_stuff.depth @@ -265,10 +265,10 @@ pub const Pattern = struct { &closure, struct { pub fn writefn(self: *Closure, slice: []const u8, replace_dots: bool) void { - self.res.appendSlice(self.allocator, prefix) catch bun.outOfMemory(); + bun.handleOom(self.res.appendSlice(self.allocator, prefix)); if (replace_dots) { const start = self.res.items.len; - self.res.appendSlice(self.allocator, slice) catch bun.outOfMemory(); + bun.handleOom(self.res.appendSlice(self.allocator, slice)); const end = self.res.items.len; for (self.res.items[start..end]) |*c| { if (c.* == '.') { @@ -277,7 +277,7 @@ pub const Pattern = struct { } return; } - self.res.appendSlice(self.allocator, slice) catch bun.outOfMemory(); + bun.handleOom(self.res.appendSlice(self.allocator, slice)); } }.writefn, ); @@ -304,7 +304,7 @@ pub const Pattern = struct { pub fn writefn(self: *Closure, slice: []const u8, replace_dots: bool) void { if (replace_dots) { const start = self.res.items.len; - self.res.appendSlice(self.allocator, slice) catch bun.outOfMemory(); + bun.handleOom(self.res.appendSlice(self.allocator, slice)); const end = self.res.items.len; for (self.res.items[start..end]) |*c| { if (c.* == '.') { @@ -313,7 +313,7 @@ pub const Pattern = struct { } return; } - self.res.appendSlice(self.allocator, slice) catch bun.outOfMemory(); + bun.handleOom(self.res.appendSlice(self.allocator, slice)); return; } }.writefn, @@ -398,7 +398,7 @@ pub fn hash(allocator: Allocator, comptime fmt: []const u8, args: anytype, at_st var stack_fallback = std.heap.stackFallback(128, allocator); const fmt_alloc = if (count <= 128) stack_fallback.get() else allocator; var hasher = bun.Wyhash11.init(0); - var fmt_str = std.fmt.allocPrint(fmt_alloc, fmt, args) catch bun.outOfMemory(); + var fmt_str = bun.handleOom(std.fmt.allocPrint(fmt_alloc, fmt, args)); hasher.update(fmt_str); const h: u32 = @truncate(hasher.final()); @@ -408,7 +408,7 @@ pub fn hash(allocator: Allocator, comptime fmt: []const u8, args: anytype, at_st const encode_len = bun.base64.simdutfEncodeLenUrlSafe(h_bytes[0..].len); var slice_to_write = if (encode_len <= 128 - @as(usize, @intFromBool(at_start))) - allocator.alloc(u8, encode_len + @as(usize, @intFromBool(at_start))) catch bun.outOfMemory() + bun.handleOom(allocator.alloc(u8, encode_len + @as(usize, @intFromBool(at_start)))) else fmt_str[0..]; diff --git a/src/css/css_parser.zig b/src/css/css_parser.zig index 38bcbc3916..6e09de4202 100644 --- a/src/css/css_parser.zig +++ b/src/css/css_parser.zig @@ -1423,13 +1423,13 @@ pub const BundlerAtRuleParser = struct { .loc = bun.logger.Loc{ .start = @intCast(start_position) }, .len = @intCast(end_position - start_position), }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } pub fn onLayerRule(this: *This, layers: *const bun.css.SmallList(LayerName, 1)) void { if (this.anon_layer_count > 0) return; - this.layer_names.ensureUnusedCapacity(this.allocator, layers.len()) catch bun.outOfMemory(); + bun.handleOom(this.layer_names.ensureUnusedCapacity(this.allocator, layers.len())); for (layers.slice()) |*layer| { if (this.enclosing_layer.v.len() > 0) { @@ -1439,9 +1439,9 @@ pub const BundlerAtRuleParser = struct { cloned.v.ensureTotalCapacity(this.allocator, this.enclosing_layer.v.len() + layer.v.len()); cloned.v.appendSliceAssumeCapacity(this.enclosing_layer.v.slice()); cloned.v.appendSliceAssumeCapacity(layer.v.slice()); - this.layer_names.push(this.allocator, cloned) catch bun.outOfMemory(); + bun.handleOom(this.layer_names.push(this.allocator, cloned)); } else { - this.layer_names.push(this.allocator, layer.deepClone(this.allocator)) catch bun.outOfMemory(); + bun.handleOom(this.layer_names.push(this.allocator, layer.deepClone(this.allocator))); } } } @@ -1828,7 +1828,7 @@ pub fn TopLevelRuleParser(comptime AtRuleParserT: type) type { AtRuleParserT.CustomAtRuleParser.onImportRule(this.at_rule_parser, &import_rule, @intCast(start.position), @intCast(start.position + 1)); this.rules.v.append(this.allocator, .{ .import = import_rule, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .namespace => { @@ -1843,7 +1843,7 @@ pub fn TopLevelRuleParser(comptime AtRuleParserT: type) type { .url = url, .loc = loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, @@ -1860,7 +1860,7 @@ pub fn TopLevelRuleParser(comptime AtRuleParserT: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .layer => { @@ -1882,7 +1882,7 @@ pub fn TopLevelRuleParser(comptime AtRuleParserT: type) type { .prelude = prelude2, .block = null, .loc = loc, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); return .success; }, .custom => { @@ -2213,7 +2213,7 @@ pub fn NestedRuleParser(comptime T: type) type { properties.append( input.allocator(), decl, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -2225,7 +2225,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .font_palette_values => { @@ -2237,7 +2237,7 @@ pub fn NestedRuleParser(comptime T: type) type { this.rules.v.append( input.allocator(), .{ .font_palette_values = rule }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .counter_style => { @@ -2254,7 +2254,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .media => { @@ -2272,7 +2272,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .supports => { @@ -2287,7 +2287,7 @@ pub fn NestedRuleParser(comptime T: type) type { .rules = rules, .loc = loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .container => { @@ -2305,7 +2305,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .scope => { @@ -2323,7 +2323,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .viewport => { @@ -2336,7 +2336,7 @@ pub fn NestedRuleParser(comptime T: type) type { }, .loc = loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .keyframes => { @@ -2350,7 +2350,7 @@ pub fn NestedRuleParser(comptime T: type) type { keyframes.append( input.allocator(), keyframe, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -2361,7 +2361,7 @@ pub fn NestedRuleParser(comptime T: type) type { .vendor_prefix = prelude.keyframes.prefix, .loc = loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .page => { @@ -2373,7 +2373,7 @@ pub fn NestedRuleParser(comptime T: type) type { this.rules.v.append( input.allocator(), .{ .page = rule }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .moz_document => { @@ -2386,7 +2386,7 @@ pub fn NestedRuleParser(comptime T: type) type { .rules = rules, .loc = loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .layer => { @@ -2414,7 +2414,7 @@ pub fn NestedRuleParser(comptime T: type) type { this.rules.v.append(input.allocator(), .{ .layer_block = css_rules.layer.LayerBlockRule(T.CustomAtRuleParser.AtRule){ .name = name, .rules = rules, .loc = loc }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .property => { @@ -2424,7 +2424,7 @@ pub fn NestedRuleParser(comptime T: type) type { .err => |e| return .{ .err = e }, .result => |v| v, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, .import, .namespace, .custom_media, .charset => { @@ -2444,7 +2444,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .nest => { @@ -2469,7 +2469,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .font_feature_values => bun.unreachablePanic("", .{}), @@ -2487,7 +2487,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .custom => { @@ -2499,7 +2499,7 @@ pub fn NestedRuleParser(comptime T: type) type { .result => |v| v, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, } @@ -2523,7 +2523,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .unknown => { @@ -2537,7 +2537,7 @@ pub fn NestedRuleParser(comptime T: type) type { .loc = loc, }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return .success; }, .custom => { @@ -2551,7 +2551,7 @@ pub fn NestedRuleParser(comptime T: type) type { )) { .err => |e| return .{ .err = e }, .result => |v| v, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; }, else => return .{ .err = {} }, @@ -2631,7 +2631,7 @@ pub fn NestedRuleParser(comptime T: type) type { const custom_properties_slice = custom_properties.slice(); for (this.composes_refs.slice()) |ref| { - const entry = this.local_properties.getOrPut(this.allocator, ref) catch bun.outOfMemory(); + const entry = bun.handleOom(this.local_properties.getOrPut(this.allocator, ref)); const property_usage: *PropertyUsage = if (!entry.found_existing) brk: { entry.value_ptr.* = PropertyUsage{ .range = bun.logger.Range{ .loc = bun.logger.Loc{ .start = @intCast(location) }, .len = @intCast(len) } }; break :brk entry.value_ptr; @@ -2648,7 +2648,7 @@ pub fn NestedRuleParser(comptime T: type) type { .rules = rules, .loc = loc, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; } @@ -2684,11 +2684,11 @@ pub fn NestedRuleParser(comptime T: type) type { /// for the bundler so we can generate the lazy JS import object later. pub fn recordComposes(this: *This, allocator: Allocator, composes: *Composes) void { for (this.composes_refs.slice()) |ref| { - const entry = this.composes.getOrPut(allocator, ref) catch bun.outOfMemory(); + const entry = bun.handleOom(this.composes.getOrPut(allocator, ref)); if (!entry.found_existing) { entry.value_ptr.* = ComposesEntry{}; } - entry.value_ptr.*.composes.push(allocator, composes.deepClone(allocator)) catch bun.outOfMemory(); + bun.handleOom(entry.value_ptr.*.composes.push(allocator, composes.deepClone(allocator))); } } @@ -2727,7 +2727,7 @@ pub fn NestedRuleParser(comptime T: type) type { errors.append( this.allocator, e, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { if (iter.parser.options.error_recovery) { iter.parser.options.warn(e); @@ -3017,7 +3017,7 @@ pub fn fillPropertyBitSet(allocator: Allocator, bitset: *PropertyBitset, block: for (block.declarations.items) |*prop| { const tag = switch (prop.*) { .custom => { - custom_properties.push(allocator, prop.custom.name.asStr()) catch bun.outOfMemory(); + bun.handleOom(custom_properties.push(allocator, prop.custom.name.asStr())); continue; }, .unparsed => |u| @as(PropertyIdTag, u.property_id), @@ -3030,7 +3030,7 @@ pub fn fillPropertyBitSet(allocator: Allocator, bitset: *PropertyBitset, block: for (block.important_declarations.items) |*prop| { const tag = switch (prop.*) { .custom => { - custom_properties.push(allocator, prop.custom.name.asStr()) catch bun.outOfMemory(); + bun.handleOom(custom_properties.push(allocator, prop.custom.name.asStr())); continue; }, .unparsed => |u| @as(PropertyIdTag, u.property_id), @@ -3100,7 +3100,7 @@ pub fn StyleSheet(comptime AtRule: type) type { for (this.rules.v.items) |*rule| { if (rule.* == .custom_media) { - custom_media.put(allocator, rule.custom_media.name.v, rule.custom_media.deepClone(allocator)) catch bun.outOfMemory(); + bun.handleOom(custom_media.put(allocator, rule.custom_media.name.v, rule.custom_media.deepClone(allocator))); } } @@ -3285,7 +3285,7 @@ pub fn StyleSheet(comptime AtRule: type) type { .whitespace => {}, .comment => |comment| { if (bun.strings.startsWithChar(comment, '!')) { - license_comments.append(allocator, comment) catch bun.outOfMemory(); + bun.handleOom(license_comments.append(allocator, comment)); } }, else => break, @@ -3311,9 +3311,9 @@ pub fn StyleSheet(comptime AtRule: type) type { } var sources = ArrayList([]const u8){}; - sources.append(allocator, options.filename) catch bun.outOfMemory(); + bun.handleOom(sources.append(allocator, options.filename)); var source_map_urls = ArrayList(?[]const u8){}; - source_map_urls.append(allocator, parser.currentSourceMapUrl()) catch bun.outOfMemory(); + bun.handleOom(source_map_urls.append(allocator, parser.currentSourceMapUrl())); return .{ .result = .{ @@ -3410,7 +3410,7 @@ pub fn StyleSheet(comptime AtRule: type) type { var count: u32 = 0; inline for (STATES[0..]) |state| { if (comptime state == .exec) { - out.v.ensureUnusedCapacity(allocator, count) catch bun.outOfMemory(); + bun.handleOom(out.v.ensureUnusedCapacity(allocator, count)); } var saw_imports = false; for (this.rules.v.items) |*rule| { @@ -3430,7 +3430,7 @@ pub fn StyleSheet(comptime AtRule: type) type { .path = bun.fs.Path.init(import_rule.url), .kind = if (import_rule.supports != null) .at_conditional else .at, .range = bun.logger.Range.None, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); rule.* = .ignored; }, } @@ -3469,7 +3469,7 @@ pub const StyleAttribute = struct { &parser_extra, ); const sources = sources: { - var s = ArrayList([]const u8).initCapacity(allocator, 1) catch bun.outOfMemory(); + var s = bun.handleOom(ArrayList([]const u8).initCapacity(allocator, 1)); s.appendAssumeCapacity(options.filename); break :sources s; }; @@ -3790,7 +3790,7 @@ const ParseUntilErrorBehavior = enum { // return switch (this.*) { // .list => |list| { // const len = list.len; -// list.push(allocator, record) catch bun.outOfMemory(); +// bun.handleOom(list.push(allocator, record)); // return len; // }, // // .dummy => |*d| { @@ -3826,7 +3826,7 @@ pub const Parser = struct { const extra = this.extra.?; - const entry = extra.local_scope.getOrPut(this.allocator(), name) catch bun.outOfMemory(); + const entry = bun.handleOom(extra.local_scope.getOrPut(this.allocator(), name)); if (!entry.found_existing) { entry.value_ptr.* = LocalEntry{ .ref = CssRef{ @@ -3838,7 +3838,7 @@ pub const Parser = struct { extra.symbols.push(this.allocator(), bun.ast.Symbol{ .kind = .local_css, .original_name = name, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } else { const prev_tag = entry.value_ptr.ref.tag; if (!prev_tag.class and tag.class) { @@ -3861,7 +3861,7 @@ pub const Parser = struct { .loc = bun.logger.Loc{ .start = @intCast(start_position) }, .len = @intCast(url.len), // TODO: technically this is not correct because the url could be escaped }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .{ .result = idx }; } else { return .{ .err = this.newBasicUnexpectedTokenError(.{ .unquoted_url = url }) }; @@ -3992,7 +3992,7 @@ pub const Parser = struct { .err => { // need to clone off the stack const needs_clone = values.items.len == 1; - if (needs_clone) return .{ .result = values.clone(this.allocator()) catch bun.outOfMemory() }; + if (needs_clone) return .{ .result = bun.handleOom(values.clone(this.allocator())) }; return .{ .result = values }; }, }; @@ -6451,13 +6451,13 @@ const CopyOnWriteStr = union(enum) { pub fn append(this: *@This(), allocator: Allocator, slice: []const u8) void { switch (this.*) { .borrowed => { - var list = std.ArrayList(u8).initCapacity(allocator, this.borrowed.len + slice.len) catch bun.outOfMemory(); + var list = bun.handleOom(std.ArrayList(u8).initCapacity(allocator, this.borrowed.len + slice.len)); list.appendSliceAssumeCapacity(this.borrowed); list.appendSliceAssumeCapacity(slice); this.* = .{ .owned = list }; }, .owned => { - this.owned.appendSlice(slice) catch bun.outOfMemory(); + bun.handleOom(this.owned.appendSlice(slice)); }, } } @@ -7108,7 +7108,7 @@ pub inline fn copysign(self: f32, sign: f32) f32 { } pub fn deepClone(comptime V: type, allocator: Allocator, list: *const ArrayList(V)) ArrayList(V) { - var newlist = ArrayList(V).initCapacity(allocator, list.items.len) catch bun.outOfMemory(); + var newlist = bun.handleOom(ArrayList(V).initCapacity(allocator, list.items.len)); for (list.items) |*item| { newlist.appendAssumeCapacity(generic.deepClone(V, item, allocator)); diff --git a/src/css/declaration.zig b/src/css/declaration.zig index 440e834dbf..86a7d86b25 100644 --- a/src/css/declaration.zig +++ b/src/css/declaration.zig @@ -168,7 +168,7 @@ pub const DeclarationBlock = struct { const handled = hndlr.handleProperty(prop, ctx); if (!handled) { - hndlr.decls.append(ctx.allocator, prop.*) catch bun.outOfMemory(); + bun.handleOom(hndlr.decls.append(ctx.allocator, prop.*)); // replacing with a property which does not require allocation // to "delete" prop.* = css.Property{ .all = .@"revert-layer" }; @@ -359,20 +359,20 @@ pub fn parse_declaration_impl( bun.logger.Data, &[_]bun.logger.Data{ bun.logger.Data{ - .text = options.allocator.dupe(u8, "The parent selector is not a single class selector because of the syntax here:") catch bun.outOfMemory(), + .text = bun.handleOom(options.allocator.dupe(u8, "The parent selector is not a single class selector because of the syntax here:")), .location = info.toLoggerLocation(options.filename), }, }, - ) catch bun.outOfMemory(), + ) catch |err| bun.handleOom(err), ); }, } } } if (important) { - important_declarations.append(input.allocator(), property) catch bun.outOfMemory(); + bun.handleOom(important_declarations.append(input.allocator(), property)); } else { - declarations.append(input.allocator(), property) catch bun.outOfMemory(); + bun.handleOom(declarations.append(input.allocator(), property)); } return .success; @@ -402,11 +402,11 @@ pub const DeclarationHandler = struct { _ = allocator; // autofix if (this.direction) |direction| { this.direction = null; - this.decls.append(context.allocator, css.Property{ .direction = direction }) catch bun.outOfMemory(); + bun.handleOom(this.decls.append(context.allocator, css.Property{ .direction = direction })); } // if (this.unicode_bidi) |unicode_bidi| { // this.unicode_bidi = null; - // this.decls.append(context.allocator, css.Property{ .unicode_bidi = unicode_bidi }) catch bun.outOfMemory(); + // this.decls.append(context.allocator, css.Property{ .unicode_bidi = unicode_bidi }) catch |err| bun.handleOom(err); // } this.background.finalize(&this.decls, context); diff --git a/src/css/generics.zig b/src/css/generics.zig index 30428d73ce..43503b3469 100644 --- a/src/css/generics.zig +++ b/src/css/generics.zig @@ -446,7 +446,7 @@ pub inline fn deepClone(comptime T: type, this: *const T, allocator: Allocator) return bun.create(allocator, TT, deepClone(TT, this.*, allocator)); } if (comptime tyinfo.pointer.size == .slice) { - var slc = allocator.alloc(tyinfo.pointer.child, this.len) catch bun.outOfMemory(); + var slc = bun.handleOom(allocator.alloc(tyinfo.pointer.child, this.len)); if (comptime bun.meta.isSimpleCopyType(tyinfo.pointer.child) or tyinfo.pointer.child == []const u8) { @memcpy(slc, this.*); } else { diff --git a/src/css/media_query.zig b/src/css/media_query.zig index ac06827393..056ba90920 100644 --- a/src/css/media_query.zig +++ b/src/css/media_query.zig @@ -47,7 +47,7 @@ pub const MediaList = struct { return .{ .err = e }; }, }; - media_queries.append(input.allocator(), mq) catch bun.outOfMemory(); + bun.handleOom(media_queries.append(input.allocator(), mq)); if (input.next().asValue()) |tok| { if (tok.* != .comma) { @@ -1491,7 +1491,7 @@ pub fn MediaFeatureName(comptime FeatureId: type) type { const final_name = if (is_webkit) name: { // PERF: stack buffer here? free_str = true; - break :name std.fmt.allocPrint(input.allocator(), "-webkit-{s}", .{name}) catch bun.outOfMemory(); + break :name bun.handleOom(std.fmt.allocPrint(input.allocator(), "-webkit-{s}", .{name})); } else name; defer if (is_webkit) { diff --git a/src/css/printer.zig b/src/css/printer.zig index 88270143f3..44f643f9d9 100644 --- a/src/css/printer.zig +++ b/src/css/printer.zig @@ -352,13 +352,13 @@ pub fn Printer(comptime Writer: type) type { pub fn writeFmt(this: *This, comptime fmt: []const u8, args: anytype) PrintErr!void { // assuming the writer comes from an ArrayList const start: usize = getWrittenAmt(this.dest); - this.dest.print(fmt, args) catch bun.outOfMemory(); + bun.handleOom(this.dest.print(fmt, args)); const written = getWrittenAmt(this.dest) - start; this.col += @intCast(written); } fn replaceDots(allocator: Allocator, s: []const u8) []const u8 { - var str = allocator.dupe(u8, s) catch bun.outOfMemory(); + var str = bun.handleOom(allocator.dupe(u8, s)); std.mem.replaceScalar(u8, str[0..], '.', '-'); return str; } diff --git a/src/css/properties/align.zig b/src/css/properties/align.zig index 5b8ea5fac2..07de47a604 100644 --- a/src/css/properties/align.zig +++ b/src/css/properties/align.zig @@ -1190,7 +1190,7 @@ pub const AlignHandler = struct { .unparsed => |*val| { if (isAlignProperty(val.property_id)) { this.flush(dest, context); - dest.append(context.allocator, property.*) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, property.*)); } else { return false; } @@ -1271,14 +1271,14 @@ pub const AlignHandler = struct { dest.append(context.allocator, Property{ .gap = Gap{ .row = row_gap.?, .column = column_gap.?, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); } else { if (row_gap != null) { - dest.append(context.allocator, Property{ .@"row-gap" = row_gap.? }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"row-gap" = row_gap.? })); } if (column_gap != null) { - dest.append(context.allocator, Property{ .@"column-gap" = column_gap.? }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"column-gap" = column_gap.? })); } } } @@ -1321,7 +1321,7 @@ pub const AlignHandler = struct { var prefix = v[1]; // If we have an unprefixed property, override necessary prefixes. prefix = if (prefix.none) flushPrefixesHelper(this, context, feature) else prefix; - dest.append(context.allocator, @unionInit(Property, prop, .{ val, prefix })) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, @unionInit(Property, prop, .{ val, prefix }))); } } @@ -1362,7 +1362,7 @@ pub const AlignHandler = struct { dest.append(context.allocator, @unionInit(Property, p2009[1], .{ a, prefixes_2009, - })) catch bun.outOfMemory(); + })) catch |err| bun.handleOom(err); } } } @@ -1381,7 +1381,7 @@ pub const AlignHandler = struct { dest.append(context.allocator, @unionInit(Property, p2012[1], .{ q, VendorPrefix.MS, - })) catch bun.outOfMemory(); + })) catch |err| bun.handleOom(err); } } } @@ -1397,7 +1397,7 @@ pub const AlignHandler = struct { if (key) |v| { const val = v[0]; const prefix = v[1]; - dest.append(context.allocator, @unionInit(Property, prop, .{ val, prefix })) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, @unionInit(Property, prop, .{ val, prefix }))); } } @@ -1405,7 +1405,7 @@ pub const AlignHandler = struct { _ = this; // autofix if (key) |v| { const val = v; - dest.append(context.allocator, @unionInit(Property, prop, val)) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, @unionInit(Property, prop, val))); } } @@ -1442,7 +1442,7 @@ pub const AlignHandler = struct { dest.append( context.allocator, @unionInit(Property, align_prop.prop, .{ css.generic.deepClone(@TypeOf(@"align".*), @"align", context.allocator), align_prefix.* }), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (comptime justify_prop != null) { @@ -1455,7 +1455,7 @@ pub const AlignHandler = struct { dest.append( context.allocator, @unionInit(Property, justify_prop.?.prop, .{ css.generic.deepClone(@TypeOf(justify_actual.*), justify_actual, context.allocator), justify_prefix.* }), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } // Add shorthand. @@ -1465,7 +1465,7 @@ pub const AlignHandler = struct { .@"align" = css.generic.deepClone(@TypeOf(@"align".*), @"align", context.allocator), .justify = css.generic.deepClone(@TypeOf(justify_actual.*), justify_actual, context.allocator), }), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { // Add shorthand. @@ -1475,7 +1475,7 @@ pub const AlignHandler = struct { .@"align" = css.generic.deepClone(@TypeOf(@"align".*), @"align", context.allocator), .justify = css.generic.deepClone(@TypeOf(justify.*), justify, context.allocator), }), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } align_val.* = null; diff --git a/src/css/properties/background.zig b/src/css/properties/background.zig index 087ae231af..3aa656ae2c 100644 --- a/src/css/properties/background.zig +++ b/src/css/properties/background.zig @@ -734,7 +734,7 @@ pub const BackgroundHandler = struct { bun.bits.insert(BackgroundProperty, &this.flushed_properties, prop); } - dest.append(allocator, Property{ .unparsed = unparsed }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .unparsed = unparsed })); } else return false; }, else => return false, @@ -784,7 +784,7 @@ pub const BackgroundHandler = struct { } }.predicate); if (this.has_prefix) { - this.decls.append(allocator, property.deepClone(allocator)) catch bun.outOfMemory(); + bun.handleOom(this.decls.append(allocator, property.deepClone(allocator))); } else if (context.targets.browsers != null) { this.decls.clearRetainingCapacity(); } @@ -812,7 +812,7 @@ pub const BackgroundHandler = struct { this.has_any = false; const push = struct { fn push(self: *BackgroundHandler, alloc: Allocator, d: *css.DeclarationList, comptime property_field_name: []const u8, val: anytype) void { - d.append(alloc, @unionInit(Property, property_field_name, val)) catch bun.outOfMemory(); + bun.handleOom(d.append(alloc, @unionInit(Property, property_field_name, val))); const prop = @field(BackgroundProperty, property_field_name); bun.bits.insert(BackgroundProperty, &self.flushed_properties, prop); } @@ -919,7 +919,7 @@ pub const BackgroundHandler = struct { push(this, allocator, dest, "background", backgrounds); if (clip_property) |clip| { - dest.append(allocator, clip) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, clip)); this.flushed_properties.clip = true; } @@ -994,7 +994,7 @@ pub const BackgroundHandler = struct { Property{ .@"background-clip" = .{ clips.deepClone(allocator), prefixes }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); this.flushed_properties.clip = true; } @@ -1033,7 +1033,7 @@ pub const BackgroundHandler = struct { } } - dest.appendSlice(allocator, this.decls.items) catch bun.outOfMemory(); + bun.handleOom(dest.appendSlice(allocator, this.decls.items)); this.decls.clearRetainingCapacity(); this.flush(allocator, dest, context); diff --git a/src/css/properties/border.zig b/src/css/properties/border.zig index b1f2b3c142..37efde9cad 100644 --- a/src/css/properties/border.zig +++ b/src/css/properties/border.zig @@ -862,7 +862,7 @@ pub const BorderHandler = struct { inline fn push(f: *FlushContext, comptime p: []const u8, val: anytype) void { bun.bits.insert(BorderProperty, &f.self.flushed_properties, @field(BorderProperty, p)); - f.dest.append(f.ctx.allocator, @unionInit(css.Property, p, val.deepClone(f.ctx.allocator))) catch bun.outOfMemory(); + bun.handleOom(f.dest.append(f.ctx.allocator, @unionInit(css.Property, p, val.deepClone(f.ctx.allocator)))); } inline fn fallbacks(f: *FlushContext, comptime p: []const u8, _val: anytype) void { @@ -870,7 +870,7 @@ pub const BorderHandler = struct { if (!bun.bits.contains(BorderProperty, f.self.flushed_properties, @field(BorderProperty, p))) { const fbs = val.getFallbacks(f.ctx.allocator, f.ctx.targets); for (css.generic.slice(@TypeOf(fbs), &fbs)) |fallback| { - f.dest.append(f.ctx.allocator, @unionInit(css.Property, p, fallback)) catch bun.outOfMemory(); + bun.handleOom(f.dest.append(f.ctx.allocator, @unionInit(css.Property, p, fallback))); } } push(f, p, val); @@ -1407,7 +1407,7 @@ pub const BorderHandler = struct { var up = unparsed.deepClone(context.allocator); context.addUnparsedFallbacks(&up); bun.bits.insert(BorderProperty, &this.flushed_properties, BorderProperty.tryFromPropertyId(up.property_id).?); - dest.append(context.allocator, .{ .unparsed = up }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .unparsed = up })); return; } @@ -1466,7 +1466,7 @@ pub const BorderHandler = struct { var up = unparsed.deepClone(context.allocator); context.addUnparsedFallbacks(&up); bun.bits.insert(BorderProperty, &this.flushed_properties, BorderProperty.tryFromPropertyId(up.property_id).?); - dest.append(context.allocator, .{ .unparsed = up }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .unparsed = up })); }, } } diff --git a/src/css/properties/border_image.zig b/src/css/properties/border_image.zig index d739b0957c..df07f82125 100644 --- a/src/css/properties/border_image.zig +++ b/src/css/properties/border_image.zig @@ -503,7 +503,7 @@ pub const BorderImageHandler = struct { context.addUnparsedFallbacks(&unparsed_clone); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.tryFromPropertyId(unparsed_clone.property_id).?); - dest.append(allocator, Property{ .unparsed = unparsed_clone }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .unparsed = unparsed_clone })); } else return false; }, else => return false, @@ -577,7 +577,7 @@ pub const BorderImageHandler = struct { if (p.isEmpty()) { p = prefix; } - dest.append(allocator, css.Property{ .@"border-image" = .{ fallback, p } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, css.Property{ .@"border-image" = .{ fallback, p } })); } } } @@ -587,37 +587,37 @@ pub const BorderImageHandler = struct { prefix = p; } - dest.append(allocator, Property{ .@"border-image" = .{ border_image, prefix } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image" = .{ border_image, prefix } })); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.@"border-image"); } else { if (source) |*mut_source| { if (!bun.bits.contains(BorderImageProperty, this.flushed_properties, BorderImageProperty.@"border-image-source")) { for (mut_source.getFallbacks(allocator, context.targets).slice()) |fallback| { - dest.append(allocator, Property{ .@"border-image-source" = fallback }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image-source" = fallback })); } } - dest.append(allocator, Property{ .@"border-image-source" = mut_source.* }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image-source" = mut_source.* })); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.@"border-image-source"); } if (slice) |s| { - dest.append(allocator, Property{ .@"border-image-slice" = s }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image-slice" = s })); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.@"border-image-slice"); } if (width) |w| { - dest.append(allocator, Property{ .@"border-image-width" = w }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image-width" = w })); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.@"border-image-width"); } if (outset) |o| { - dest.append(allocator, Property{ .@"border-image-outset" = o }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image-outset" = o })); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.@"border-image-outset"); } if (repeat) |r| { - dest.append(allocator, Property{ .@"border-image-repeat" = r }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .@"border-image-repeat" = r })); bun.bits.insert(BorderImageProperty, &this.flushed_properties, BorderImageProperty.@"border-image-repeat"); } } diff --git a/src/css/properties/border_radius.zig b/src/css/properties/border_radius.zig index 41abb979a7..f3dcc51ee3 100644 --- a/src/css/properties/border_radius.zig +++ b/src/css/properties/border_radius.zig @@ -144,7 +144,7 @@ pub const BorderRadiusHandler = struct { .@"border-end-start-radius" => logicalPropertyHelper(this, dest, context, "end_start", property), else => { this.flush(dest, context); - dest.append(context.allocator, Property{ .unparsed = unparsed.getPrefixed(context.allocator, context.targets, css.prefixes.Feature.border_radius) }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .unparsed = unparsed.getPrefixed(context.allocator, context.targets, css.prefixes.Feature.border_radius) })); }, } } else return false; @@ -185,7 +185,7 @@ pub const BorderRadiusHandler = struct { .bottom_left = bottom_left.?[0].deepClone(context.allocator), }, prefix, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); bun.bits.remove(VendorPrefix, &top_left.?[1], intersection); bun.bits.remove(VendorPrefix, &top_right.?[1], intersection); bun.bits.remove(VendorPrefix, &bottom_right.?[1], intersection); @@ -210,7 +210,7 @@ pub const BorderRadiusHandler = struct { if (val) |v| { if (!v[1].isEmpty()) { const prefix = ctx.targets.prefixes(v[1], css.prefixes.Feature.border_radius); - d.append(ctx.allocator, @unionInit(css.Property, prop, .{ v[0], prefix })) catch bun.outOfMemory(); + bun.handleOom(d.append(ctx.allocator, @unionInit(css.Property, prop, .{ v[0], prefix }))); } } } @@ -218,7 +218,7 @@ pub const BorderRadiusHandler = struct { fn logicalProperty(d: *css.DeclarationList, ctx: *css.PropertyHandlerContext, val: ?css.Property, comptime ltr: []const u8, comptime rtl: []const u8, logical_supported: bool) void { if (val) |v| { if (logical_supported) { - d.append(ctx.allocator, v) catch bun.outOfMemory(); + bun.handleOom(d.append(ctx.allocator, v)); } else { const prefix = ctx.targets.prefixes(css.VendorPrefix{}, css.prefixes.Feature.border_radius); switch (v) { diff --git a/src/css/properties/box_shadow.zig b/src/css/properties/box_shadow.zig index ac9da490ea..260af58198 100644 --- a/src/css/properties/box_shadow.zig +++ b/src/css/properties/box_shadow.zig @@ -165,7 +165,7 @@ pub const BoxShadowHandler = struct { var unparsed = unp.deepClone(context.allocator); context.addUnparsedFallbacks(&unparsed); - dest.append(context.allocator, .{ .unparsed = unparsed }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .unparsed = unparsed })); this.flushed = true; } else return false; }, @@ -208,7 +208,7 @@ pub const BoxShadowHandler = struct { } } - dest.append(context.allocator, .{ .@"box-shadow" = .{ rgb, prefixes } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .@"box-shadow" = .{ rgb, prefixes } })); if (prefixes.none) { prefixes = VendorPrefix.NONE; } else { @@ -228,7 +228,7 @@ pub const BoxShadowHandler = struct { @field(output, field.name) = css.generic.deepClone(field.type, &@field(input, field.name), context.allocator); } } - dest.append(context.allocator, .{ .@"box-shadow" = .{ p3, VendorPrefix.NONE } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .@"box-shadow" = .{ p3, VendorPrefix.NONE } })); } if (fallbacks.lab) { @@ -242,12 +242,12 @@ pub const BoxShadowHandler = struct { @field(output, field.name) = css.generic.deepClone(field.type, &@field(input, field.name), context.allocator); } } - dest.append(context.allocator, .{ .@"box-shadow" = .{ lab, VendorPrefix.NONE } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .@"box-shadow" = .{ lab, VendorPrefix.NONE } })); } else { - dest.append(context.allocator, .{ .@"box-shadow" = .{ box_shadows, prefixes } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .@"box-shadow" = .{ box_shadows, prefixes } })); } } else { - dest.append(context.allocator, .{ .@"box-shadow" = .{ box_shadows, prefixes2 } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, .{ .@"box-shadow" = .{ box_shadows, prefixes2 } })); } this.flushed = true; diff --git a/src/css/properties/custom.zig b/src/css/properties/custom.zig index 19e8f446f4..8e9f5eb12e 100644 --- a/src/css/properties/custom.zig +++ b/src/css/properties/custom.zig @@ -596,7 +596,7 @@ pub const TokenList = struct { pub fn getFallback(this: *const TokenList, allocator: Allocator, kind: ColorFallbackKind) @This() { var tokens = TokenList{}; - tokens.v.ensureTotalCapacity(allocator, this.v.items.len) catch bun.outOfMemory(); + bun.handleOom(tokens.v.ensureTotalCapacity(allocator, this.v.items.len)); tokens.v.items.len = this.v.items.len; for (this.v.items, tokens.v.items[0..this.v.items.len]) |*old, *new| { new.* = switch (old.*) { @@ -990,10 +990,10 @@ pub const UnresolvedColor = union(enum) { } pub fn lightDarkOwned(allocator: Allocator, light: UnresolvedColor, dark: UnresolvedColor) UnresolvedColor { - var lightlist = ArrayList(TokenOrValue).initCapacity(allocator, 1) catch bun.outOfMemory(); - lightlist.append(allocator, TokenOrValue{ .unresolved_color = light }) catch bun.outOfMemory(); - var darklist = ArrayList(TokenOrValue).initCapacity(allocator, 1) catch bun.outOfMemory(); - darklist.append(allocator, TokenOrValue{ .unresolved_color = dark }) catch bun.outOfMemory(); + var lightlist = bun.handleOom(ArrayList(TokenOrValue).initCapacity(allocator, 1)); + bun.handleOom(lightlist.append(allocator, TokenOrValue{ .unresolved_color = light })); + var darklist = bun.handleOom(ArrayList(TokenOrValue).initCapacity(allocator, 1)); + bun.handleOom(darklist.append(allocator, TokenOrValue{ .unresolved_color = dark })); return UnresolvedColor{ .light_dark = .{ .light = css.TokenList{ .v = lightlist }, @@ -1166,7 +1166,7 @@ pub const EnvironmentVariable = struct { pub fn getFallback(this: *const EnvironmentVariable, allocator: Allocator, kind: ColorFallbackKind) @This() { return EnvironmentVariable{ .name = this.name, - .indices = this.indices.clone(allocator) catch bun.outOfMemory(), + .indices = bun.handleOom(this.indices.clone(allocator)), .fallback = if (this.fallback) |*fallback| fallback.getFallback(allocator, kind) else null, }; } @@ -1182,7 +1182,7 @@ pub const EnvironmentVariable = struct { pub fn deepClone(this: *const EnvironmentVariable, allocator: Allocator) EnvironmentVariable { return .{ .name = this.name, - .indices = this.indices.clone(allocator) catch bun.outOfMemory(), + .indices = bun.handleOom(this.indices.clone(allocator)), .fallback = if (this.fallback) |*fallback| fallback.deepClone(allocator) else null, }; } diff --git a/src/css/properties/flex.zig b/src/css/properties/flex.zig index 505afa708e..2ce4162739 100644 --- a/src/css/properties/flex.zig +++ b/src/css/properties/flex.zig @@ -751,8 +751,8 @@ pub const FlexHandler = struct { } if (!prefixes_2009.isEmpty()) { const orient, const newdir = dir.to2009(); - dest.append(context.allocator, Property{ .@"box-orient" = .{ orient, prefixes_2009 } }) catch bun.outOfMemory(); - dest.append(context.allocator, Property{ .@"box-direction" = .{ newdir, prefixes_2009 } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"box-orient" = .{ orient, prefixes_2009 } })); + bun.handleOom(dest.append(context.allocator, Property{ .@"box-direction" = .{ newdir, prefixes_2009 } })); } } } @@ -774,7 +774,7 @@ pub const FlexHandler = struct { .wrap = wrapinner.*, }, prefix, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); bun.bits.remove(css.VendorPrefix, dir_prefix, intersection); bun.bits.remove(css.VendorPrefix, wrap_prefix, intersection); } @@ -795,7 +795,7 @@ pub const FlexHandler = struct { prefixes_2009.moz = true; } if (!prefixes_2009.isEmpty()) { - dest.append(context.allocator, Property{ .@"box-flex" = .{ g, prefixes_2009 } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"box-flex" = .{ g, prefixes_2009 } })); } } } @@ -820,7 +820,7 @@ pub const FlexHandler = struct { .basis = b, }, prefix, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); bun.bits.remove(css.VendorPrefix, g_prefix, intersection); bun.bits.remove(css.VendorPrefix, s_prefix, intersection); bun.bits.remove(css.VendorPrefix, b_prefix, intersection); @@ -870,7 +870,7 @@ pub const FlexHandler = struct { dest.append(ctx.allocator, @unionInit(Property, p2009[1], .{ v, prefixes_2009, - })) catch bun.outOfMemory(); + })) catch |err| bun.handleOom(err); } } } @@ -883,7 +883,7 @@ pub const FlexHandler = struct { dest.append(ctx.allocator, @unionInit(Property, p2012, .{ val, css.VendorPrefix.MS, - })) catch bun.outOfMemory(); + })) catch |err| bun.handleOom(err); ms = false; } @@ -897,7 +897,7 @@ pub const FlexHandler = struct { dest.append(ctx.allocator, @unionInit(Property, prop, .{ val, prefix, - })) catch bun.outOfMemory(); + })) catch |err| bun.handleOom(err); } } } @@ -911,7 +911,7 @@ pub const FlexHandler = struct { dest.append(ctx.allocator, @unionInit(Property, field_name, .{ val, prefix, - })) catch bun.outOfMemory(); + })) catch |err| bun.handleOom(err); } else { // css.generic.eql(comptime T: type, lhs: *const T, rhs: *const T) // css.generic.deinit(@TypeOf(val), &val, ctx.allocator); diff --git a/src/css/properties/font.zig b/src/css/properties/font.zig index 3d11eedb65..4a2c496fb1 100644 --- a/src/css/properties/font.zig +++ b/src/css/properties/font.zig @@ -312,12 +312,12 @@ pub const FontFamily = union(enum) { while (input.tryParse(css.Parser.expectIdent, .{}).asValue()) |ident| { if (string == null) { string = ArrayList(u8){}; - string.?.appendSlice(stralloc, value) catch bun.outOfMemory(); + bun.handleOom(string.?.appendSlice(stralloc, value)); } if (string) |*s| { - s.append(stralloc, ' ') catch bun.outOfMemory(); - s.appendSlice(stralloc, ident) catch bun.outOfMemory(); + bun.handleOom(s.append(stralloc, ' ')); + bun.handleOom(s.appendSlice(stralloc, ident)); } } @@ -352,7 +352,7 @@ pub const FontFamily = union(enum) { if (first) { first = false; } else { - id.append(dest.allocator, ' ') catch bun.outOfMemory(); + bun.handleOom(id.append(dest.allocator, ' ')); } const dest_id = id.writer(dest.allocator); css.serializer.serializeIdentifier(slice, dest_id) catch return dest.addFmtError(); @@ -866,7 +866,7 @@ pub const FontHandler = struct { if (isFontProperty(val.property_id)) { this.flush(dest, context); bun.bits.insert(FontProperty, &this.flushed_properties, FontProperty.tryFromPropertyId(val.property_id).?); - dest.append(context.allocator, property.*) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, property.*)); } else { return false; } @@ -905,7 +905,7 @@ pub const FontHandler = struct { } fn push(self: *FontHandler, d: *css.DeclarationList, ctx: *css.PropertyHandlerContext, comptime prop: []const u8, val: anytype) void { - d.append(ctx.allocator, @unionInit(css.Property, prop, val)) catch bun.outOfMemory(); + bun.handleOom(d.append(ctx.allocator, @unionInit(css.Property, prop, val))); var insertion: FontProperty = .{}; if (comptime std.mem.eql(u8, prop, "font")) { insertion = FontProperty.FONT; @@ -944,7 +944,7 @@ pub const FontHandler = struct { var i: usize = 0; while (i < f.len) { - const gop = seen.getOrPut(alloc, f.at(i).*) catch bun.outOfMemory(); + const gop = bun.handleOom(seen.getOrPut(alloc, f.at(i).*)); if (gop.found_existing) { _ = f.orderedRemove(i); } else { @@ -1028,7 +1028,7 @@ inline fn compatibleFontFamily(allocator: std.mem.Allocator, _family: ?bun.BabyL for (families.sliceConst(), 0..) |v, i| { if (v.eql(&SYSTEM_UI)) { for (DEFAULT_SYSTEM_FONTS, 0..) |name, j| { - families.insert(allocator, i + j + 1, .{ .family_name = name }) catch bun.outOfMemory(); + bun.handleOom(families.insert(allocator, i + j + 1, .{ .family_name = name })); } break; } diff --git a/src/css/properties/grid.zig b/src/css/properties/grid.zig index 9b4baed437..db3c595619 100644 --- a/src/css/properties/grid.zig +++ b/src/css/properties/grid.zig @@ -39,14 +39,14 @@ pub const TrackList = struct { while (true) { const line_name = input.tryParse(parseLineNames, .{}).asValue() orelse CustomIdentList{}; - line_names.append(input.allocator(), line_name) catch bun.outOfMemory(); + bun.handleOom(line_names.append(input.allocator(), line_name)); if (input.tryParse(TrackSize.parse, .{}).asValue()) |track_size| { // TODO: error handling - items.append(.{ .track_size = track_size }) catch bun.outOfMemory(); + bun.handleOom(items.append(.{ .track_size = track_size })); } else if (input.tryParse(TrackRepeat.parse, .{}).asValue()) |repeat| { // TODO: error handling - items.append(.{ .track_repeat = repeat }) catch bun.outOfMemory(); + bun.handleOom(items.append(.{ .track_repeat = repeat })); } else { break; } @@ -183,7 +183,7 @@ pub const TrackSizeList = struct { pub fn parse(input: *css.Parser) css.Result(@This()) { var res = SmallList(TrackSize, 1){}; while (input.tryParse(TrackSize.parse, .{}).asValue()) |size| { - res.append(input.allocator(), size) catch bun.outOfMemory(); + bun.handleOom(res.append(input.allocator(), size)); } if (res.len() == 1 and res.at(0).eql(&TrackSize.default())) { @@ -314,11 +314,11 @@ pub const TrackRepeat = struct { while (true) { const line_name = i.tryParse(parseLineNames, .{}).unwrapOr(CustomIdentList{}); - line_names.append(i.allocator(), line_name) catch bun.outOfMemory(); + bun.handleOom(line_names.append(i.allocator(), line_name)); if (input.tryParse(TrackSize.parse, .{}).asValue()) |track_size| { // TODO: error handling - track_sizes.append(i.allocator(), track_size) catch bun.outOfMemory(); + bun.handleOom(track_sizes.append(i.allocator(), track_size)); } else { break; } @@ -401,7 +401,7 @@ fn parseLineNames(input: *css.Parser) css.Result(CustomIdentList) { var values = CustomIdentList{}; while (input.tryParse(CustomIdent.parse, .{}).asValue()) |ident| { - values.append(i.allocator(), ident) catch bun.outOfMemory(); + bun.handleOom(values.append(i.allocator(), ident)); } return .{ .result = values }; @@ -519,7 +519,7 @@ pub const GridTemplateAreas = union(enum) { break :token_len rest.len; }; const token = rest[0..token_len]; - tokens.append(allocator, token) catch bun.outOfMemory(); + bun.handleOom(tokens.append(allocator, token)); string = rest[token_len..]; } diff --git a/src/css/properties/margin_padding.zig b/src/css/properties/margin_padding.zig index c1c76b59ad..83f128e0cf 100644 --- a/src/css/properties/margin_padding.zig +++ b/src/css/properties/margin_padding.zig @@ -680,34 +680,34 @@ pub fn NewSizeHandler( .right = right.?, }, ), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { if (top) |t| { dest.append( context.allocator, @unionInit(Property, @tagName(top_prop), t), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (bottom) |b| { dest.append( context.allocator, @unionInit(Property, @tagName(bottom_prop), b), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (left) |b| { dest.append( context.allocator, @unionInit(Property, @tagName(left_prop), b), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (right) |b| { dest.append( context.allocator, @unionInit(Property, @tagName(right_prop), b), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -804,13 +804,13 @@ pub fn NewSizeHandler( Property, @tagName(shorthand_property), value, - )) catch bun.outOfMemory(); + )) catch |err| bun.handleOom(err); } else { if (start.* != null) { - dest.append(context.allocator, start.*.?) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, start.*.?)); } if (end.* != null) { - dest.append(context.allocator, end.*.?) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, end.*.?)); } } } @@ -833,14 +833,14 @@ pub fn NewSizeHandler( @tagName(physical), @field(v, @tagName(logical)), ), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else if (v.* == .unparsed) { dest.append( context.allocator, Property{ .unparsed = v.unparsed.withPropertyId(context.allocator, physical), }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } diff --git a/src/css/properties/prefix_handler.zig b/src/css/properties/prefix_handler.zig index 550a1d996e..5af8023c1f 100644 --- a/src/css/properties/prefix_handler.zig +++ b/src/css/properties/prefix_handler.zig @@ -49,7 +49,7 @@ pub const FallbackHandler = struct { else fallback, ), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (comptime has_vendor_prefix) { if (has_fallbacks and @field(property, field.name[1]).contains(VendorPrefix{ .none = true })) { @@ -72,7 +72,7 @@ pub const FallbackHandler = struct { else val, ), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else if (@field(this, field.name) != null) { const index = @field(this, field.name).?; dest.items[index] = @unionInit( @@ -115,7 +115,7 @@ pub const FallbackHandler = struct { dest.items[i] = Property{ .unparsed = unparsed }; } else { index.* = dest.items.len; - dest.append(context.allocator, Property{ .unparsed = unparsed }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .unparsed = unparsed })); } return true; diff --git a/src/css/properties/size.zig b/src/css/properties/size.zig index 72cec2a060..2b2bcfb228 100644 --- a/src/css/properties/size.zig +++ b/src/css/properties/size.zig @@ -469,14 +469,14 @@ pub const SizeHandler = struct { inline fn logicalUnparsedHelper(this: *@This(), property: *const Property, unparsed: *const UnparsedProperty, comptime physical: PropertyIdTag, logical_supported: bool, dest: *css.DeclarationList, context: *css.PropertyHandlerContext) void { if (logical_supported) { bun.bits.insert(SizeProperty, &this.flushed_properties, SizeProperty.tryFromPropertyIdTag(@as(PropertyIdTag, unparsed.property_id)).?); - dest.append(context.allocator, property.deepClone(context.allocator)) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, property.deepClone(context.allocator))); } else { dest.append(context.allocator, Property{ .unparsed = unparsed.withPropertyId( context.allocator, @unionInit(PropertyId, @tagName(physical), {}), ), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); @field(this.flushed_properties, @tagName(physical)) = true; } } @@ -549,7 +549,7 @@ pub const SizeHandler = struct { @tagName(property), @unionInit(SizeType, @tagName(feature), prefix), ), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } @@ -579,7 +579,7 @@ pub const SizeHandler = struct { }, else => {}, } - dest.append(context.allocator, @unionInit(Property, @tagName(property), val.deepClone(context.allocator))) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, @unionInit(Property, @tagName(property), val.deepClone(context.allocator)))); @field(this.flushed_properties, @tagName(property)) = true; } } diff --git a/src/css/properties/transform.zig b/src/css/properties/transform.zig index d3c1067a2b..94776e6d8d 100644 --- a/src/css/properties/transform.zig +++ b/src/css/properties/transform.zig @@ -23,14 +23,14 @@ pub const TransformList = struct { input.skipWhitespace(); var results = ArrayList(Transform){}; switch (Transform.parse(input)) { - .result => |first| results.append(input.allocator(), first) catch bun.outOfMemory(), + .result => |first| bun.handleOom(results.append(input.allocator(), first)), .err => |e| return .{ .err = e }, } while (true) { input.skipWhitespace(); if (input.tryParse(Transform.parse, .{}).asValue()) |item| { - results.append(input.allocator(), item) catch bun.outOfMemory(); + bun.handleOom(results.append(input.allocator(), item)); } else { return .{ .result = .{ .v = results } }; } @@ -1203,7 +1203,7 @@ pub const TransformHandler = struct { const individualProperty = struct { fn individualProperty(self: *TransformHandler, allocator: std.mem.Allocator, comptime field: []const u8, val: anytype) void { if (self.transform) |*transform| { - transform.*[0].v.append(allocator, val.toTransform(allocator)) catch bun.outOfMemory(); + bun.handleOom(transform.*[0].v.append(allocator, val.toTransform(allocator))); } else { @field(self, field) = val.deepClone(allocator); self.has_any = true; @@ -1251,7 +1251,7 @@ pub const TransformHandler = struct { Property{ .unparsed = unparsed.getPrefixed(allocator, context.targets, css.prefixes.Feature.transform) } else property.deepClone(allocator); - dest.append(allocator, prop) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, prop)); } else return false; }, else => return false, @@ -1276,19 +1276,19 @@ pub const TransformHandler = struct { if (transform) |t| { const prefix = context.targets.prefixes(t[1], css.prefixes.Feature.transform); - dest.append(allocator, Property{ .transform = .{ t[0], prefix } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .transform = .{ t[0], prefix } })); } if (translate) |t| { - dest.append(allocator, Property{ .translate = t }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .translate = t })); } if (rotate) |r| { - dest.append(allocator, Property{ .rotate = r }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .rotate = r })); } if (scale) |s| { - dest.append(allocator, Property{ .scale = s }) catch bun.outOfMemory(); + bun.handleOom(dest.append(allocator, Property{ .scale = s })); } } }; diff --git a/src/css/properties/transition.zig b/src/css/properties/transition.zig index 5cd4b0824b..74798444c1 100644 --- a/src/css/properties/transition.zig +++ b/src/css/properties/transition.zig @@ -159,7 +159,7 @@ pub const TransitionHandler = struct { dest.append( context.allocator, .{ .unparsed = x.getPrefixed(context.allocator, context.targets, Feature.transition) }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else return false, else => return false, } @@ -244,7 +244,7 @@ pub const TransitionHandler = struct { dest.append( context.allocator, Property{ .transition = .{ transitions.deepClone(context.allocator), intersection } }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } bun.bits.remove(VendorPrefix, property_prefixes, intersection); @@ -267,7 +267,7 @@ pub const TransitionHandler = struct { ); rtl_properties = null; } else { - dest.append(context.allocator, Property{ .@"transition-property" = .{ properties, prefix } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"transition-property" = .{ properties, prefix } })); } } } @@ -277,7 +277,7 @@ pub const TransitionHandler = struct { const prefix: VendorPrefix = _durations.?[1]; _durations = null; if (!prefix.isEmpty()) { - dest.append(context.allocator, Property{ .@"transition-duration" = .{ durations, prefix } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"transition-duration" = .{ durations, prefix } })); } } @@ -286,7 +286,7 @@ pub const TransitionHandler = struct { const prefix: VendorPrefix = _delays.?[1]; _delays = null; if (!prefix.isEmpty()) { - dest.append(context.allocator, Property{ .@"transition-delay" = .{ delays, prefix } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"transition-delay" = .{ delays, prefix } })); } } @@ -295,7 +295,7 @@ pub const TransitionHandler = struct { const prefix: VendorPrefix = _timing_functions.?[1]; _timing_functions = null; if (!prefix.isEmpty()) { - dest.append(context.allocator, Property{ .@"transition-timing-function" = .{ timing_functions, prefix } }) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, Property{ .@"transition-timing-function" = .{ timing_functions, prefix } })); } } diff --git a/src/css/properties/ui.zig b/src/css/properties/ui.zig index 3ebc4b8f10..11b46739ad 100644 --- a/src/css/properties/ui.zig +++ b/src/css/properties/ui.zig @@ -159,11 +159,11 @@ pub const ColorSchemeHandler = struct { dest.append( context.allocator, defineVar(context.allocator, "--buncss-light", .{ .ident = "initial" }), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); dest.append( context.allocator, defineVar(context.allocator, "--buncss-dark", .{ .whitespace = " " }), - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); if (color_scheme.dark) { context.addDarkRule( @@ -176,11 +176,11 @@ pub const ColorSchemeHandler = struct { ); } } else if (color_scheme.dark) { - dest.append(context.allocator, defineVar(context.allocator, "--buncss-light", .{ .whitespace = " " })) catch bun.outOfMemory(); - dest.append(context.allocator, defineVar(context.allocator, "--buncss-dark", .{ .ident = "initial" })) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, defineVar(context.allocator, "--buncss-light", .{ .whitespace = " " }))); + bun.handleOom(dest.append(context.allocator, defineVar(context.allocator, "--buncss-dark", .{ .ident = "initial" }))); } } - dest.append(context.allocator, property.deepClone(context.allocator)) catch bun.outOfMemory(); + bun.handleOom(dest.append(context.allocator, property.deepClone(context.allocator))); return true; }, else => return false, @@ -197,7 +197,7 @@ fn defineVar(allocator: Allocator, name: []const u8, value: css.Token) css.Prope .value = css.TokenList{ .v = brk: { var list = ArrayList(css.css_properties.custom.TokenOrValue){}; - list.append(allocator, css.css_properties.custom.TokenOrValue{ .token = value }) catch bun.outOfMemory(); + bun.handleOom(list.append(allocator, css.css_properties.custom.TokenOrValue{ .token = value })); break :brk list; }, }, diff --git a/src/css/rules/page.zig b/src/css/rules/page.zig index b1427ed9cc..438c33b5a8 100644 --- a/src/css/rules/page.zig +++ b/src/css/rules/page.zig @@ -32,7 +32,7 @@ pub const PageSelector = struct { .result => |vv| vv, .err => |e| return .{ .err = e }, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { input.reset(&state); break; @@ -355,7 +355,7 @@ pub const PageRuleParser = struct { .line = loc.line, .column = loc.column, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return .success; } diff --git a/src/css/rules/rules.zig b/src/css/rules/rules.zig index 8e1294df40..bd2578c20b 100644 --- a/src/css/rules/rules.zig +++ b/src/css/rules/rules.zig @@ -172,12 +172,12 @@ pub fn CssRuleList(comptime AtRule: type) type { // } // keyframez.vendor_prefix = context.targets.prefixes(keyframez.vendor_prefix, css.prefixes.Feature.at_keyframes); - // keyframe_rules.put(context.allocator, keyframez.name, rules.items.len) catch bun.outOfMemory(); + // bun.handleOom(keyframe_rules.put(context.allocator, keyframez.name, rules.items.len)); // const fallbacks = keyframez.getFallbacks(AtRule, context.targets); // moved_rule = true; - // rules.append(context.allocator, rule.*) catch bun.outOfMemory(); - // rules.appendSlice(context.allocator, fallbacks) catch bun.outOfMemory(); + // bun.handleOom(rules.append(context.allocator, rule.*)); + // bun.handleOom(rules.appendSlice(context.allocator, fallbacks)); // continue; debug("TODO: KeyframesRule", .{}); }, @@ -191,7 +191,7 @@ pub fn CssRuleList(comptime AtRule: type) type { if (rules.items.len > 0 and rules.items[rules.items.len - 1] == .media) { var last_rule = &rules.items[rules.items.len - 1].media; if (last_rule.query.eql(&med.query)) { - last_rule.rules.v.appendSlice(context.allocator, med.rules.v.items) catch bun.outOfMemory(); + bun.handleOom(last_rule.rules.v.appendSlice(context.allocator, med.rules.v.items)); _ = try last_rule.minify(context, parent_is_unused); continue; } @@ -372,7 +372,7 @@ pub fn CssRuleList(comptime AtRule: type) type { const has_no_rules = sty.rules.v.items.len == 0; const idx = rules.items.len; - rules.append(context.allocator, rule.*) catch bun.outOfMemory(); + bun.handleOom(rules.append(context.allocator, rule.*)); moved_rule = true; // Check if this rule is a duplicate of an earlier rule, meaning it has @@ -394,7 +394,7 @@ pub fn CssRuleList(comptime AtRule: type) type { } } - style_rules.put(context.allocator, key, idx) catch bun.outOfMemory(); + bun.handleOom(style_rules.put(context.allocator, key, idx)); } } @@ -404,22 +404,22 @@ pub fn CssRuleList(comptime AtRule: type) type { } var log = CssRuleList(AtRule){ .v = logical }; try log.minify(context, parent_is_unused); - rules.appendSlice(context.allocator, log.v.items) catch bun.outOfMemory(); + bun.handleOom(rules.appendSlice(context.allocator, log.v.items)); } - rules.appendSlice(context.allocator, supps.items) catch bun.outOfMemory(); + bun.handleOom(rules.appendSlice(context.allocator, supps.items)); for (incompatible_rules.slice_mut()) |incompatible_entry| { if (!incompatible_entry.rule.isEmpty()) { - rules.append(context.allocator, .{ .style = incompatible_entry.rule }) catch bun.outOfMemory(); + bun.handleOom(rules.append(context.allocator, .{ .style = incompatible_entry.rule })); } if (incompatible_entry.logical.items.len > 0) { var log = CssRuleList(AtRule){ .v = incompatible_entry.logical }; try log.minify(context, parent_is_unused); - rules.appendSlice(context.allocator, log.v.items) catch bun.outOfMemory(); + bun.handleOom(rules.appendSlice(context.allocator, log.v.items)); } - rules.appendSlice(context.allocator, incompatible_entry.supports.items) catch bun.outOfMemory(); + bun.handleOom(rules.appendSlice(context.allocator, incompatible_entry.supports.items)); } if (nested_rule) |nested| { - rules.append(context.allocator, .{ .style = nested }) catch bun.outOfMemory(); + bun.handleOom(rules.append(context.allocator, .{ .style = nested })); } continue; @@ -451,7 +451,7 @@ pub fn CssRuleList(comptime AtRule: type) type { else => {}, } - rules.append(context.allocator, rule.*) catch bun.outOfMemory(); + bun.handleOom(rules.append(context.allocator, rule.*)); } // MISSING SHIT HERE @@ -614,13 +614,13 @@ fn mergeStyleRules( last_style_rule.declarations.declarations.appendSlice( context.allocator, sty.declarations.declarations.items, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); sty.declarations.declarations.clearRetainingCapacity(); last_style_rule.declarations.important_declarations.appendSlice( context.allocator, sty.declarations.important_declarations.items, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); sty.declarations.important_declarations.clearRetainingCapacity(); last_style_rule.declarations.minify( diff --git a/src/css/rules/supports.zig b/src/css/rules/supports.zig index 016b708009..1884c2ff33 100644 --- a/src/css/rules/supports.zig +++ b/src/css/rules/supports.zig @@ -171,14 +171,14 @@ pub const SupportsCondition = union(enum) { switch (_condition) { .result => |condition| { if (conditions.items.len == 0) { - conditions.append(input.allocator(), in_parens.deepClone(input.allocator())) catch bun.outOfMemory(); + bun.handleOom(conditions.append(input.allocator(), in_parens.deepClone(input.allocator()))); if (in_parens == .declaration) { const property_id = in_parens.declaration.property_id; const value = in_parens.declaration.value; seen_declarations.put( .{ property_id.withPrefix(css.VendorPrefix{ .none = true }), value }, 0, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } @@ -195,17 +195,17 @@ pub const SupportsCondition = union(enum) { cond.declaration.property_id.addPrefix(property_id.prefix()); } } else { - seen_declarations.put(key, conditions.items.len) catch bun.outOfMemory(); + bun.handleOom(seen_declarations.put(key, conditions.items.len)); conditions.append(input.allocator(), SupportsCondition{ .declaration = .{ .property_id = property_id, .value = value, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); } } else { conditions.append( input.allocator(), condition, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } }, else => break, diff --git a/src/css/selectors/parser.zig b/src/css/selectors/parser.zig index f5b5527b41..b4ce5d2181 100644 --- a/src/css/selectors/parser.zig +++ b/src/css/selectors/parser.zig @@ -1669,7 +1669,7 @@ pub fn GenericSelector(comptime Impl: type) type { } break :index this.components.items.len; }; - this.components.insert(allocator, index, component) catch bun.outOfMemory(); + bun.handleOom(this.components.insert(allocator, index, component)); } pub fn deepClone(this: *const @This(), allocator: Allocator) This { diff --git a/src/css/selectors/selector.zig b/src/css/selectors/selector.zig index d33e4b45aa..8ecc3a2a4d 100644 --- a/src/css/selectors/selector.zig +++ b/src/css/selectors/selector.zig @@ -151,13 +151,13 @@ pub fn downlevelComponent(allocator: Allocator, component: *Component, targets: // https://drafts.csswg.org/selectors/#specificity-rules if (selectors.len > 1 and css.targets.Targets.shouldCompileSame(&targets, .not_selector_list)) { const is: Selector = Selector.fromComponent(allocator, Component{ .is = selectors: { - const new_selectors = allocator.alloc(Selector, selectors.len) catch bun.outOfMemory(); + const new_selectors = bun.handleOom(allocator.alloc(Selector, selectors.len)); for (new_selectors, selectors) |*new, *sel| { new.* = sel.deepClone(allocator); } break :selectors new_selectors; } }); - var list = ArrayList(Selector).initCapacity(allocator, 1) catch bun.outOfMemory(); + var list = bun.handleOom(ArrayList(Selector).initCapacity(allocator, 1)); list.appendAssumeCapacity(is); component.* = .{ .negation = list.items }; @@ -188,7 +188,7 @@ fn downlevelDir(allocator: Allocator, dir: parser.Direction, targets: css.target const c = Component{ .non_ts_pseudo_class = PseudoClass{ .lang = .{ .languages = lang: { - var list = ArrayList([]const u8).initCapacity(allocator, RTL_LANGS.len) catch bun.outOfMemory(); + var list = bun.handleOom(ArrayList([]const u8).initCapacity(allocator, RTL_LANGS.len)); list.appendSliceAssumeCapacity(RTL_LANGS); break :lang list; } }, @@ -196,7 +196,7 @@ fn downlevelDir(allocator: Allocator, dir: parser.Direction, targets: css.target }; if (dir == .ltr) return Component{ .negation = negation: { - var list = allocator.alloc(Selector, 1) catch bun.outOfMemory(); + var list = bun.handleOom(allocator.alloc(Selector, 1)); list[0] = Selector.fromComponent(allocator, c); break :negation list; }, @@ -209,12 +209,12 @@ fn downlevelDir(allocator: Allocator, dir: parser.Direction, targets: css.target } fn langListToSelectors(allocator: Allocator, langs: []const []const u8) []Selector { - var selectors = allocator.alloc(Selector, langs.len) catch bun.outOfMemory(); + var selectors = bun.handleOom(allocator.alloc(Selector, langs.len)); for (langs, selectors[0..]) |lang, *sel| { sel.* = Selector.fromComponent(allocator, Component{ .non_ts_pseudo_class = PseudoClass{ .lang = .{ .languages = langs: { - var list = ArrayList([]const u8).initCapacity(allocator, 1) catch bun.outOfMemory(); + var list = bun.handleOom(ArrayList([]const u8).initCapacity(allocator, 1)); list.appendAssumeCapacity(lang); break :langs list; } }, diff --git a/src/css/small_list.zig b/src/css/small_list.zig index 648cb9750e..132b1609b7 100644 --- a/src/css/small_list.zig +++ b/src/css/small_list.zig @@ -27,7 +27,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { pub fn initCapacity(allocator: Allocator, capacity: u32) HeapData { return .{ .len = 0, - .ptr = (allocator.alloc(T, capacity) catch bun.outOfMemory()).ptr, + .ptr = bun.handleOom(allocator.alloc(T, capacity)).ptr, }; } }; @@ -175,7 +175,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { pub inline fn toOwnedSlice(this: *const @This(), allocator: Allocator) []T { if (this.spilled()) return this.data.heap.ptr[0..this.data.heap.len]; - return allocator.dupe(T, this.data.inlined[0..this.capacity]) catch bun.outOfMemory(); + return bun.handleOom(allocator.dupe(T, this.data.inlined[0..this.capacity])); } /// NOTE: If this is inlined then this will refer to stack memory, if @@ -237,7 +237,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { break :images images; }; if (!images.isEmpty()) { - res.push(allocator, images) catch bun.outOfMemory(); + bun.handleOom(res.push(allocator, images)); } } @@ -250,7 +250,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { const image = in.getImage().getPrefixed(alloc, css.VendorPrefix.fromName(prefix)); out.* = in.withImage(alloc, image); } - r.push(alloc, images) catch bun.outOfMemory(); + bun.handleOom(r.push(alloc, images)); } } }.helper; @@ -261,7 +261,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { if (prefixes.none) { if (rgb) |r| { - res.push(allocator, r) catch bun.outOfMemory(); + bun.handleOom(res.push(allocator, r)); } if (fallbacks.p3) { @@ -427,7 +427,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { pub fn clone(this: *const @This(), allocator: Allocator) @This() { var ret = this.*; if (!this.spilled()) return ret; - ret.data.heap.ptr = (allocator.dupe(T, ret.data.heap.ptr[0..ret.data.heap.len]) catch bun.outOfMemory()).ptr; + ret.data.heap.ptr = bun.handleOom(allocator.dupe(T, ret.data.heap.ptr[0..ret.data.heap.len])).ptr; return ret; } @@ -597,11 +597,11 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { allocator.free(ptr[0..length]); } else if (new_cap != cap) { const new_alloc: [*]T = if (unspilled) new_alloc: { - const new_alloc = allocator.alloc(T, new_cap) catch bun.outOfMemory(); + const new_alloc = bun.handleOom(allocator.alloc(T, new_cap)); @memcpy(new_alloc[0..length], ptr[0..length]); break :new_alloc new_alloc.ptr; } else new_alloc: { - break :new_alloc (allocator.realloc(ptr[0..length], new_cap * @sizeOf(T)) catch bun.outOfMemory()).ptr; + break :new_alloc bun.handleOom(allocator.realloc(ptr[0..length], new_cap * @sizeOf(T))).ptr; }; this.data = .{ .heap = .{ .ptr = new_alloc, .len = length } }; this.capacity = new_cap; @@ -623,7 +623,7 @@ pub fn SmallList(comptime T: type, comptime N: comptime_int) type { fn growToHeap(this: *@This(), allocator: Allocator, additional: usize) void { bun.assert(!this.spilled()); const new_size = growCapacity(this.capacity, this.capacity + additional); - var slc = allocator.alloc(T, new_size) catch bun.outOfMemory(); + var slc = bun.handleOom(allocator.alloc(T, new_size)); @memcpy(slc[0..this.capacity], this.data.inlined[0..this.capacity]); this.data = .{ .heap = HeapData{ .len = this.capacity, .ptr = slc.ptr } }; this.capacity = new_size; diff --git a/src/css/values/calc.zig b/src/css/values/calc.zig index 04a7e429c2..a6f729da88 100644 --- a/src/css/values/calc.zig +++ b/src/css/values/calc.zig @@ -1492,7 +1492,7 @@ pub fn Calc(comptime V: type) type { continue; } } else { - reduced.append(allocator, arg.*) catch bun.outOfMemory(); + bun.handleOom(reduced.append(allocator, arg.*)); // set to dummy value since we moved it into `reduced` arg.* = This{ .number = 420 }; continue; @@ -1820,7 +1820,7 @@ fn arr2(allocator: std.mem.Allocator, a: anytype, b: anytype) ArrayList(@TypeOf( @compileError("arr2: types must match"); } var arr = ArrayList(T){}; - arr.appendSlice(allocator, &.{ a, b }) catch bun.outOfMemory(); + bun.handleOom(arr.appendSlice(allocator, &.{ a, b })); return arr; } diff --git a/src/css/values/color_js.zig b/src/css/values/color_js.zig index 99c9a287ef..84cccde9ec 100644 --- a/src/css/values/color_js.zig +++ b/src/css/values/color_js.zig @@ -399,7 +399,7 @@ pub fn jsFunctionColor(globalThis: *jsc.JSGlobalObject, callFrame: *jsc.CallFram break :color bun.String.createFormat("lab({d}, {d}, {d})", .{ lab.l, lab.a, lab.b }); }, } - } catch bun.outOfMemory(); + } catch |err| bun.handleOom(err); return str.transferToJS(globalThis); } diff --git a/src/css/values/gradient.zig b/src/css/values/gradient.zig index 8f239b5be6..0ca5198699 100644 --- a/src/css/values/gradient.zig +++ b/src/css/values/gradient.zig @@ -396,7 +396,7 @@ pub const LinearGradient = struct { var flipped_items = ArrayList(GradientItem(LengthPercentage)).initCapacity( dest.allocator, this.items.items.len, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); defer flipped_items.deinit(dest.allocator); var i: usize = this.items.items.len; @@ -405,7 +405,7 @@ pub const LinearGradient = struct { const item = &this.items.items[i]; switch (item.*) { .hint => |*h| switch (h.*) { - .percentage => |p| flipped_items.append(dest.allocator, .{ .hint = .{ .percentage = .{ .v = 1.0 - p.v } } }) catch bun.outOfMemory(), + .percentage => |p| bun.handleOom(flipped_items.append(dest.allocator, .{ .hint = .{ .percentage = .{ .v = 1.0 - p.v } } })), else => unreachable, }, .color_stop => |*cs| flipped_items.append(dest.allocator, .{ @@ -416,7 +416,7 @@ pub const LinearGradient = struct { else => unreachable, } else null, }, - }) catch bun.outOfMemory(), + }) catch |err| bun.handleOom(err), } } @@ -449,7 +449,7 @@ pub const LinearGradient = struct { } pub fn getFallback(this: *const @This(), allocator: std.mem.Allocator, kind: css.ColorFallbackKind) LinearGradient { - var fallback_items = ArrayList(GradientItem(LengthPercentage)).initCapacity(allocator, this.items.items.len) catch bun.outOfMemory(); + var fallback_items = bun.handleOom(ArrayList(GradientItem(LengthPercentage)).initCapacity(allocator, this.items.items.len)); fallback_items.items.len = this.items.items.len; for (fallback_items.items, this.items.items) |*out, *in| { out.* = in.getFallback(allocator, kind); @@ -537,7 +537,7 @@ pub const RadialGradient = struct { } pub fn getFallback(this: *const RadialGradient, allocator: Allocator, kind: css.ColorFallbackKind) RadialGradient { - var items = ArrayList(GradientItem(LengthPercentage)).initCapacity(allocator, this.items.items.len) catch bun.outOfMemory(); + var items = bun.handleOom(ArrayList(GradientItem(LengthPercentage)).initCapacity(allocator, this.items.items.len)); items.items.len = this.items.items.len; for (items.items, this.items.items) |*out, *in| { out.* = in.getFallback(allocator, kind); @@ -630,7 +630,7 @@ pub const ConicGradient = struct { } pub fn getFallback(this: *const @This(), allocator: Allocator, kind: css.ColorFallbackKind) ConicGradient { - var items = ArrayList(GradientItem(AnglePercentage)).initCapacity(allocator, this.items.items.len) catch bun.outOfMemory(); + var items = bun.handleOom(ArrayList(GradientItem(AnglePercentage)).initCapacity(allocator, this.items.items.len)); items.items.len = this.items.items.len; for (items.items, this.items.items) |*out, *in| { out.* = in.getFallback(allocator, kind); @@ -798,7 +798,7 @@ pub const WebKitGradient = union(enum) { var stops: ArrayList(WebKitColorStop) = .{}; switch (this.*) { .linear => |linear| { - stops = ArrayList(WebKitColorStop).initCapacity(allocator, linear.stops.items.len) catch bun.outOfMemory(); + stops = bun.handleOom(ArrayList(WebKitColorStop).initCapacity(allocator, linear.stops.items.len)); stops.items.len = linear.stops.items.len; for (stops.items, linear.stops.items) |*out, *in| { out.* = in.getFallback(allocator, kind); @@ -812,7 +812,7 @@ pub const WebKitGradient = union(enum) { }; }, .radial => |radial| { - stops = ArrayList(WebKitColorStop).initCapacity(allocator, radial.stops.items.len) catch bun.outOfMemory(); + stops = bun.handleOom(ArrayList(WebKitColorStop).initCapacity(allocator, radial.stops.items.len)); stops.items.len = radial.stops.items.len; for (stops.items, radial.stops.items) |*out, *in| { out.* = in.getFallback(allocator, kind); @@ -1539,7 +1539,7 @@ pub fn parseItems(comptime D: type, input: *css.Parser) Result(ArrayList(Gradien if (closure.seen_stop.*) { if (i.tryParse(comptime css.generic.parseFor(D), .{}).asValue()) |hint| { closure.seen_stop.* = false; - closure.items.append(i.allocator(), .{ .hint = hint }) catch bun.outOfMemory(); + bun.handleOom(closure.items.append(i.allocator(), .{ .hint = hint })); return .success; } } @@ -1551,13 +1551,13 @@ pub fn parseItems(comptime D: type, input: *css.Parser) Result(ArrayList(Gradien if (i.tryParse(comptime css.generic.parseFor(D), .{}).asValue()) |position| { const color = stop.color.deepClone(i.allocator()); - closure.items.append(i.allocator(), .{ .color_stop = stop }) catch bun.outOfMemory(); + bun.handleOom(closure.items.append(i.allocator(), .{ .color_stop = stop })); closure.items.append(i.allocator(), .{ .color_stop = .{ .color = color, .position = position, - } }) catch bun.outOfMemory(); + } }) catch |err| bun.handleOom(err); } else { - closure.items.append(i.allocator(), .{ .color_stop = stop }) catch bun.outOfMemory(); + bun.handleOom(closure.items.append(i.allocator(), .{ .color_stop = stop })); } closure.seen_stop.* = true; @@ -1617,7 +1617,7 @@ pub fn serializeItems( } pub fn convertStopsToWebkit(allocator: Allocator, items: *const ArrayList(GradientItem(LengthPercentage))) ?ArrayList(WebKitColorStop) { - var stops: ArrayList(WebKitColorStop) = ArrayList(WebKitColorStop).initCapacity(allocator, items.items.len) catch bun.outOfMemory(); + var stops: ArrayList(WebKitColorStop) = bun.handleOom(ArrayList(WebKitColorStop).initCapacity(allocator, items.items.len)); for (items.items, 0..) |*item, i| { switch (item.*) { .color_stop => |*stop| { diff --git a/src/css/values/ident.zig b/src/css/values/ident.zig index b14ac562e0..ed11425429 100644 --- a/src/css/values/ident.zig +++ b/src/css/values/ident.zig @@ -193,7 +193,7 @@ pub const IdentOrRef = packed struct(u128) { }; if (comptime bun.Environment.isDebug) { - const heap_ptr: *[]const u8 = debug_ident[1].create([]const u8) catch bun.outOfMemory(); + const heap_ptr: *[]const u8 = bun.handleOom(debug_ident[1].create([]const u8)); heap_ptr.* = debug_ident[0]; this.__ptrbits = @intCast(@intFromPtr(heap_ptr)); } diff --git a/src/css/values/image.zig b/src/css/values/image.zig index 191fd3c4ef..f09d10da48 100644 --- a/src/css/values/image.zig +++ b/src/css/values/image.zig @@ -351,7 +351,7 @@ pub const ImageSetOption = struct { dependencies.append( dest.allocator, .{ .url = dep }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } else { css.serializer.serializeString(try dest.getImportRecordUrl(this.image.url.import_record_idx), dest) catch return dest.addFmtError(); diff --git a/src/css/values/syntax.zig b/src/css/values/syntax.zig index a6d57f898b..bf74f563f6 100644 --- a/src/css/values/syntax.zig +++ b/src/css/values/syntax.zig @@ -90,7 +90,7 @@ pub const SyntaxString = union(enum) { components.append( allocator, component, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); trimmed_input = std.mem.trimLeft(u8, trimmed_input, SPACE_CHARACTERS); if (trimmed_input.len == 0) { @@ -211,7 +211,7 @@ pub const SyntaxString = union(enum) { switch (component.multiplier) { .none => return .{ .result = value }, .space => { - parsed.append(input.allocator(), value) catch bun.outOfMemory(); + bun.handleOom(parsed.append(input.allocator(), value)); if (input.isExhausted()) { return .{ .result = ParsedComponent{ .repeated = .{ .components = parsed, @@ -220,7 +220,7 @@ pub const SyntaxString = union(enum) { } }, .comma => { - parsed.append(input.allocator(), value) catch bun.outOfMemory(); + bun.handleOom(parsed.append(input.allocator(), value)); if (input.next().asValue()) |token| { if (token.* == .comma) continue; break; diff --git a/src/css/values/url.zig b/src/css/values/url.zig index 1020a3812c..2e0cd86fc5 100644 --- a/src/css/values/url.zig +++ b/src/css/values/url.zig @@ -84,7 +84,7 @@ pub const Url = struct { try dest.writeChar(')'); if (dest.dependencies) |*dependencies| { - dependencies.append(dest.allocator, css.Dependency{ .url = d }) catch bun.outOfMemory(); + bun.handleOom(dependencies.append(dest.allocator, css.Dependency{ .url = d })); } return; diff --git a/src/deps/c_ares.zig b/src/deps/c_ares.zig index 293412a486..d8c9825089 100644 --- a/src/deps/c_ares.zig +++ b/src/deps/c_ares.zig @@ -383,7 +383,7 @@ pub const hostent_with_ttls = struct { if (result != ARES_SUCCESS) { return .{ .err = Error.get(result).? }; } - var with_ttls = bun.default_allocator.create(hostent_with_ttls) catch bun.outOfMemory(); + var with_ttls = bun.handleOom(bun.default_allocator.create(hostent_with_ttls)); with_ttls.hostent = start.?; for (addrttls[0..@intCast(naddrttls)], 0..) |ttl, i| { with_ttls.ttls[i] = ttl.ttl; @@ -399,7 +399,7 @@ pub const hostent_with_ttls = struct { if (result != ARES_SUCCESS) { return .{ .err = Error.get(result).? }; } - var with_ttls = bun.default_allocator.create(hostent_with_ttls) catch bun.outOfMemory(); + var with_ttls = bun.handleOom(bun.default_allocator.create(hostent_with_ttls)); with_ttls.hostent = start.?; for (addr6ttls[0..@intCast(naddr6ttls)], 0..) |ttl, i| { with_ttls.ttls[i] = ttl.ttl; @@ -1460,7 +1460,7 @@ pub const struct_any_reply = struct { var any_success = false; var last_error: ?c_int = null; - var reply = bun.default_allocator.create(struct_any_reply) catch bun.outOfMemory(); + var reply = bun.handleOom(bun.default_allocator.create(struct_any_reply)); reply.* = .{}; switch (hostent_with_ttls.parse("a", buffer, buffer_length)) { @@ -1687,9 +1687,9 @@ pub const Error = enum(i32) { .errno = @intFromEnum(this.errno), .code = bun.String.static(this.errno.code()), .message = if (this.hostname) |hostname| - bun.String.createFormat("{s} {s} {s}", .{ this.syscall, this.errno.code()[4..], hostname }) catch bun.outOfMemory() + bun.handleOom(bun.String.createFormat("{s} {s} {s}", .{ this.syscall, this.errno.code()[4..], hostname })) else - bun.String.createFormat("{s} {s}", .{ this.syscall, this.errno.code()[4..] }) catch bun.outOfMemory(), + bun.handleOom(bun.String.createFormat("{s} {s}", .{ this.syscall, this.errno.code()[4..] })), .syscall = bun.String.cloneUTF8(this.syscall), .hostname = this.hostname orelse bun.String.empty, }; @@ -1712,7 +1712,7 @@ pub const Error = enum(i32) { } }; - const context = bun.default_allocator.create(Context) catch bun.outOfMemory(); + const context = bun.handleOom(bun.default_allocator.create(Context)); context.deferred = this; context.globalThis = globalThis; // TODO(@heimskr): new custom Task type @@ -1742,7 +1742,7 @@ pub const Error = enum(i32) { .errno = @intFromEnum(this), .code = bun.String.static(this.code()[4..]), .syscall = bun.String.static(syscall), - .message = bun.String.createFormat("{s} {s}", .{ syscall, this.code()[4..] }) catch bun.outOfMemory(), + .message = bun.handleOom(bun.String.createFormat("{s} {s}", .{ syscall, this.code()[4..] })), }).toErrorInstance(globalThis); instance.put(globalThis, "name", bun.String.static("DNSException").toJS(globalThis)); return instance; @@ -1752,7 +1752,7 @@ pub const Error = enum(i32) { const instance = (jsc.SystemError{ .errno = @intFromEnum(this), .code = bun.String.static(this.code()[4..]), - .message = bun.String.createFormat("{s} {s} {s}", .{ syscall, this.code()[4..], hostname }) catch bun.outOfMemory(), + .message = bun.handleOom(bun.String.createFormat("{s} {s} {s}", .{ syscall, this.code()[4..], hostname })), .syscall = bun.String.static(syscall), .hostname = bun.String.cloneUTF8(hostname), }).toErrorInstance(globalThis); diff --git a/src/deps/uws/UpgradedDuplex.zig b/src/deps/uws/UpgradedDuplex.zig index 515a73f2d4..4c9f70af3e 100644 --- a/src/deps/uws/UpgradedDuplex.zig +++ b/src/deps/uws/UpgradedDuplex.zig @@ -74,8 +74,8 @@ fn onHandshake(this: *UpgradedDuplex, handshake_success: bool, ssl_error: uws.us this.ssl_error = .{ .error_no = ssl_error.error_no, - .code = if (ssl_error.code == null or ssl_error.error_no == 0) "" else bun.default_allocator.dupeZ(u8, ssl_error.code[0..bun.len(ssl_error.code) :0]) catch bun.outOfMemory(), - .reason = if (ssl_error.reason == null or ssl_error.error_no == 0) "" else bun.default_allocator.dupeZ(u8, ssl_error.reason[0..bun.len(ssl_error.reason) :0]) catch bun.outOfMemory(), + .code = if (ssl_error.code == null or ssl_error.error_no == 0) "" else bun.handleOom(bun.default_allocator.dupeZ(u8, ssl_error.code[0..bun.len(ssl_error.code) :0])), + .reason = if (ssl_error.reason == null or ssl_error.error_no == 0) "" else bun.handleOom(bun.default_allocator.dupeZ(u8, ssl_error.reason[0..bun.len(ssl_error.reason) :0])), }; this.handlers.onHandshake(this.handlers.ctx, handshake_success, ssl_error); } diff --git a/src/deps/uws/WindowsNamedPipe.zig b/src/deps/uws/WindowsNamedPipe.zig index 904c4be907..f45ff568db 100644 --- a/src/deps/uws/WindowsNamedPipe.zig +++ b/src/deps/uws/WindowsNamedPipe.zig @@ -81,7 +81,7 @@ fn onPipeClose(this: *WindowsNamedPipe) void { fn onReadAlloc(this: *WindowsNamedPipe, suggested_size: usize) []u8 { var available = this.incoming.available(); if (available.len < suggested_size) { - this.incoming.ensureUnusedCapacity(bun.default_allocator, suggested_size) catch bun.outOfMemory(); + bun.handleOom(this.incoming.ensureUnusedCapacity(bun.default_allocator, suggested_size)); available = this.incoming.available(); } return available.ptr[0..suggested_size]; @@ -155,8 +155,8 @@ fn onHandshake(this: *WindowsNamedPipe, handshake_success: bool, ssl_error: uws. this.ssl_error = .{ .error_no = ssl_error.error_no, - .code = if (ssl_error.code == null or ssl_error.error_no == 0) "" else bun.default_allocator.dupeZ(u8, ssl_error.code[0..bun.len(ssl_error.code) :0]) catch bun.outOfMemory(), - .reason = if (ssl_error.reason == null or ssl_error.error_no == 0) "" else bun.default_allocator.dupeZ(u8, ssl_error.reason[0..bun.len(ssl_error.reason) :0]) catch bun.outOfMemory(), + .code = if (ssl_error.code == null or ssl_error.error_no == 0) "" else bun.handleOom(bun.default_allocator.dupeZ(u8, ssl_error.code[0..bun.len(ssl_error.code) :0])), + .reason = if (ssl_error.reason == null or ssl_error.error_no == 0) "" else bun.handleOom(bun.default_allocator.dupeZ(u8, ssl_error.reason[0..bun.len(ssl_error.reason) :0])), }; this.handlers.onHandshake(this.handlers.ctx, handshake_success, ssl_error); } @@ -179,7 +179,7 @@ fn callWriteOrEnd(this: *WindowsNamedPipe, data: ?[]const u8, msg_more: bool) vo } if (this.flags.disconnected) { // enqueue to be sent after connecting - this.writer.outgoing.write(bytes) catch bun.outOfMemory(); + bun.handleOom(this.writer.outgoing.write(bytes)); } else { // write will enqueue the data if it cannot be sent _ = this.writer.write(bytes); diff --git a/src/deps/uws/socket.zig b/src/deps/uws/socket.zig index 6e7b3551e3..d4f81b8f77 100644 --- a/src/deps/uws/socket.zig +++ b/src/deps/uws/socket.zig @@ -478,7 +478,7 @@ pub fn NewSocketHandler(comptime is_ssl: bool) type { else host; - const host_ = allocator.dupeZ(u8, clean_host) catch bun.outOfMemory(); + const host_ = bun.handleOom(allocator.dupeZ(u8, clean_host)); defer allocator.free(host); var did_dns_resolve: i32 = 0; @@ -578,7 +578,7 @@ pub fn NewSocketHandler(comptime is_ssl: bool) type { debug("connect(unix:{s})", .{path}); var stack_fallback = std.heap.stackFallback(1024, bun.default_allocator); var allocator = stack_fallback.get(); - const path_ = allocator.dupeZ(u8, path) catch bun.outOfMemory(); + const path_ = bun.handleOom(allocator.dupeZ(u8, path)); defer allocator.free(path_); const socket = socket_ctx.connectUnix(is_ssl, path_, if (allowHalfOpen) uws.LIBUS_SOCKET_ALLOW_HALF_OPEN else 0, 8) orelse @@ -608,7 +608,7 @@ pub fn NewSocketHandler(comptime is_ssl: bool) type { else raw_host; - const host = allocator.dupeZ(u8, clean_host) catch bun.outOfMemory(); + const host = bun.handleOom(allocator.dupeZ(u8, clean_host)); defer allocator.free(host); var did_dns_resolve: i32 = 0; diff --git a/src/fs.zig b/src/fs.zig index 581291bf00..ad429ff5f0 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -537,14 +537,14 @@ pub const FileSystem = struct { bun.default_allocator, "{s}\\Temp", .{strings.withoutTrailingSlash(windir)}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (bun.getenvZ("USERPROFILE")) |profile| { var buf: bun.PathBuffer = undefined; var parts = [_]string{"AppData\\Local\\Temp"}; const out = bun.path.joinAbsStringBuf(profile, &buf, &parts, .loose); - break :brk bun.default_allocator.dupe(u8, out) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.default_allocator.dupe(u8, out)); } var tmp_buf: bun.PathBuffer = undefined; @@ -554,7 +554,7 @@ pub const FileSystem = struct { bun.default_allocator, "{s}\\Windows\\Temp", .{strings.withoutTrailingSlash(root)}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); }; win_tempdir_cache = value; return value; @@ -1088,7 +1088,7 @@ pub const FileSystem = struct { }; if (comptime FeatureFlags.enable_entry_cache) { - const entries_ptr = in_place orelse bun.fs_allocator.create(DirEntry) catch bun.outOfMemory(); + const entries_ptr = in_place orelse bun.handleOom(bun.fs_allocator.create(DirEntry)); if (in_place) |original| { original.data.clearAndFree(bun.fs_allocator); } diff --git a/src/handle_oom.zig b/src/handle_oom.zig new file mode 100644 index 0000000000..ac166cd03b --- /dev/null +++ b/src/handle_oom.zig @@ -0,0 +1,66 @@ +fn isOomOnlyError(comptime ErrorUnionOrSet: type) bool { + @setEvalBranchQuota(10000); + const ErrorSet = switch (@typeInfo(ErrorUnionOrSet)) { + .error_union => |union_info| union_info.error_set, + .error_set => ErrorUnionOrSet, + else => @compileError("argument must be an error union or error set"), + }; + for (@typeInfo(ErrorSet).error_set orelse &.{}) |err| { + if (!std.mem.eql(u8, err.name, "OutOfMemory")) return false; + } + return true; +} + +/// If `error_union_or_set` is `error.OutOfMemory`, calls `bun.outOfMemory`. Otherwise: +/// +/// * If that was the only possible error, returns the non-error payload for error unions, or +/// `noreturn` for error sets. +/// * If other errors are possible, returns the same error union or set, but without +/// `error.OutOfMemory` in the error set. +/// +/// Prefer this method over `catch bun.outOfMemory()`, since that could mistakenly catch +/// non-OOM-related errors. +/// +/// There are two ways to use this function: +/// +/// ``` +/// // option 1: +/// const thing = bun.handleOom(allocateThing()); +/// // option 2: +/// const thing = allocateThing() catch |err| bun.handleOom(err); +/// ``` +pub fn handleOom(error_union_or_set: anytype) return_type: { + const ArgType = @TypeOf(error_union_or_set); + const arg_info = @typeInfo(ArgType); + break :return_type if (isOomOnlyError(ArgType)) switch (arg_info) { + .error_union => |union_info| union_info.payload, + .error_set => noreturn, + else => unreachable, + } else @TypeOf(blk: { + const err = switch (comptime arg_info) { + .error_union => if (error_union_or_set) |success| break :blk success else |err| err, + .error_set => error_union_or_set, + else => unreachable, + }; + break :blk switch (err) { + error.OutOfMemory => unreachable, + else => |other_error| other_error, + }; + }); +} { + const ArgType = @TypeOf(error_union_or_set); + const err = switch (comptime @typeInfo(ArgType)) { + .error_union => if (error_union_or_set) |success| return success else |err| err, + .error_set => error_union_or_set, + else => unreachable, + }; + return if (comptime isOomOnlyError(ArgType)) + bun.outOfMemory() + else switch (err) { + error.OutOfMemory => bun.outOfMemory(), + else => |other_error| other_error, + }; +} + +const bun = @import("bun"); +const std = @import("std"); diff --git a/src/http.zig b/src/http.zig index e33dc2f73c..91fcf18ebc 100644 --- a/src/http.zig +++ b/src/http.zig @@ -50,7 +50,7 @@ pub fn checkServerIdentity( if (client.signals.get(.cert_errors)) { // clone the relevant data const cert_size = BoringSSL.i2d_X509(x509, null); - const cert = bun.default_allocator.alloc(u8, @intCast(cert_size)) catch bun.outOfMemory(); + const cert = bun.handleOom(bun.default_allocator.alloc(u8, @intCast(cert_size))); var cert_ptr = cert.ptr; const result_size = BoringSSL.i2d_X509(x509, &cert_ptr); assert(result_size == cert_size); @@ -64,11 +64,11 @@ pub fn checkServerIdentity( client.state.certificate_info = .{ .cert = cert, - .hostname = bun.default_allocator.dupe(u8, hostname) catch bun.outOfMemory(), + .hostname = bun.handleOom(bun.default_allocator.dupe(u8, hostname)), .cert_error = .{ .error_no = certError.error_no, - .code = bun.default_allocator.dupeZ(u8, certError.code) catch bun.outOfMemory(), - .reason = bun.default_allocator.dupeZ(u8, certError.reason) catch bun.outOfMemory(), + .code = bun.handleOom(bun.default_allocator.dupeZ(u8, certError.code)), + .reason = bun.handleOom(bun.default_allocator.dupeZ(u8, certError.reason)), }, }; @@ -984,7 +984,7 @@ fn writeToSocket(comptime is_ssl: bool, socket: NewHTTPContext(is_ssl).HTTPSocke fn writeToSocketWithBufferFallback(comptime is_ssl: bool, socket: NewHTTPContext(is_ssl).HTTPSocket, buffer: *bun.io.StreamBuffer, data: []const u8) !usize { const amount = try writeToSocket(is_ssl, socket, data); if (amount < data.len) { - buffer.write(data[@intCast(amount)..]) catch bun.outOfMemory(); + bun.handleOom(buffer.write(data[@intCast(amount)..])); } return amount; } @@ -999,7 +999,7 @@ fn writeToStreamUsingBuffer(this: *HTTPClient, comptime is_ssl: bool, socket: Ne if (amount < to_send.len) { // we could not send all pending data so we need to buffer the extra data if (data.len > 0) { - buffer.write(data) catch bun.outOfMemory(); + bun.handleOom(buffer.write(data)); } // failed to send everything so we have backpressure return true; @@ -1308,7 +1308,7 @@ inline fn handleShortRead( if (to_copy.len > 0) { // this one will probably be another chunk, so we leave a little extra room - this.state.response_message_buffer.append(to_copy) catch bun.outOfMemory(); + bun.handleOom(this.state.response_message_buffer.append(to_copy)); } } @@ -1328,7 +1328,7 @@ pub fn handleOnDataHeaders( var needs_move = true; if (this.state.response_message_buffer.list.items.len > 0) { // this one probably won't be another chunk, so we use appendSliceExact() to avoid over-allocating - this.state.response_message_buffer.appendSliceExact(incoming_data) catch bun.outOfMemory(); + bun.handleOom(this.state.response_message_buffer.appendSliceExact(incoming_data)); to_read = this.state.response_message_buffer.list.items; needs_move = false; } diff --git a/src/http/HTTPThread.zig b/src/http/HTTPThread.zig index 90ba1c31f5..8ed4f2f52a 100644 --- a/src/http/HTTPThread.zig +++ b/src/http/HTTPThread.zig @@ -406,7 +406,7 @@ pub fn scheduleShutdown(this: *@This(), http: *AsyncHTTP) void { this.queued_shutdowns.append(bun.default_allocator, .{ .async_http_id = http.async_http_id, .is_tls = http.client.isHTTPS(), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } if (this.has_awoken.load(.monotonic)) this.loop.loop.wakeup(); @@ -422,7 +422,7 @@ pub fn scheduleRequestWrite(this: *@This(), http: *AsyncHTTP, messageType: Write .is_tls = http.client.isHTTPS(), .type = messageType, }, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } if (this.has_awoken.load(.monotonic)) this.loop.loop.wakeup(); @@ -431,7 +431,7 @@ pub fn scheduleRequestWrite(this: *@This(), http: *AsyncHTTP, messageType: Write pub fn scheduleProxyDeref(this: *@This(), proxy: *ProxyTunnel) void { // this is always called on the http thread { - this.queued_proxy_deref.append(bun.default_allocator, proxy) catch bun.outOfMemory(); + bun.handleOom(this.queued_proxy_deref.append(bun.default_allocator, proxy)); } if (this.has_awoken.load(.monotonic)) this.loop.loop.wakeup(); diff --git a/src/http/Headers.zig b/src/http/Headers.zig index 587ec0b5eb..e69701a3a8 100644 --- a/src/http/Headers.zig +++ b/src/http/Headers.zig @@ -99,9 +99,9 @@ pub fn fromPicoHttpHeaders(headers: []const picohttp.Header, allocator: std.mem. for (headers) |header| { buf_len += header.name.len + header.value.len; } - result.entries.ensureTotalCapacity(allocator, header_count) catch bun.outOfMemory(); + bun.handleOom(result.entries.ensureTotalCapacity(allocator, header_count)); result.entries.len = headers.len; - result.buf.ensureTotalCapacityPrecise(allocator, buf_len) catch bun.outOfMemory(); + bun.handleOom(result.buf.ensureTotalCapacityPrecise(allocator, buf_len)); result.buf.items.len = buf_len; var offset: u32 = 0; for (headers, 0..headers.len) |header, i| { @@ -147,9 +147,9 @@ pub fn from(fetch_headers_ref: ?*FetchHeaders, allocator: std.mem.Allocator, opt } break :brk false; }; - headers.entries.ensureTotalCapacity(allocator, header_count) catch bun.outOfMemory(); + bun.handleOom(headers.entries.ensureTotalCapacity(allocator, header_count)); headers.entries.len = header_count; - headers.buf.ensureTotalCapacityPrecise(allocator, buf_len) catch bun.outOfMemory(); + bun.handleOom(headers.buf.ensureTotalCapacityPrecise(allocator, buf_len)); headers.buf.items.len = buf_len; var sliced = headers.entries.slice(); var names = sliced.items(.name); diff --git a/src/http/MimeType.zig b/src/http/MimeType.zig index dd600e9e70..dcb643a445 100644 --- a/src/http/MimeType.zig +++ b/src/http/MimeType.zig @@ -291,7 +291,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .application, }; }, @@ -299,7 +299,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (strings.eqlComptimeIgnoreLen(category_, "font")) { if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .font, }; } @@ -323,7 +323,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .text, }; } @@ -332,7 +332,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (strings.eqlComptimeIgnoreLen(category_, "image")) { if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .image, }; } @@ -340,7 +340,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (strings.eqlComptimeIgnoreLen(category_, "audio")) { if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .audio, }; } @@ -348,7 +348,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (strings.eqlComptimeIgnoreLen(category_, "video")) { if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .video, }; } @@ -359,7 +359,7 @@ pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) Mime if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = if (allocator) |a| a.dupe(u8, str_) catch bun.outOfMemory() else str_, + .value = if (allocator) |a| bun.handleOom(a.dupe(u8, str_)) else str_, .category = .other, }; } diff --git a/src/http/ProxyTunnel.zig b/src/http/ProxyTunnel.zig index bf980343b4..c32c7e1770 100644 --- a/src/http/ProxyTunnel.zig +++ b/src/http/ProxyTunnel.zig @@ -201,7 +201,7 @@ pub fn write(this: *HTTPClient, encoded_data: []const u8) void { const pending = encoded_data[@intCast(written)..]; if (pending.len > 0) { // lets flush when we are truly writable - proxy.write_buffer.write(pending) catch bun.outOfMemory(); + bun.handleOom(proxy.write_buffer.write(pending)); } } } diff --git a/src/http/websocket_client.zig b/src/http/websocket_client.zig index bb26ec8b87..ce5321a24a 100644 --- a/src/http/websocket_client.zig +++ b/src/http/websocket_client.zig @@ -1185,8 +1185,8 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { return null; } - ws.send_buffer.ensureTotalCapacity(2048) catch bun.outOfMemory(); - ws.receive_buffer.ensureTotalCapacity(2048) catch bun.outOfMemory(); + bun.handleOom(ws.send_buffer.ensureTotalCapacity(2048)); + bun.handleOom(ws.receive_buffer.ensureTotalCapacity(2048)); ws.poll_ref.ref(globalThis.bunVM()); const buffered_slice: []u8 = buffered_data[0..buffered_data_len]; diff --git a/src/http/websocket_client/WebSocketUpgradeClient.zig b/src/http/websocket_client/WebSocketUpgradeClient.zig index 91e33c505b..c97e31665c 100644 --- a/src/http/websocket_client/WebSocketUpgradeClient.zig +++ b/src/http/websocket_client/WebSocketUpgradeClient.zig @@ -305,7 +305,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { var body = data; if (this.body.items.len > 0) { - this.body.appendSlice(bun.default_allocator, data) catch bun.outOfMemory(); + bun.handleOom(this.body.appendSlice(bun.default_allocator, data)); body = this.body.items; } @@ -327,7 +327,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { }, error.ShortRead => { if (this.body.items.len == 0) { - this.body.appendSlice(bun.default_allocator, data) catch bun.outOfMemory(); + bun.handleOom(this.body.appendSlice(bun.default_allocator, data)); } return; }, diff --git a/src/install/NetworkTask.zig b/src/install/NetworkTask.zig index fc0f989fd6..db025b7485 100644 --- a/src/install/NetworkTask.zig +++ b/src/install/NetworkTask.zig @@ -106,7 +106,7 @@ pub fn forManifest( allocator, "Failed to join registry {} and package {} URLs", .{ bun.fmt.QuotedFormatter{ .text = scope.url.href }, bun.fmt.QuotedFormatter{ .text = name } }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { this.package_manager.log.addWarningFmt( null, @@ -114,7 +114,7 @@ pub fn forManifest( allocator, "Failed to join registry {} and package {} URLs", .{ bun.fmt.QuotedFormatter{ .text = scope.url.href }, bun.fmt.QuotedFormatter{ .text = name } }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } return error.InvalidURL; } @@ -127,7 +127,7 @@ pub fn forManifest( allocator, "Registry URL must be http:// or https://\nReceived: \"{}\"", .{tmp}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { this.package_manager.log.addWarningFmt( null, @@ -135,7 +135,7 @@ pub fn forManifest( allocator, "Registry URL must be http:// or https://\nReceived: \"{}\"", .{tmp}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } return error.InvalidURL; } diff --git a/src/install/PackageInstall.zig b/src/install/PackageInstall.zig index b60c23cde4..3446d35094 100644 --- a/src/install/PackageInstall.zig +++ b/src/install/PackageInstall.zig @@ -519,7 +519,7 @@ pub const PackageInstall = struct { &[_]bun.OSPathSlice{comptime bun.OSPathLiteral("node_modules")} else &[_]bun.OSPathSlice{}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); if (!Environment.isWindows) { state.subdir = destbase.makeOpenPath(bun.span(destpath), .{ @@ -750,7 +750,7 @@ pub const PackageInstall = struct { const allocation_size = (src.len) + 1 + (dest.len) + 1; - const combined = bun.default_allocator.alloc(u16, allocation_size) catch bun.outOfMemory(); + const combined = bun.handleOom(bun.default_allocator.alloc(u16, allocation_size)); var remaining = combined; @memcpy(remaining[0..src.len], src); remaining[src.len] = 0; @@ -1180,7 +1180,7 @@ pub const PackageInstall = struct { } }; var task = UninstallTask.new(.{ - .absolute_path = bun.default_allocator.dupeZ(u8, bun.path.joinAbsString(FileSystem.instance.top_level_dir, &.{ this.node_modules.path.items, temp_path }, .auto)) catch bun.outOfMemory(), + .absolute_path = bun.handleOom(bun.default_allocator.dupeZ(u8, bun.path.joinAbsString(FileSystem.instance.top_level_dir, &.{ this.node_modules.path.items, temp_path }, .auto))), }); PackageManager.get().incrementPendingTasks(1); PackageManager.get().thread_pool.schedule(bun.ThreadPool.Batch.from(&task.task)); diff --git a/src/install/PackageInstaller.zig b/src/install/PackageInstaller.zig index e6a3e6076c..ee0ad7e6bc 100644 --- a/src/install/PackageInstaller.zig +++ b/src/install/PackageInstaller.zig @@ -310,7 +310,7 @@ pub const PackageInstaller = struct { "Failed to link {s}: {s}", .{ alias, @errorName(err) }, .{}, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } if (this.options.enable.fail_early) { @@ -342,7 +342,7 @@ pub const PackageInstaller = struct { .node_modules, ); - this.node_modules.path.appendSlice(rel_path) catch bun.outOfMemory(); + bun.handleOom(this.node_modules.path.appendSlice(rel_path)); this.linkTreeBins(tree, @intCast(tree_id), &link_target_buf, &link_dest_buf, &link_rel_buf, log_level); } @@ -536,7 +536,7 @@ pub const PackageInstaller = struct { // fixes an assertion failure where a transitive dependency is a git dependency newly added to the lockfile after the list of dependencies has been resized // this assertion failure would also only happen after the lockfile has been written to disk and the summary is being printed. if (this.successfully_installed.bit_length < this.lockfile.packages.len) { - const new = Bitset.initEmpty(bun.default_allocator, this.lockfile.packages.len) catch bun.outOfMemory(); + const new = bun.handleOom(Bitset.initEmpty(bun.default_allocator, this.lockfile.packages.len)); var old = this.successfully_installed; defer old.deinit(bun.default_allocator); old.copyInto(new); @@ -908,7 +908,7 @@ pub const PackageInstaller = struct { const context: TaskCallbackContext = .{ .dependency_install_context = .{ .tree_id = this.current_tree_id, - .path = this.node_modules.path.clone() catch bun.outOfMemory(), + .path = bun.handleOom(this.node_modules.path.clone()), .dependency_id = dependency_id, }, }; @@ -1015,7 +1015,7 @@ pub const PackageInstaller = struct { task.callback.apply.install_context = .{ .dependency_id = dependency_id, .tree_id = this.current_tree_id, - .path = this.node_modules.path.clone() catch bun.outOfMemory(), + .path = bun.handleOom(this.node_modules.path.clone()), }; this.manager.enqueuePatchTask(task); return; @@ -1026,8 +1026,8 @@ pub const PackageInstaller = struct { this.trees[this.current_tree_id].pending_installs.append(this.manager.allocator, .{ .dependency_id = dependency_id, .tree_id = this.current_tree_id, - .path = this.node_modules.path.clone() catch bun.outOfMemory(), - }) catch bun.outOfMemory(); + .path = bun.handleOom(this.node_modules.path.clone()), + }) catch |err| bun.handleOom(err); return; } @@ -1087,7 +1087,7 @@ pub const PackageInstaller = struct { } if (this.bins[package_id].tag != .none) { - this.trees[this.current_tree_id].binaries.add(dependency_id) catch bun.outOfMemory(); + bun.handleOom(this.trees[this.current_tree_id].binaries.add(dependency_id)); } const dep = this.lockfile.buffers.dependencies.items[dependency_id]; @@ -1114,11 +1114,11 @@ pub const PackageInstaller = struct { if (is_trusted_through_update_request) { this.manager.trusted_deps_to_add_to_package_json.append( this.manager.allocator, - this.manager.allocator.dupe(u8, alias.slice(this.lockfile.buffers.string_bytes.items)) catch bun.outOfMemory(), - ) catch bun.outOfMemory(); + bun.handleOom(this.manager.allocator.dupe(u8, alias.slice(this.lockfile.buffers.string_bytes.items))), + ) catch |err| bun.handleOom(err); if (this.lockfile.trusted_dependencies == null) this.lockfile.trusted_dependencies = .{}; - this.lockfile.trusted_dependencies.?.put(this.manager.allocator, truncated_dep_name_hash, {}) catch bun.outOfMemory(); + this.lockfile.trusted_dependencies.?.put(this.manager.allocator, truncated_dep_name_hash, {}) catch |err| bun.handleOom(err); } } } @@ -1149,7 +1149,7 @@ pub const PackageInstaller = struct { resolution.fmt(this.lockfile.buffers.string_bytes.items, .posix), }); } - const entry = this.summary.packages_with_blocked_scripts.getOrPut(this.manager.allocator, truncated_dep_name_hash) catch bun.outOfMemory(); + const entry = bun.handleOom(this.summary.packages_with_blocked_scripts.getOrPut(this.manager.allocator, truncated_dep_name_hash)); if (!entry.found_existing) entry.value_ptr.* = 0; entry.value_ptr.* += count; } @@ -1241,7 +1241,7 @@ pub const PackageInstaller = struct { } } else { if (this.bins[package_id].tag != .none) { - this.trees[this.current_tree_id].binaries.add(dependency_id) catch bun.outOfMemory(); + bun.handleOom(this.trees[this.current_tree_id].binaries.add(dependency_id)); } var destination_dir: LazyPackageDestinationDir = .{ @@ -1286,13 +1286,13 @@ pub const PackageInstaller = struct { if (is_trusted_through_update_request) { this.manager.trusted_deps_to_add_to_package_json.append( this.manager.allocator, - this.manager.allocator.dupe(u8, alias.slice(this.lockfile.buffers.string_bytes.items)) catch bun.outOfMemory(), - ) catch bun.outOfMemory(); + bun.handleOom(this.manager.allocator.dupe(u8, alias.slice(this.lockfile.buffers.string_bytes.items))), + ) catch |err| bun.handleOom(err); } if (add_to_lockfile) { if (this.lockfile.trusted_dependencies == null) this.lockfile.trusted_dependencies = .{}; - this.lockfile.trusted_dependencies.?.put(this.manager.allocator, truncated_dep_name_hash, {}) catch bun.outOfMemory(); + this.lockfile.trusted_dependencies.?.put(this.manager.allocator, truncated_dep_name_hash, {}) catch |err| bun.handleOom(err); } } } @@ -1367,7 +1367,7 @@ pub const PackageInstaller = struct { .list = scripts_list.?, .tree_id = this.current_tree_id, .optional = optional, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return true; } diff --git a/src/install/PackageManager.zig b/src/install/PackageManager.zig index f9055beb8f..6424abef2b 100644 --- a/src/install/PackageManager.zig +++ b/src/install/PackageManager.zig @@ -356,7 +356,7 @@ pub var configureEnvForScriptsOnce = bun.once(struct { { var node_path: bun.PathBuffer = undefined; if (this.env.getNodePath(this_transpiler.fs, &node_path)) |node_pathZ| { - _ = try this.env.loadNodeJSConfig(this_transpiler.fs, bun.default_allocator.dupe(u8, node_pathZ) catch bun.outOfMemory()); + _ = try this.env.loadNodeJSConfig(this_transpiler.fs, bun.handleOom(bun.default_allocator.dupe(u8, node_pathZ))); } else brk: { const current_path = this.env.get("PATH") orelse ""; var PATH = try std.ArrayList(u8).initCapacity(bun.default_allocator, current_path.len); @@ -364,7 +364,7 @@ pub var configureEnvForScriptsOnce = bun.once(struct { var bun_path: string = ""; RunCommand.createFakeTemporaryNodeExecutable(&PATH, &bun_path) catch break :brk; try this.env.map.put("PATH", PATH.items); - _ = try this.env.loadNodeJSConfig(this_transpiler.fs, bun.default_allocator.dupe(u8, bun_path) catch bun.outOfMemory()); + _ = try this.env.loadNodeJSConfig(this_transpiler.fs, bun.handleOom(bun.default_allocator.dupe(u8, bun_path))); } } @@ -435,7 +435,7 @@ const Holder = struct { }; pub fn allocatePackageManager() void { - Holder.ptr = bun.default_allocator.create(PackageManager) catch bun.outOfMemory(); + Holder.ptr = bun.handleOom(bun.default_allocator.create(PackageManager)); } pub fn get() *PackageManager { @@ -583,14 +583,14 @@ pub fn init( @memcpy(cwd_buf[0..top_level_dir_no_trailing_slash.len], top_level_dir_no_trailing_slash); } - var original_package_json_path_buf = std.ArrayListUnmanaged(u8).initCapacity(ctx.allocator, top_level_dir_no_trailing_slash.len + "/package.json".len + 1) catch bun.outOfMemory(); + var original_package_json_path_buf = bun.handleOom(std.ArrayListUnmanaged(u8).initCapacity(ctx.allocator, top_level_dir_no_trailing_slash.len + "/package.json".len + 1)); original_package_json_path_buf.appendSliceAssumeCapacity(top_level_dir_no_trailing_slash); original_package_json_path_buf.appendSliceAssumeCapacity(std.fs.path.sep_str ++ "package.json"); original_package_json_path_buf.appendAssumeCapacity(0); var original_package_json_path: stringZ = original_package_json_path_buf.items[0 .. top_level_dir_no_trailing_slash.len + "/package.json".len :0]; const original_cwd = strings.withoutSuffixComptime(original_package_json_path, std.fs.path.sep_str ++ "package.json"); - const original_cwd_clone = ctx.allocator.dupe(u8, original_cwd) catch bun.outOfMemory(); + const original_cwd_clone = bun.handleOom(ctx.allocator.dupe(u8, original_cwd)); var workspace_names = Package.WorkspaceMap.init(ctx.allocator); var workspace_package_json_cache: WorkspacePackageJSONCache = .{ @@ -795,7 +795,7 @@ pub fn init( }; bun.ini.loadNpmrcConfig(ctx.allocator, ctx.install orelse brk: { - const install_ = ctx.allocator.create(Api.BunInstall) catch bun.outOfMemory(); + const install_ = bun.handleOom(ctx.allocator.create(Api.BunInstall)); install_.* = std.mem.zeroes(Api.BunInstall); ctx.install = install_; break :brk install_; @@ -807,7 +807,7 @@ pub fn init( ), ".npmrc" }); } else { bun.ini.loadNpmrcConfig(ctx.allocator, ctx.install orelse brk: { - const install_ = ctx.allocator.create(Api.BunInstall) catch bun.outOfMemory(); + const install_ = bun.handleOom(ctx.allocator.create(Api.BunInstall)); install_.* = std.mem.zeroes(Api.BunInstall); ctx.install = install_; break :brk install_; @@ -1009,7 +1009,7 @@ pub fn initWithRuntimeOnce( // var progress = Progress{}; // var node = progress.start(name: []const u8, estimated_total_items: usize) const top_level_dir_no_trailing_slash = strings.withoutTrailingSlash(Fs.FileSystem.instance.top_level_dir); - var original_package_json_path = allocator.allocSentinel(u8, top_level_dir_no_trailing_slash.len + "/package.json".len, 0) catch bun.outOfMemory(); + var original_package_json_path = bun.handleOom(allocator.allocSentinel(u8, top_level_dir_no_trailing_slash.len + "/package.json".len, 0)); @memcpy(original_package_json_path[0..top_level_dir_no_trailing_slash.len], top_level_dir_no_trailing_slash); @memcpy(original_package_json_path[top_level_dir_no_trailing_slash.len..][0.."/package.json".len], "/package.json"); @@ -1039,7 +1039,7 @@ pub fn initWithRuntimeOnce( .original_package_json_path = original_package_json_path[0..original_package_json_path.len :0], .subcommand = .install, }; - manager.lockfile = allocator.create(Lockfile) catch bun.outOfMemory(); + manager.lockfile = bun.handleOom(allocator.create(Lockfile)); if (Output.enable_ansi_colors_stderr) { manager.progress = Progress{}; diff --git a/src/install/PackageManager/PackageJSONEditor.zig b/src/install/PackageManager/PackageJSONEditor.zig index 43f0225a34..a37af47613 100644 --- a/src/install/PackageManager/PackageJSONEditor.zig +++ b/src/install/PackageManager/PackageJSONEditor.zig @@ -243,7 +243,7 @@ pub fn editUpdateNoArgs( } const key_str = try key.asStringCloned(allocator) orelse unreachable; - const entry = manager.updating_packages.getOrPut(allocator, key_str) catch bun.outOfMemory(); + const entry = bun.handleOom(manager.updating_packages.getOrPut(allocator, key_str)); // If a dependency is present in more than one dependency group, only one of it's versions // will be updated. The group is determined by the order of `dependency_groups`, the same @@ -259,9 +259,9 @@ pub fn editUpdateNoArgs( if (manager.options.do.update_to_latest) { // is it an aliased package const temp_version = if (alias_at_index) |at_index| - std.fmt.allocPrint(allocator, "{s}@latest", .{version_literal[0..at_index]}) catch bun.outOfMemory() + bun.handleOom(std.fmt.allocPrint(allocator, "{s}@latest", .{version_literal[0..at_index]})) else - allocator.dupe(u8, "latest") catch bun.outOfMemory(); + bun.handleOom(allocator.dupe(u8, "latest")); dep.value = Expr.allocate(allocator, E.String, .{ .data = temp_version, @@ -432,7 +432,7 @@ pub fn edit( if (tag != .npm and tag != .dist_tag) break :add_packages_to_update; - const entry = manager.updating_packages.getOrPut(allocator, name) catch bun.outOfMemory(); + const entry = bun.handleOom(manager.updating_packages.getOrPut(allocator, name)); // first come, first serve if (entry.found_existing) break :add_packages_to_update; diff --git a/src/install/PackageManager/PackageManagerDirectories.zig b/src/install/PackageManager/PackageManagerDirectories.zig index dd4cc9b04a..b12a25039c 100644 --- a/src/install/PackageManager/PackageManagerDirectories.zig +++ b/src/install/PackageManager/PackageManagerDirectories.zig @@ -15,7 +15,7 @@ pub inline fn getTemporaryDirectory(this: *PackageManager) std.fs.Dir { this.temp_dir_ = ensureTemporaryDirectory(this); var pathbuf: bun.PathBuffer = undefined; const temp_dir_path = bun.getFdPathZ(.fromStdDir(this.temp_dir_.?), &pathbuf) catch Output.panic("Unable to read temporary directory path", .{}); - this.temp_dir_path = bun.default_allocator.dupeZ(u8, temp_dir_path) catch bun.outOfMemory(); + this.temp_dir_path = bun.handleOom(bun.default_allocator.dupeZ(u8, temp_dir_path)); break :brk this.temp_dir_.?; }; } @@ -24,7 +24,7 @@ noinline fn ensureCacheDirectory(this: *PackageManager) std.fs.Dir { loop: while (true) { if (this.options.enable.cache) { const cache_dir = fetchCacheDirectoryPath(this.env, &this.options); - this.cache_directory_path = this.allocator.dupeZ(u8, cache_dir.path) catch bun.outOfMemory(); + this.cache_directory_path = bun.handleOom(this.allocator.dupeZ(u8, cache_dir.path)); return std.fs.cwd().makeOpenPath(cache_dir.path, .{}) catch { this.options.enable.cache = false; @@ -40,7 +40,7 @@ noinline fn ensureCacheDirectory(this: *PackageManager) std.fs.Dir { ".cache", }, .auto, - )) catch bun.outOfMemory(); + )) catch |err| bun.handleOom(err); return std.fs.cwd().makeOpenPath("node_modules/.cache", .{}) catch |err| { Output.prettyErrorln("error: bun is unable to write files: {s}", .{@errorName(err)}); @@ -383,7 +383,7 @@ pub fn globalLinkDir(this: *PackageManager) std.fs.Dir { Output.err(err, "failed to get the full path of the global directory", .{}); Global.exit(1); }; - this.global_link_dir_path = Fs.FileSystem.DirnameStore.instance.append([]const u8, _path) catch bun.outOfMemory(); + this.global_link_dir_path = bun.handleOom(Fs.FileSystem.DirnameStore.instance.append([]const u8, _path)); break :brk this.global_link_dir.?; }; } diff --git a/src/install/PackageManager/PackageManagerEnqueue.zig b/src/install/PackageManager/PackageManagerEnqueue.zig index b93bbc3e98..a24bb80cc5 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.zig +++ b/src/install/PackageManager/PackageManagerEnqueue.zig @@ -1420,7 +1420,7 @@ fn getOrPutResolvedPackageWithFindResult( .{ .pkg_id = package.meta.id, .dependency_id = dependency_id, - .url = this.allocator.dupe(u8, manifest.str(&find_result.package.tarball_url)) catch bun.outOfMemory(), + .url = bun.handleOom(this.allocator.dupe(u8, manifest.str(&find_result.package.tarball_url))), }, ), }, @@ -1670,7 +1670,7 @@ fn getOrPutResolvedPackage( builder.count(name_slice); builder.count(folder_path); - builder.allocate() catch bun.outOfMemory(); + bun.handleOom(builder.allocate()); name_slice = this.lockfile.str(&name); folder_path = this.lockfile.str(&version.value.folder); @@ -1689,7 +1689,7 @@ fn getOrPutResolvedPackage( } // these are always new - package = this.lockfile.appendPackage(package) catch bun.outOfMemory(); + package = bun.handleOom(this.lockfile.appendPackage(package)); break :res .{ .new_package_id = package.meta.id, diff --git a/src/install/PackageManager/PackageManagerLifecycle.zig b/src/install/PackageManager/PackageManagerLifecycle.zig index 59e76aeed5..4f14481899 100644 --- a/src/install/PackageManager/PackageManagerLifecycle.zig +++ b/src/install/PackageManager/PackageManagerLifecycle.zig @@ -13,7 +13,7 @@ pub const LifecycleScriptTimeLog = struct { pub fn appendConcurrent(log: *LifecycleScriptTimeLog, allocator: std.mem.Allocator, entry: Entry) void { log.mutex.lock(); defer log.mutex.unlock(); - log.list.append(allocator, entry) catch bun.outOfMemory(); + bun.handleOom(log.list.append(allocator, entry)); } /// this can be called if .start was never called @@ -54,7 +54,7 @@ pub fn ensurePreinstallStateListCapacity(this: *PackageManager, count: usize) vo } const offset = this.preinstall_state.items.len; - this.preinstall_state.ensureTotalCapacity(this.allocator, count) catch bun.outOfMemory(); + bun.handleOom(this.preinstall_state.ensureTotalCapacity(this.allocator, count)); this.preinstall_state.expandToCapacity(); @memset(this.preinstall_state.items[offset..], PreinstallState.unknown); } @@ -139,7 +139,7 @@ pub fn determinePreinstallState( // 4. rename temp dir to `folder_path` if (patch_hash != null) { const non_patched_path_ = folder_path[0 .. std.mem.indexOf(u8, folder_path, "_patch_hash=") orelse @panic("Expected folder path to contain `patch_hash=`, this is a bug in Bun. Please file a GitHub issue.")]; - const non_patched_path = manager.lockfile.allocator.dupeZ(u8, non_patched_path_) catch bun.outOfMemory(); + const non_patched_path = bun.handleOom(manager.lockfile.allocator.dupeZ(u8, non_patched_path_)); defer manager.lockfile.allocator.free(non_patched_path); if (manager.isFolderInCache(non_patched_path)) { manager.setPreinstallState(pkg.meta.id, manager.lockfile, .apply_patch); @@ -329,7 +329,7 @@ pub fn findTrustedDependenciesFromUpdateRequests(this: *PackageManager) std.Auto const package_id = this.lockfile.buffers.resolutions.items[dep_id]; if (package_id == invalid_package_id) continue; - const entry = set.getOrPut(this.lockfile.allocator, @truncate(root_dep.name_hash)) catch bun.outOfMemory(); + const entry = bun.handleOom(set.getOrPut(this.lockfile.allocator, @truncate(root_dep.name_hash))); if (!entry.found_existing) { const dependency_slice = parts.items(.dependencies)[package_id]; addDependenciesToSet(&set, this.lockfile, dependency_slice); @@ -356,7 +356,7 @@ fn addDependenciesToSet( if (package_id == invalid_package_id) continue; const dep = lockfile.buffers.dependencies.items[dep_id]; - const entry = names.getOrPut(lockfile.allocator, @truncate(dep.name_hash)) catch bun.outOfMemory(); + const entry = bun.handleOom(names.getOrPut(lockfile.allocator, @truncate(dep.name_hash))); if (!entry.found_existing) { const dependency_slice = lockfile.packages.items(.dependencies)[package_id]; addDependenciesToSet(names, lockfile, dependency_slice); diff --git a/src/install/PackageManager/UpdateRequest.zig b/src/install/PackageManager/UpdateRequest.zig index 7273053dc5..eeb5476ed5 100644 --- a/src/install/PackageManager/UpdateRequest.zig +++ b/src/install/PackageManager/UpdateRequest.zig @@ -125,7 +125,7 @@ fn parseWithError( // add // remove outer: for (positionals) |positional| { - var input: []u8 = bun.default_allocator.dupe(u8, std.mem.trim(u8, positional, " \n\r\t")) catch bun.outOfMemory(); + var input: []u8 = bun.handleOom(bun.default_allocator.dupe(u8, std.mem.trim(u8, positional, " \n\r\t"))); { var temp: [2048]u8 = undefined; const len = std.mem.replace(u8, input, "\\\\", "/", &temp); @@ -174,7 +174,7 @@ fn parseWithError( } else { log.addErrorFmt(null, logger.Loc.Empty, allocator, "unrecognised dependency format: {s}", .{ positional, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } return error.UnrecognizedDependencyFormat; @@ -206,7 +206,7 @@ fn parseWithError( } else { log.addErrorFmt(null, logger.Loc.Empty, allocator, "unrecognised dependency format: {s}", .{ positional, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } return error.UnrecognizedDependencyFormat; @@ -229,7 +229,7 @@ fn parseWithError( for (update_requests.items) |*prev| { if (prev.name_hash == request.name_hash and request.name.len == prev.name.len) continue :outer; } - update_requests.append(allocator, request) catch bun.outOfMemory(); + bun.handleOom(update_requests.append(allocator, request)); } return update_requests.items; diff --git a/src/install/PackageManager/WorkspacePackageJSONCache.zig b/src/install/PackageManager/WorkspacePackageJSONCache.zig index 07ea1f2bb0..2cd7a3b506 100644 --- a/src/install/PackageManager/WorkspacePackageJSONCache.zig +++ b/src/install/PackageManager/WorkspacePackageJSONCache.zig @@ -49,12 +49,12 @@ pub fn getWithPath( break :brk buf[0..abs_package_json_path.len]; }; - const entry = this.map.getOrPut(allocator, path) catch bun.outOfMemory(); + const entry = bun.handleOom(this.map.getOrPut(allocator, path)); if (entry.found_existing) { return .{ .entry = entry.value_ptr }; } - const key = allocator.dupeZ(u8, path) catch bun.outOfMemory(); + const key = bun.handleOom(allocator.dupeZ(u8, path)); entry.key_ptr.* = key; const source = &(bun.sys.File.toSource(key, allocator, .{}).unwrap() catch |err| { @@ -85,7 +85,7 @@ pub fn getWithPath( }; entry.value_ptr.* = .{ - .root = json.root.deepClone(bun.default_allocator) catch bun.outOfMemory(), + .root = bun.handleOom(json.root.deepClone(bun.default_allocator)), .source = source.*, .indentation = json.indentation, }; @@ -112,7 +112,7 @@ pub fn getWithSource( break :brk buf[0..source.path.text.len]; }; - const entry = this.map.getOrPut(allocator, path) catch bun.outOfMemory(); + const entry = bun.handleOom(this.map.getOrPut(allocator, path)); if (entry.found_existing) { return .{ .entry = entry.value_ptr }; } @@ -138,12 +138,12 @@ pub fn getWithSource( }; entry.value_ptr.* = .{ - .root = json.root.deepClone(allocator) catch bun.outOfMemory(), + .root = bun.handleOom(json.root.deepClone(allocator)), .source = source.*, .indentation = json.indentation, }; - entry.key_ptr.* = allocator.dupe(u8, path) catch bun.outOfMemory(); + entry.key_ptr.* = bun.handleOom(allocator.dupe(u8, path)); return .{ .entry = entry.value_ptr }; } diff --git a/src/install/PackageManager/install_with_manager.zig b/src/install/PackageManager/install_with_manager.zig index 45181f339b..c5114032e3 100644 --- a/src/install/PackageManager/install_with_manager.zig +++ b/src/install/PackageManager/install_with_manager.zig @@ -109,7 +109,7 @@ pub fn installWithManager( const tag_total = original.tag.pre.len() + original.tag.build.len(); if (tag_total > 0) { // clone because don't know if lockfile buffer will reallocate - const tag_buf = manager.allocator.alloc(u8, tag_total) catch bun.outOfMemory(); + const tag_buf = bun.handleOom(manager.allocator.alloc(u8, tag_total)); var ptr = tag_buf; original.tag = original_resolution.value.npm.version.tag.cloneInto( lockfile.buffers.string_bytes.items, @@ -605,7 +605,7 @@ pub fn installWithManager( @field(manager.lockfile.scripts, Lockfile.Scripts.names[i]).append( manager.lockfile.allocator, entry, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } @@ -626,7 +626,7 @@ pub fn installWithManager( @field(manager.lockfile.scripts, Lockfile.Scripts.names[i]).append( manager.lockfile.allocator, entry, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } } } @@ -643,7 +643,7 @@ pub fn installWithManager( if (manager.options.enable.frozen_lockfile and load_result != .not_found) frozen_lockfile: { if (load_result.loadedFromTextLockfile()) { - if (manager.lockfile.eql(lockfile_before_clean, packages_len_before_install, manager.allocator) catch bun.outOfMemory()) { + if (bun.handleOom(manager.lockfile.eql(lockfile_before_clean, packages_len_before_install, manager.allocator))) { break :frozen_lockfile; } } else { diff --git a/src/install/PackageManager/patchPackage.zig b/src/install/PackageManager/patchPackage.zig index 924e5c0e07..01093d36ca 100644 --- a/src/install/PackageManager/patchPackage.zig +++ b/src/install/PackageManager/patchPackage.zig @@ -454,8 +454,8 @@ pub fn doPatchCommit( Global.crash(); } - const patch_key = std.fmt.allocPrint(manager.allocator, "{s}", .{resolution_label}) catch bun.outOfMemory(); - const patchfile_path = manager.allocator.dupe(u8, path_in_patches_dir) catch bun.outOfMemory(); + const patch_key = bun.handleOom(std.fmt.allocPrint(manager.allocator, "{s}", .{resolution_label})); + const patchfile_path = bun.handleOom(manager.allocator.dupe(u8, path_in_patches_dir)); _ = bun.sys.unlink(bun.path.joinZ(&[_][]const u8{ changes_dir, ".bun-patch-tag" }, .auto)); return .{ @@ -527,7 +527,7 @@ fn escapePatchFilename(allocator: std.mem.Allocator, name: []const u8) ?[]const var count: usize = 0; for (name) |c| count += if (ESCAPE_TABLE[c].escaped()) |e| e.len else 1; if (count == name.len) return null; - var buf = allocator.alloc(u8, count) catch bun.outOfMemory(); + var buf = bun.handleOom(allocator.alloc(u8, count)); var i: usize = 0; for (name) |c| { const e = ESCAPE_TABLE[c].escaped() orelse &[_]u8{c}; @@ -839,7 +839,7 @@ fn overwritePackageInNodeModulesFolder( var pkg_in_cache_dir = try cache_dir.openDir(cache_dir_subpath, .{ .iterate = true }); defer pkg_in_cache_dir.close(); - var walker = Walker.walk(.fromStdDir(pkg_in_cache_dir), manager.allocator, &.{}, IGNORED_PATHS) catch bun.outOfMemory(); + var walker = bun.handleOom(Walker.walk(.fromStdDir(pkg_in_cache_dir), manager.allocator, &.{}, IGNORED_PATHS)); defer walker.deinit(); var buf1: if (bun.Environment.isWindows) bun.WPathBuffer else void = undefined; @@ -924,7 +924,7 @@ fn pkgInfoForNameAndVersion( version: ?[]const u8, ) struct { PackageID, Lockfile.Tree.Iterator(.node_modules).Next } { var sfb = std.heap.stackFallback(@sizeOf(IdPair) * 4, lockfile.allocator); - var pairs = std.ArrayList(IdPair).initCapacity(sfb.get(), 8) catch bun.outOfMemory(); + var pairs = bun.handleOom(std.ArrayList(IdPair).initCapacity(sfb.get(), 8)); defer pairs.deinit(); const name_hash = String.Builder.stringHash(name); @@ -942,10 +942,10 @@ fn pkgInfoForNameAndVersion( if (version) |v| { const label = std.fmt.bufPrint(buf[0..], "{}", .{pkg.resolution.fmt(strbuf, .posix)}) catch @panic("Resolution name too long"); if (std.mem.eql(u8, label, v)) { - pairs.append(.{ @intCast(dep_id), pkg_id }) catch bun.outOfMemory(); + bun.handleOom(pairs.append(.{ @intCast(dep_id), pkg_id })); } } else { - pairs.append(.{ @intCast(dep_id), pkg_id }) catch bun.outOfMemory(); + bun.handleOom(pairs.append(.{ @intCast(dep_id), pkg_id })); } } @@ -1069,7 +1069,7 @@ fn pathArgumentRelativeToRootWorkspacePackage(manager: *PackageManager, lockfile if (workspace_package_id == 0) return null; const workspace_res = lockfile.packages.items(.resolution)[workspace_package_id]; const rel_path: []const u8 = workspace_res.value.workspace.slice(lockfile.buffers.string_bytes.items); - return bun.default_allocator.dupe(u8, bun.path.join(&[_][]const u8{ rel_path, argument }, .posix)) catch bun.outOfMemory(); + return bun.handleOom(bun.default_allocator.dupe(u8, bun.path.join(&[_][]const u8{ rel_path, argument }, .posix))); } const PatchArgKind = enum { diff --git a/src/install/PackageManager/processDependencyList.zig b/src/install/PackageManager/processDependencyList.zig index 805bda10ec..944db33d1b 100644 --- a/src/install/PackageManager/processDependencyList.zig +++ b/src/install/PackageManager/processDependencyList.zig @@ -121,7 +121,7 @@ pub fn processExtractedTarballPackage( builder.count(new_name); resolver.count(*Lockfile.StringBuilder, &builder, undefined); - builder.allocate() catch bun.outOfMemory(); + bun.handleOom(builder.allocate()); const name = builder.append(ExternalString, new_name); pkg.name = name.value; @@ -137,7 +137,7 @@ pub fn processExtractedTarballPackage( package_id.* = package.meta.id; if (package.dependencies.len > 0) { - manager.lockfile.scratch.dependency_list_queue.writeItem(package.dependencies) catch bun.outOfMemory(); + bun.handleOom(manager.lockfile.scratch.dependency_list_queue.writeItem(package.dependencies)); } return package; @@ -192,7 +192,7 @@ pub fn processExtractedTarballPackage( package_id.* = package.meta.id; if (package.dependencies.len > 0) { - manager.lockfile.scratch.dependency_list_queue.writeItem(package.dependencies) catch bun.outOfMemory(); + bun.handleOom(manager.lockfile.scratch.dependency_list_queue.writeItem(package.dependencies)); } return package; diff --git a/src/install/PackageManager/runTasks.zig b/src/install/PackageManager/runTasks.zig index 9d7c09fa5b..649dc3007b 100644 --- a/src/install/PackageManager/runTasks.zig +++ b/src/install/PackageManager/runTasks.zig @@ -191,7 +191,7 @@ pub fn runTasks( manager.allocator, fmt, .{ @errorName(err), name.slice() }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } else { manager.log.addWarningFmt( null, @@ -199,7 +199,7 @@ pub fn runTasks( manager.allocator, fmt, .{ @errorName(err), name.slice() }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } if (manager.subcommand != .remove) { @@ -247,7 +247,7 @@ pub fn runTasks( manager.allocator, "GET {s} - {d}", .{ metadata.url, response.status_code }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { manager.log.addWarningFmt( null, @@ -255,7 +255,7 @@ pub fn runTasks( manager.allocator, "GET {s} - {d}", .{ metadata.url, response.status_code }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (manager.subcommand != .remove) { for (manager.update_requests) |*request| { @@ -387,7 +387,7 @@ pub fn runTasks( extract.name.slice(), extract.resolution.fmt(manager.lockfile.buffers.string_bytes.items, .auto), }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } else { manager.log.addWarningFmt( null, @@ -399,7 +399,7 @@ pub fn runTasks( extract.name.slice(), extract.resolution.fmt(manager.lockfile.buffers.string_bytes.items, .auto), }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } if (manager.subcommand != .remove) { for (manager.update_requests) |*request| { @@ -451,7 +451,7 @@ pub fn runTasks( metadata.url, response.status_code, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } else { manager.log.addWarningFmt( null, @@ -462,7 +462,7 @@ pub fn runTasks( metadata.url, response.status_code, }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } if (manager.subcommand != .remove) { for (manager.update_requests) |*request| { @@ -537,7 +537,7 @@ pub fn runTasks( @errorName(err), name.slice(), }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } continue; @@ -607,7 +607,7 @@ pub fn runTasks( @errorName(err), alias, }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } continue; } @@ -727,7 +727,7 @@ pub fn runTasks( @errorName(err), name, }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); } continue; } @@ -801,7 +801,7 @@ pub fn runTasks( @errorName(err), alias.slice(), }, - ) catch bun.outOfMemory(); + ) catch |e| bun.handleOom(e); continue; } @@ -1006,7 +1006,7 @@ pub fn allocGitHubURL(this: *const PackageManager, repository: *const Repository } pub fn hasCreatedNetworkTask(this: *PackageManager, task_id: Task.Id, is_required: bool) bool { - const gpe = this.network_dedupe_map.getOrPut(task_id) catch bun.outOfMemory(); + const gpe = bun.handleOom(this.network_dedupe_map.getOrPut(task_id)); // if there's an existing network task that is optional, we want to make it non-optional if this one would be required gpe.value_ptr.is_required = if (!gpe.found_existing) @@ -1060,7 +1060,7 @@ pub fn generateNetworkTaskForTarball( this.lockfile.str(&package.name), *FileSystem.FilenameStore, FileSystem.FilenameStore.instance, - ) catch bun.outOfMemory(), + ) catch |err| bun.handleOom(err), .resolution = package.resolution, .cache_dir = this.getCacheDirectory(), .temp_dir = this.getTemporaryDirectory(), @@ -1070,7 +1070,7 @@ pub fn generateNetworkTaskForTarball( url, *FileSystem.FilenameStore, FileSystem.FilenameStore.instance, - ) catch bun.outOfMemory(), + ) catch |err| bun.handleOom(err), }, scope, authorization, diff --git a/src/install/PackageManager/security_scanner.zig b/src/install/PackageManager/security_scanner.zig index 97ad580d02..8aa24ef3b2 100644 --- a/src/install/PackageManager/security_scanner.zig +++ b/src/install/PackageManager/security_scanner.zig @@ -398,13 +398,13 @@ pub const SecurityScanSubprocess = struct { } pub fn onStderrChunk(this: *SecurityScanSubprocess, chunk: []const u8) void { - this.stderr_data.appendSlice(chunk) catch bun.outOfMemory(); + bun.handleOom(this.stderr_data.appendSlice(chunk)); } pub fn getReadBuffer(this: *SecurityScanSubprocess) []u8 { const available = this.ipc_data.unusedCapacitySlice(); if (available.len < 4096) { - this.ipc_data.ensureTotalCapacity(this.ipc_data.capacity + 4096) catch bun.outOfMemory(); + bun.handleOom(this.ipc_data.ensureTotalCapacity(this.ipc_data.capacity + 4096)); return this.ipc_data.unusedCapacitySlice(); } return available; @@ -412,7 +412,7 @@ pub const SecurityScanSubprocess = struct { pub fn onReadChunk(this: *SecurityScanSubprocess, chunk: []const u8, hasMore: bun.io.ReadState) bool { _ = hasMore; - this.ipc_data.appendSlice(chunk) catch bun.outOfMemory(); + bun.handleOom(this.ipc_data.appendSlice(chunk)); return true; } diff --git a/src/install/PackageManager/updatePackageJSONAndInstall.zig b/src/install/PackageManager/updatePackageJSONAndInstall.zig index 3e508aa4c4..9407add0fe 100644 --- a/src/install/PackageManager/updatePackageJSONAndInstall.zig +++ b/src/install/PackageManager/updatePackageJSONAndInstall.zig @@ -3,7 +3,7 @@ pub fn updatePackageJSONAndInstallWithManager( ctx: Command.Context, original_cwd: string, ) !void { - var update_requests = UpdateRequest.Array.initCapacity(manager.allocator, 64) catch bun.outOfMemory(); + var update_requests = bun.handleOom(UpdateRequest.Array.initCapacity(manager.allocator, 64)); defer update_requests.deinit(manager.allocator); if (manager.options.positionals.len <= 1) { @@ -689,7 +689,7 @@ pub fn updatePackageJSONAndInstall( result: *bun.bundle_v2.BundleV2.DependenciesScanner.Result, ) anyerror!void { // TODO: add separate argument that makes it so positionals[1..] is not done and instead the positionals are passed - var positionals = bun.default_allocator.alloc(string, result.dependencies.keys().len + 1) catch bun.outOfMemory(); + var positionals = bun.handleOom(bun.default_allocator.alloc(string, result.dependencies.keys().len + 1)); positionals[0] = "add"; bun.copy(string, positionals[1..], result.dependencies.keys()); this.cli.positionals = positionals; diff --git a/src/install/PackageManagerTask.zig b/src/install/PackageManagerTask.zig index 5842b11c28..a78a7fefa2 100644 --- a/src/install/PackageManagerTask.zig +++ b/src/install/PackageManagerTask.zig @@ -78,7 +78,7 @@ pub fn callback(task: *ThreadPool.Task) void { if (this.status == .success) { if (this.apply_patch_task) |pt| { defer pt.deinit(); - pt.apply() catch bun.outOfMemory(); + bun.handleOom(pt.apply()); if (pt.callback.apply.logger.errors > 0) { defer pt.callback.apply.logger.deinit(); // this.log.addErrorFmt(null, logger.Loc.Empty, bun.default_allocator, "failed to apply patch: {}", .{e}) catch unreachable; diff --git a/src/install/PackageManifestMap.zig b/src/install/PackageManifestMap.zig index a758e8d55c..3014727490 100644 --- a/src/install/PackageManifestMap.zig +++ b/src/install/PackageManifestMap.zig @@ -50,7 +50,7 @@ pub fn byNameHashAllowExpired( }; } - const entry = this.hash_map.getOrPut(bun.default_allocator, name_hash) catch bun.outOfMemory(); + const entry = bun.handleOom(this.hash_map.getOrPut(bun.default_allocator, name_hash)); if (entry.found_existing) { if (entry.value_ptr.* == .manifest) { return &entry.value_ptr.manifest; diff --git a/src/install/bin.zig b/src/install/bin.zig index 5646944bf1..decf15f580 100644 --- a/src/install/bin.zig +++ b/src/install/bin.zig @@ -598,11 +598,11 @@ pub const Bin = extern struct { if (this.seen) |seen| { // Skip seen destinations for this tree // https://github.com/npm/cli/blob/22731831e22011e32fa0ca12178e242c2ee2b33d/node_modules/bin-links/lib/link-gently.js#L30 - const entry = seen.getOrPut(abs_dest) catch bun.outOfMemory(); + const entry = bun.handleOom(seen.getOrPut(abs_dest)); if (entry.found_existing) { return; } - entry.key_ptr.* = seen.allocator.dupe(u8, abs_dest) catch bun.outOfMemory(); + entry.key_ptr.* = bun.handleOom(seen.allocator.dupe(u8, abs_dest)); } // Skip if the target does not exist. This is important because placing a dangling diff --git a/src/install/dependency.zig b/src/install/dependency.zig index 2f5b559438..de72d54c5d 100644 --- a/src/install/dependency.zig +++ b/src/install/dependency.zig @@ -1291,7 +1291,7 @@ pub fn fromJS(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JS var buf = alias; if (name_value.isString()) { - var builder = bun.StringBuilder.initCapacity(allocator, name_slice.len + alias_slice.len) catch bun.outOfMemory(); + var builder = bun.handleOom(bun.StringBuilder.initCapacity(allocator, name_slice.len + alias_slice.len)); name = builder.append(name_slice.slice()); alias = builder.append(alias_slice.slice()); buf = builder.allocatedSlice(); diff --git a/src/install/hoisted_install.zig b/src/install/hoisted_install.zig index 7e9f25b94e..e2113ea316 100644 --- a/src/install/hoisted_install.zig +++ b/src/install/hoisted_install.zig @@ -176,7 +176,7 @@ pub fn installHoistedPackages( .tree_ids_to_trees_the_id_depends_on = tree_ids_to_trees_the_id_depends_on, .completed_trees = completed_trees, .trees = trees: { - const trees = this.allocator.alloc(TreeContext, this.lockfile.buffers.trees.items.len) catch bun.outOfMemory(); + const trees = bun.handleOom(this.allocator.alloc(TreeContext, this.lockfile.buffers.trees.items.len)); for (0..this.lockfile.buffers.trees.items.len) |i| { trees[i] = .{ .binaries = Bin.PriorityQueue.init(this.allocator, .{ diff --git a/src/install/install.zig b/src/install/install.zig index 3929bf86b7..daeb49d773 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -10,7 +10,10 @@ pub const BuntagHashBuf = [max_buntag_hash_buf_len]u8; pub fn buntaghashbuf_make(buf: *BuntagHashBuf, patch_hash: u64) [:0]u8 { @memcpy(buf[0..bun_hash_tag.len], bun_hash_tag); - const digits = std.fmt.bufPrint(buf[bun_hash_tag.len..], "{x}", .{patch_hash}) catch bun.outOfMemory(); + const digits = std.fmt.bufPrint(buf[bun_hash_tag.len..], "{x}", .{patch_hash}) catch |err| + switch (err) { + error.NoSpaceLeft => unreachable, + }; buf[bun_hash_tag.len + digits.len] = 0; const bunhashtag = buf[0 .. bun_hash_tag.len + digits.len :0]; return bunhashtag; @@ -69,7 +72,7 @@ pub fn initializeMiniStore() void { pub threadlocal var instance: ?*@This() = null; }; if (MiniStore.instance == null) { - var mini_store = bun.default_allocator.create(MiniStore) catch bun.outOfMemory(); + var mini_store = bun.handleOom(bun.default_allocator.create(MiniStore)); mini_store.* = .{ .heap = bun.MimallocArena.init(), .memory_allocator = undefined, diff --git a/src/install/isolated_install/Store.zig b/src/install/isolated_install/Store.zig index a1486baf49..cded0df949 100644 --- a/src/install/isolated_install/Store.zig +++ b/src/install/isolated_install/Store.zig @@ -65,7 +65,7 @@ pub const Store = struct { if (parent_id == maybe_parent_id) { return true; } - parent_dedupe.put(parent_id, {}) catch bun.outOfMemory(); + bun.handleOom(parent_dedupe.put(parent_id, {})); } len = parent_dedupe.count(); @@ -77,7 +77,7 @@ pub const Store = struct { if (parent_id == maybe_parent_id) { return true; } - parent_dedupe.put(parent_id, {}) catch bun.outOfMemory(); + bun.handleOom(parent_dedupe.put(parent_id, {})); len = parent_dedupe.count(); } i += 1; @@ -184,7 +184,7 @@ pub const Store = struct { if (parent_id == .invalid) { continue; } - parents.put(bun.default_allocator, parent_id, {}) catch bun.outOfMemory(); + bun.handleOom(parents.put(bun.default_allocator, parent_id, {})); } len = parents.count(); @@ -193,7 +193,7 @@ pub const Store = struct { if (parent_id == .invalid) { continue; } - parents.put(bun.default_allocator, parent_id, {}) catch bun.outOfMemory(); + bun.handleOom(parents.put(bun.default_allocator, parent_id, {})); len = parents.count(); } i += 1; diff --git a/src/install/lifecycle_script_runner.zig b/src/install/lifecycle_script_runner.zig index 38faa13d80..40c316ecbf 100644 --- a/src/install/lifecycle_script_runner.zig +++ b/src/install/lifecycle_script_runner.zig @@ -183,8 +183,8 @@ pub const LifecycleScriptSubprocess = struct { null, }; if (Environment.isWindows) { - this.stdout.source = .{ .pipe = bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory() }; - this.stderr.source = .{ .pipe = bun.default_allocator.create(uv.Pipe) catch bun.outOfMemory() }; + this.stdout.source = .{ .pipe = bun.handleOom(bun.default_allocator.create(uv.Pipe)) }; + this.stderr.source = .{ .pipe = bun.handleOom(bun.default_allocator.create(uv.Pipe)) }; } const spawn_options = bun.spawn.SpawnOptions{ .stdin = if (this.foreground) diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig index a0dbc5e6f6..572b33ca10 100644 --- a/src/install/lockfile.zig +++ b/src/install/lockfile.zig @@ -319,7 +319,7 @@ pub fn loadFromDir( Output.panic("failed to convert binary lockfile to text lockfile: {s}", .{@errorName(err)}); }; - buffered_writer.flush() catch bun.outOfMemory(); + bun.handleOom(buffered_writer.flush()); const text_lockfile_bytes = writer_buf.list.items; @@ -617,7 +617,7 @@ pub fn cleanWithLogger( // preinstall state before linking stage. manager.ensurePreinstallStateListCapacity(old.packages.len); var preinstall_state = manager.preinstall_state; - var old_preinstall_state = preinstall_state.clone(old.allocator) catch bun.outOfMemory(); + var old_preinstall_state = bun.handleOom(preinstall_state.clone(old.allocator)); defer old_preinstall_state.deinit(old.allocator); @memset(preinstall_state.items, .unknown); diff --git a/src/install/lockfile/Package.zig b/src/install/lockfile/Package.zig index 7a3a0ff373..520c6d0876 100644 --- a/src/install/lockfile/Package.zig +++ b/src/install/lockfile/Package.zig @@ -1790,7 +1790,7 @@ pub const Package = extern struct { for (workspace_names.values(), workspace_names.keys()) |value, note_path| { if (note_path.ptr == path.ptr) continue; if (strings.eqlLong(value.name, entry.name, true)) { - const note_abs_path = allocator.dupeZ(u8, Path.joinAbsStringZ(cwd, &.{ note_path, "package.json" }, .auto)) catch bun.outOfMemory(); + const note_abs_path = bun.handleOom(allocator.dupeZ(u8, Path.joinAbsStringZ(cwd, &.{ note_path, "package.json" }, .auto))); const note_src = bun.sys.File.toSource(note_abs_path, allocator, .{}).unwrap() catch logger.Source.initEmptyFile(note_abs_path); diff --git a/src/install/lockfile/Package/Scripts.zig b/src/install/lockfile/Package/Scripts.zig index df0a18f72c..129db63e98 100644 --- a/src/install/lockfile/Package/Scripts.zig +++ b/src/install/lockfile/Package/Scripts.zig @@ -78,7 +78,7 @@ pub const Scripts = extern struct { inline for (this.items, 0..) |maybe_script, i| { if (maybe_script) |script| { debug("enqueue({s}, {s}) in {s}", .{ "prepare", this.package_name, this.cwd }); - @field(lockfile.scripts, Lockfile.Scripts.names[i]).append(lockfile.allocator, script) catch bun.outOfMemory(); + bun.handleOom(@field(lockfile.scripts, Lockfile.Scripts.names[i]).append(lockfile.allocator, script)); } } } @@ -214,8 +214,8 @@ pub const Scripts = extern struct { .items = scripts, .first_index = @intCast(first_index), .total = total, - .cwd = allocator.dupeZ(u8, cwd) catch bun.outOfMemory(), - .package_name = lockfile.allocator.dupe(u8, package_name) catch bun.outOfMemory(), + .cwd = bun.handleOom(allocator.dupeZ(u8, cwd)), + .package_name = bun.handleOom(lockfile.allocator.dupe(u8, package_name)), }; } diff --git a/src/install/lockfile/Package/WorkspaceMap.zig b/src/install/lockfile/Package/WorkspaceMap.zig index f43b0dc4f3..f0cbc1279e 100644 --- a/src/install/lockfile/Package/WorkspaceMap.zig +++ b/src/install/lockfile/Package/WorkspaceMap.zig @@ -131,7 +131,7 @@ pub fn processNamesArray( if (input_path.len == 0 or input_path.len == 1 and input_path[0] == '.') continue; if (Glob.detectGlobSyntax(input_path)) { - workspace_globs.append(input_path) catch bun.outOfMemory(); + bun.handleOom(workspace_globs.append(input_path)); continue; } @@ -220,7 +220,7 @@ pub fn processNamesArray( const glob_pattern = if (user_pattern.len == 0) "package.json" else brk: { const parts = [_][]const u8{ user_pattern, "package.json" }; - break :brk arena.allocator().dupe(u8, bun.path.join(parts, .auto)) catch bun.outOfMemory(); + break :brk bun.handleOom(arena.allocator().dupe(u8, bun.path.join(parts, .auto))); }; var walker: GlobWalker = .{}; diff --git a/src/install/lockfile/Tree.zig b/src/install/lockfile/Tree.zig index 6949c3ec0a..b3b8d7e19a 100644 --- a/src/install/lockfile/Tree.zig +++ b/src/install/lockfile/Tree.zig @@ -521,7 +521,7 @@ pub fn processSubtree( switch (hoisted) { .dependency_loop, .hoisted => continue, .placement => |dest| { - dependency_lists[dest.id].append(builder.allocator, dep_id) catch bun.outOfMemory(); + bun.handleOom(dependency_lists[dest.id].append(builder.allocator, dep_id)); trees[dest.id].dependencies.len += 1; if (builder.resolution_lists[pkg_id].len > 0) { try builder.queue.writeItem(.{ diff --git a/src/install/lockfile/printer/tree_printer.zig b/src/install/lockfile/printer/tree_printer.zig index 0efef2d768..f16dfefba1 100644 --- a/src/install/lockfile/printer/tree_printer.zig +++ b/src/install/lockfile/printer/tree_printer.zig @@ -282,7 +282,7 @@ pub fn print( for (resolutions_list[0].begin()..resolutions_list[0].end()) |dep_id| { const dep = dependencies_buffer[dep_id]; if (dep.behavior.isWorkspace()) { - workspaces_to_print.append(allocator, @intCast(dep_id)) catch bun.outOfMemory(); + bun.handleOom(workspaces_to_print.append(allocator, @intCast(dep_id))); } } @@ -438,7 +438,7 @@ pub fn print( if (manager.track_installed_bin == .pending) { if (iterator.next() catch null) |bin_name| { manager.track_installed_bin = .{ - .basename = bun.default_allocator.dupe(u8, bin_name) catch bun.outOfMemory(), + .basename = bun.handleOom(bun.default_allocator.dupe(u8, bin_name)), }; try writer.print(fmt, .{bin_name}); diff --git a/src/install/migration.zig b/src/install/migration.zig index 6365245703..36e2d8e1e3 100644 --- a/src/install/migration.zig +++ b/src/install/migration.zig @@ -379,7 +379,7 @@ pub fn migrateNPMLockfile( const pkg_name = packageNameFromPath(pkg_path); if (!strings.eqlLong(wksp_entry.name, pkg_name, true)) { const pkg_name_hash = stringHash(pkg_name); - const path_entry = this.workspace_paths.getOrPut(allocator, pkg_name_hash) catch bun.outOfMemory(); + const path_entry = bun.handleOom(this.workspace_paths.getOrPut(allocator, pkg_name_hash)); if (!path_entry.found_existing) { // Package resolve path is an entry in the workspace map, but // the package name is different. This package doesn't exist @@ -391,7 +391,7 @@ pub fn migrateNPMLockfile( const sliced_version = Semver.SlicedString.init(version_string, version_string); const result = Semver.Version.parse(sliced_version); if (result.valid and result.wildcard == .none) { - this.workspace_versions.put(allocator, pkg_name_hash, result.version.min()) catch bun.outOfMemory(); + bun.handleOom(this.workspace_versions.put(allocator, pkg_name_hash, result.version.min())); } } } diff --git a/src/install/patch_install.zig b/src/install/patch_install.zig index ca27a6fb6f..b6177d8b4d 100644 --- a/src/install/patch_install.zig +++ b/src/install/patch_install.zig @@ -109,7 +109,7 @@ pub const PatchTask = struct { this.callback.calc_hash.result = this.calcHash(); }, .apply => { - this.apply() catch bun.outOfMemory(); + bun.handleOom(this.apply()); }, } } @@ -165,7 +165,7 @@ pub const PatchTask = struct { Global.crash(); }; - var gop = manager.lockfile.patched_dependencies.getOrPut(manager.allocator, calc_hash.name_and_version_hash) catch bun.outOfMemory(); + var gop = bun.handleOom(manager.lockfile.patched_dependencies.getOrPut(manager.allocator, calc_hash.name_and_version_hash)); if (gop.found_existing) { gop.value_ptr.setPatchfileHash(hash); } else @panic("No entry for patched dependency, this is a bug in Bun."); @@ -280,7 +280,12 @@ pub const PatchTask = struct { // 2. Create temp dir to do all the modifications var tmpname_buf: [1024]u8 = undefined; - const tempdir_name = bun.span(bun.fs.FileSystem.instance.tmpname("tmp", &tmpname_buf, bun.fastRandom()) catch bun.outOfMemory()); + const tempdir_name = bun.span( + bun.fs.FileSystem.instance.tmpname("tmp", &tmpname_buf, bun.fastRandom()) catch |err| switch (err) { + // max len is 1+16+1+8+3, well below 1024 + error.NoSpaceLeft => unreachable, + }, + ); const system_tmpdir = this.tempdir; const pkg_name = this.callback.apply.pkgname; @@ -293,7 +298,7 @@ pub const PatchTask = struct { const resolution_label, const resolution_tag = brk: { // TODO: fix this threadsafety issue. const resolution = &this.manager.lockfile.packages.items(.resolution)[patch.pkg_id]; - break :brk .{ std.fmt.allocPrint(bun.default_allocator, "{}", .{resolution.fmt(this.manager.lockfile.buffers.string_bytes.items, .posix)}) catch bun.outOfMemory(), resolution.tag }; + break :brk .{ bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{}", .{resolution.fmt(this.manager.lockfile.buffers.string_bytes.items, .posix)})), resolution.tag }; }; defer this.manager.allocator.free(resolution_label); @@ -428,7 +433,7 @@ pub const PatchTask = struct { this.callback.calc_hash.patchfile_path, this.manager.lockfile.patched_dependencies.get(this.callback.calc_hash.name_and_version_hash).?.path.slice(this.manager.lockfile.buffers.string_bytes.items), }; - log.addErrorFmt(null, Loc.Empty, this.manager.allocator, fmt, args) catch bun.outOfMemory(); + bun.handleOom(log.addErrorFmt(null, Loc.Empty, this.manager.allocator, fmt, args)); return null; } log.addWarningFmt( @@ -437,7 +442,7 @@ pub const PatchTask = struct { this.manager.allocator, "patchfile {s} is empty, please restore or delete it.", .{absolute_patchfile_path}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return null; }, .result => |s| s, @@ -450,7 +455,7 @@ pub const PatchTask = struct { this.manager.allocator, "patchfile {s} is empty, please restore or delete it.", .{absolute_patchfile_path}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return null; } @@ -462,7 +467,7 @@ pub const PatchTask = struct { this.manager.allocator, "failed to open patch file: {}", .{e}, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return null; }, .result => |fd| fd, @@ -487,7 +492,7 @@ pub const PatchTask = struct { this.manager.allocator, "failed to read from patch file: {} ({s})", .{ e, absolute_patchfile_path }, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); return null; }, }; @@ -514,7 +519,7 @@ pub const PatchTask = struct { state: ?CalcPatchHash.EnqueueAfterState, ) *PatchTask { const patchdep = manager.lockfile.patched_dependencies.get(name_and_version_hash) orelse @panic("This is a bug"); - const patchfile_path = manager.allocator.dupeZ(u8, patchdep.path.slice(manager.lockfile.buffers.string_bytes.items)) catch bun.outOfMemory(); + const patchfile_path = bun.handleOom(manager.allocator.dupeZ(u8, patchdep.path.slice(manager.lockfile.buffers.string_bytes.items))); const pt = bun.new(PatchTask, .{ .tempdir = manager.getTemporaryDirectory(), @@ -551,7 +556,7 @@ pub const PatchTask = struct { patch_hash, ); - const patchfilepath = pkg_manager.allocator.dupe(u8, pkg_manager.lockfile.patched_dependencies.get(name_and_version_hash).?.path.slice(pkg_manager.lockfile.buffers.string_bytes.items)) catch bun.outOfMemory(); + const patchfilepath = bun.handleOom(pkg_manager.allocator.dupe(u8, pkg_manager.lockfile.patched_dependencies.get(name_and_version_hash).?.path.slice(pkg_manager.lockfile.buffers.string_bytes.items))); const pt = bun.new(PatchTask, .{ .tempdir = pkg_manager.getTemporaryDirectory(), @@ -567,8 +572,8 @@ pub const PatchTask = struct { // need to dupe this as it's calculated using // `PackageManager.cached_package_folder_name_buf` which may be // modified - .cache_dir_subpath = pkg_manager.allocator.dupeZ(u8, stuff.cache_dir_subpath) catch bun.outOfMemory(), - .cache_dir_subpath_without_patch_hash = pkg_manager.allocator.dupeZ(u8, stuff.cache_dir_subpath[0 .. std.mem.indexOf(u8, stuff.cache_dir_subpath, "_patch_hash=") orelse @panic("This is a bug in Bun.")]) catch bun.outOfMemory(), + .cache_dir_subpath = bun.handleOom(pkg_manager.allocator.dupeZ(u8, stuff.cache_dir_subpath)), + .cache_dir_subpath_without_patch_hash = bun.handleOom(pkg_manager.allocator.dupeZ(u8, stuff.cache_dir_subpath[0 .. std.mem.indexOf(u8, stuff.cache_dir_subpath, "_patch_hash=") orelse @panic("This is a bug in Bun.")])), }, }, .manager = pkg_manager, diff --git a/src/install/repository.zig b/src/install/repository.zig index 8d374d0bfa..89ccd3f500 100644 --- a/src/install/repository.zig +++ b/src/install/repository.zig @@ -127,19 +127,19 @@ pub const Repository = extern struct { // A value can still be entered, but we need to find a workaround // so the user can see what is being prompted. By default the settings // below will cause no prompt and throw instead. - var cloned = other.map.cloneWithAllocator(allocator) catch bun.outOfMemory(); + var cloned = bun.handleOom(other.map.cloneWithAllocator(allocator)); if (cloned.get("GIT_ASKPASS") == null) { const config = SloppyGlobalGitConfig.get(); if (!config.has_askpass) { - cloned.put("GIT_ASKPASS", "echo") catch bun.outOfMemory(); + bun.handleOom(cloned.put("GIT_ASKPASS", "echo")); } } if (cloned.get("GIT_SSH_COMMAND") == null) { const config = SloppyGlobalGitConfig.get(); if (!config.has_ssh_command) { - cloned.put("GIT_SSH_COMMAND", "ssh -oStrictHostKeyChecking=accept-new") catch bun.outOfMemory(); + bun.handleOom(cloned.put("GIT_SSH_COMMAND", "ssh -oStrictHostKeyChecking=accept-new")); } } @@ -229,7 +229,7 @@ pub const Repository = extern struct { if (name.len == 0) { const version_literal = dep.version.literal.slice(buf); - const name_buf = allocator.alloc(u8, bun.sha.EVP.SHA1.digest) catch bun.outOfMemory(); + const name_buf = bun.handleOom(allocator.alloc(u8, bun.sha.EVP.SHA1.digest)); var sha1 = bun.sha.SHA1.init(); defer sha1.deinit(); sha1.update(version_literal); @@ -237,7 +237,7 @@ pub const Repository = extern struct { return name_buf[0..bun.sha.SHA1.digest]; } - return allocator.dupe(u8, name) catch bun.outOfMemory(); + return bun.handleOom(allocator.dupe(u8, name)); } pub fn order(lhs: *const Repository, rhs: *const Repository, lhs_buf: []const u8, rhs_buf: []const u8) std.math.Order { diff --git a/src/io/MaxBuf.zig b/src/io/MaxBuf.zig index 2ac0235a4e..eb80afc2a7 100644 --- a/src/io/MaxBuf.zig +++ b/src/io/MaxBuf.zig @@ -13,7 +13,7 @@ pub fn createForSubprocess(owner: *Subprocess, ptr: *?*MaxBuf, initial: ?i64) vo ptr.* = null; return; } - const maxbuf = bun.default_allocator.create(MaxBuf) catch bun.outOfMemory(); + const maxbuf = bun.handleOom(bun.default_allocator.create(MaxBuf)); maxbuf.* = .{ .owned_by_subprocess = owner, .owned_by_reader = false, diff --git a/src/io/PipeReader.zig b/src/io/PipeReader.zig index ddd6fe9b2b..628adf34e0 100644 --- a/src/io/PipeReader.zig +++ b/src/io/PipeReader.zig @@ -451,7 +451,7 @@ const PosixBufferedReader = struct { // Stream this chunk and register for next cycle _ = parent.vtable.onReadChunk(stack_buffer[0..bytes_read], if (received_hup and bytes_read < stack_buffer.len) .eof else .progress); } else { - resizable_buffer.appendSlice(stack_buffer[0..bytes_read]) catch bun.outOfMemory(); + bun.handleOom(resizable_buffer.appendSlice(stack_buffer[0..bytes_read])); } }, .err => |err| { @@ -463,7 +463,7 @@ const PosixBufferedReader = struct { }, } } else { - resizable_buffer.ensureUnusedCapacity(16 * 1024) catch bun.outOfMemory(); + bun.handleOom(resizable_buffer.ensureUnusedCapacity(16 * 1024)); var buf: []u8 = resizable_buffer.unusedCapacitySlice(); switch (bun.sys.readNonblocking(fd, buf)) { @@ -584,7 +584,7 @@ const PosixBufferedReader = struct { switch (sys_fn(fd, stack_buffer, 0)) { .result => |bytes_read| { if (bytes_read > 0) { - resizable_buffer.appendSlice(stack_buffer[0..bytes_read]) catch bun.outOfMemory(); + bun.handleOom(resizable_buffer.appendSlice(stack_buffer[0..bytes_read])); } if (parent.maxbuf) |l| l.onReadBytes(bytes_read); parent._offset += bytes_read; @@ -615,7 +615,7 @@ const PosixBufferedReader = struct { } while (true) { - resizable_buffer.ensureUnusedCapacity(16 * 1024) catch bun.outOfMemory(); + bun.handleOom(resizable_buffer.ensureUnusedCapacity(16 * 1024)); var buf: []u8 = resizable_buffer.unusedCapacitySlice(); switch (sys_fn(fd, buf, parent._offset)) { @@ -854,7 +854,7 @@ pub const WindowsBufferedReader = struct { pub fn getReadBufferWithStableMemoryAddress(this: *WindowsBufferedReader, suggested_size: usize) []u8 { this.flags.has_inflight_read = true; - this._buffer.ensureUnusedCapacity(suggested_size) catch bun.outOfMemory(); + bun.handleOom(this._buffer.ensureUnusedCapacity(suggested_size)); const res = this._buffer.allocatedSlice()[this._buffer.items.len..]; return res; } diff --git a/src/io/io.zig b/src/io/io.zig index a24a1499cc..7cc055a364 100644 --- a/src/io/io.zig +++ b/src/io/io.zig @@ -203,7 +203,7 @@ pub const Loop = struct { { var pending_batch = this.pending.popBatch(); var pending = pending_batch.iterator(); - events_list.ensureUnusedCapacity(pending.batch.count) catch bun.outOfMemory(); + bun.handleOom(events_list.ensureUnusedCapacity(pending.batch.count)); @memset(std.mem.sliceAsBytes(events_list.items.ptr[0..events_list.capacity]), 0); while (pending.next()) |request| { diff --git a/src/io/source.zig b/src/io/source.zig index 5f7e7b2250..647c5a8165 100644 --- a/src/io/source.zig +++ b/src/io/source.zig @@ -100,7 +100,7 @@ pub const Source = union(enum) { pub fn openPipe(loop: *uv.Loop, fd: bun.FileDescriptor) bun.sys.Maybe(*Source.Pipe) { log("openPipe (fd = {})", .{fd}); - const pipe = bun.default_allocator.create(Source.Pipe) catch bun.outOfMemory(); + const pipe = bun.handleOom(bun.default_allocator.create(Source.Pipe)); // we should never init using IPC here see ipc.zig switch (pipe.init(loop, false)) { .err => |err| { @@ -139,7 +139,7 @@ pub const Source = union(enum) { return .{ .result = &stdin_tty }; } - const tty = bun.default_allocator.create(Source.Tty) catch bun.outOfMemory(); + const tty = bun.handleOom(bun.default_allocator.create(Source.Tty)); return switch (tty.init(loop, uv_fd)) { .err => |err| .{ .err = err }, .result => .{ .result = tty }, @@ -149,7 +149,7 @@ pub const Source = union(enum) { pub fn openFile(fd: bun.FileDescriptor) *Source.File { bun.assert(fd.isValid() and fd.uv() != -1); log("openFile (fd = {})", .{fd}); - const file = bun.default_allocator.create(Source.File) catch bun.outOfMemory(); + const file = bun.handleOom(bun.default_allocator.create(Source.File)); file.* = std.mem.zeroes(Source.File); file.file = fd.uv(); diff --git a/src/js_lexer.zig b/src/js_lexer.zig index 393a74f2d5..fa284f7bcc 100644 --- a/src/js_lexer.zig +++ b/src/js_lexer.zig @@ -2675,7 +2675,7 @@ fn NewLexer_( // them. and LineTerminatorSequences are normalized to // for both TV and TRV. An explicit EscapeSequence is needed to // include a or sequence. - var bytes = MutableString.initCopy(lexer.allocator, text) catch bun.outOfMemory(); + var bytes = bun.handleOom(MutableString.initCopy(lexer.allocator, text)); var end: usize = 0; var i: usize = 0; var c: u8 = '0'; diff --git a/src/js_printer.zig b/src/js_printer.zig index 71ab9b4725..afdf531890 100644 --- a/src/js_printer.zig +++ b/src/js_printer.zig @@ -2734,12 +2734,12 @@ fn NewPrinter( if (inlined_value) |value| { if (replaced.items.len == 0) { - replaced.appendSlice(e.parts[0..i]) catch bun.outOfMemory(); + bun.handleOom(replaced.appendSlice(e.parts[0..i])); } part.value = value; - replaced.append(part) catch bun.outOfMemory(); + bun.handleOom(replaced.append(part)); } else if (replaced.items.len > 0) { - replaced.append(part) catch bun.outOfMemory(); + bun.handleOom(replaced.append(part)); } } @@ -3043,7 +3043,7 @@ fn NewPrinter( } // Only allocate heap memory on the stack for nested binary expressions - p.binary_expression_stack.append(v) catch bun.outOfMemory(); + bun.handleOom(p.binary_expression_stack.append(v)); v = BinaryExpressionVisitor{ .e = left_binary.?, .level = v.left_level, diff --git a/src/main_wasm.zig b/src/main_wasm.zig index 4f7d0c15fb..e4a02a47e6 100644 --- a/src/main_wasm.zig +++ b/src/main_wasm.zig @@ -436,7 +436,7 @@ export fn getTests(opts_array: u64) u64 { defer arena.deinit(); var log_ = Logger.Log.init(allocator); var reader = ApiReader.init(Uint8Array.fromJS(opts_array), allocator); - var opts = api.GetTestsRequest.decode(&reader) catch bun.outOfMemory(); + var opts = bun.handleOom(api.GetTestsRequest.decode(&reader)); var code = Logger.Source.initPathString(if (opts.path.len > 0) opts.path else "my-test-file.test.tsx", opts.contents); code.contents_is_recycled = true; defer { @@ -447,7 +447,7 @@ export fn getTests(opts_array: u64) u64 { var parser = JSParser.Parser.init(.{ .jsx = .{}, .ts = true, - }, &log_, &code, define, allocator) catch bun.outOfMemory(); + }, &log_, &code, define, allocator) catch |err| bun.handleOom(err); var anaylzer = TestAnalyzer{ .items = std.ArrayList( diff --git a/src/napi/napi.zig b/src/napi/napi.zig index af98f22253..046164c4d5 100644 --- a/src/napi/napi.zig +++ b/src/napi/napi.zig @@ -1625,7 +1625,7 @@ pub const ThreadSafeFunction = struct { } _ = this.queue.count.fetchAdd(1, .seq_cst); - this.queue.data.writeItem(ctx) catch bun.outOfMemory(); + bun.handleOom(this.queue.data.writeItem(ctx)); this.scheduleDispatch(); return @intFromEnum(NapiStatus.ok); } @@ -2459,7 +2459,7 @@ pub const NapiFinalizerTask = struct { const AnyTask = jsc.AnyTask.New(@This(), runOnJSThread); pub fn init(finalizer: Finalizer) *NapiFinalizerTask { - const finalizer_task = bun.default_allocator.create(NapiFinalizerTask) catch bun.outOfMemory(); + const finalizer_task = bun.handleOom(bun.default_allocator.create(NapiFinalizerTask)); finalizer_task.* = .{ .finalizer = finalizer, }; diff --git a/src/options.zig b/src/options.zig index 8bc91ca384..826a45467a 100644 --- a/src/options.zig +++ b/src/options.zig @@ -142,7 +142,7 @@ pub const ExternalModules = struct { } } - result.patterns = patterns.toOwnedSlice() catch bun.outOfMemory(); + result.patterns = bun.handleOom(patterns.toOwnedSlice()); return result; } diff --git a/src/patch.zig b/src/patch.zig index 9cb700395a..60635a33e6 100644 --- a/src/patch.zig +++ b/src/patch.zig @@ -58,15 +58,15 @@ pub const PatchFile = struct { defer _ = arena.reset(.retain_capacity); switch (part.*) { .file_deletion => { - const pathz = arena.allocator().dupeZ(u8, part.file_deletion.path) catch bun.outOfMemory(); + const pathz = bun.handleOom(arena.allocator().dupeZ(u8, part.file_deletion.path)); if (bun.sys.unlinkat(patch_dir, pathz).asErr()) |e| { return e.withoutPath(); } }, .file_rename => { - const from_path = arena.allocator().dupeZ(u8, part.file_rename.from_path) catch bun.outOfMemory(); - const to_path = arena.allocator().dupeZ(u8, part.file_rename.to_path) catch bun.outOfMemory(); + const from_path = bun.handleOom(arena.allocator().dupeZ(u8, part.file_rename.from_path)); + const to_path = bun.handleOom(arena.allocator().dupeZ(u8, part.file_rename.to_path)); if (std.fs.path.dirname(to_path)) |todir| { const abs_patch_dir = switch (state.patchDirAbsPath(patch_dir)) { @@ -90,7 +90,7 @@ pub const PatchFile = struct { } }, .file_creation => { - const filepath = bun.PathString.init(arena.allocator().dupeZ(u8, part.file_creation.path) catch bun.outOfMemory()); + const filepath = bun.PathString.init(bun.handleOom(arena.allocator().dupeZ(u8, part.file_creation.path))); const filedir = bun.path.dirname(filepath.slice(), .auto); const mode = part.file_creation.mode; @@ -136,7 +136,7 @@ pub const PatchFile = struct { // TODO: this additional allocation is probably not necessary in all cases and should be avoided or use stack buffer const file_contents = brk: { - var contents = file_alloc.alloc(u8, count) catch bun.outOfMemory(); + var contents = bun.handleOom(file_alloc.alloc(u8, count)); var i: usize = 0; for (hunk.parts.items[0].lines.items, 0..) |line, idx| { @memcpy(contents[i .. i + line.len], line); @@ -166,7 +166,7 @@ pub const PatchFile = struct { }, .file_mode_change => { const newmode = part.file_mode_change.new_mode; - const filepath = arena.allocator().dupeZ(u8, part.file_mode_change.path) catch bun.outOfMemory(); + const filepath = bun.handleOom(arena.allocator().dupeZ(u8, part.file_mode_change.path)); if (comptime bun.Environment.isPosix) { if (bun.sys.fchmodat(patch_dir, filepath, newmode.toBunMode(), 0).asErr()) |e| { return e.withoutPath(); @@ -210,7 +210,7 @@ pub const PatchFile = struct { patch_dir: bun.FileDescriptor, state: *ApplyState, ) bun.sys.Maybe(void) { - const file_path: [:0]const u8 = arena.allocator().dupeZ(u8, patch.path) catch bun.outOfMemory(); + const file_path: [:0]const u8 = bun.handleOom(arena.allocator().dupeZ(u8, patch.path)); // Need to get the mode of the original file // And also get the size to read file into memory @@ -266,13 +266,13 @@ pub const PatchFile = struct { }; // TODO: i hate this - var lines = std.ArrayListUnmanaged([]const u8).initCapacity(bun.default_allocator, lines_count) catch bun.outOfMemory(); + var lines = bun.handleOom(std.ArrayListUnmanaged([]const u8).initCapacity(bun.default_allocator, lines_count)); defer lines.deinit(bun.default_allocator); { var iter = std.mem.splitScalar(u8, filebuf, '\n'); var i: usize = 0; while (iter.next()) |line| : (i += 1) { - lines.append(bun.default_allocator, line) catch bun.outOfMemory(); + bun.handleOom(lines.append(bun.default_allocator, line)); } bun.debugAssert(i == file_line_count); } @@ -287,7 +287,7 @@ pub const PatchFile = struct { line_cursor += @intCast(part.lines.items.len); }, .insertion => { - const lines_to_insert = lines.addManyAt(bun.default_allocator, line_cursor, part.lines.items.len) catch bun.outOfMemory(); + const lines_to_insert = bun.handleOom(lines.addManyAt(bun.default_allocator, line_cursor, part.lines.items.len)); @memcpy(lines_to_insert, part.lines.items); line_cursor += @intCast(part.lines.items.len); if (part.no_newline_at_end_of_file) { @@ -296,9 +296,9 @@ pub const PatchFile = struct { }, .deletion => { // TODO: check if the lines match in the original file? - lines.replaceRange(bun.default_allocator, line_cursor, part.lines.items.len, &.{}) catch bun.outOfMemory(); + bun.handleOom(lines.replaceRange(bun.default_allocator, line_cursor, part.lines.items.len, &.{})); if (part.no_newline_at_end_of_file) { - lines.append(bun.default_allocator, "") catch bun.outOfMemory(); + bun.handleOom(lines.append(bun.default_allocator, "")); } // line_cursor -= part.lines.items.len; }, @@ -317,7 +317,7 @@ pub const PatchFile = struct { }; defer file_fd.close(); - const contents = std.mem.join(bun.default_allocator, "\n", lines.items) catch bun.outOfMemory(); + const contents = bun.handleOom(std.mem.join(bun.default_allocator, "\n", lines.items)); defer bun.default_allocator.free(contents); var written: usize = 0; @@ -1224,7 +1224,7 @@ pub fn spawnOpts( "--full-index", "--no-index", }; - const argv_buf = bun.default_allocator.alloc([]const u8, ARGV.len + 2) catch bun.outOfMemory(); + const argv_buf = bun.handleOom(bun.default_allocator.alloc([]const u8, ARGV.len + 2)); argv_buf[0] = git; for (1..ARGV.len) |i| { argv_buf[i] = ARGV[i]; @@ -1242,7 +1242,7 @@ pub fn spawnOpts( "USERPROFILE", }; const PATH = bun.getenvZ("PATH"); - const envp_buf = bun.default_allocator.allocSentinel(?[*:0]const u8, env_arr.len + @as(usize, if (PATH != null) 1 else 0), null) catch bun.outOfMemory(); + const envp_buf = bun.handleOom(bun.default_allocator.allocSentinel(?[*:0]const u8, env_arr.len + @as(usize, if (PATH != null) 1 else 0), null)); for (0..env_arr.len) |i| { envp_buf[i] = env_arr[i].ptr; } @@ -1299,7 +1299,7 @@ pub fn gitDiffPreprocessPaths( const bump = if (sentinel) 1 else 0; const old_folder = if (comptime bun.Environment.isWindows) brk: { // backslash in the path fucks everything up - const cpy = allocator.alloc(u8, old_folder_.len + bump) catch bun.outOfMemory(); + const cpy = bun.handleOom(allocator.alloc(u8, old_folder_.len + bump)); @memcpy(cpy[0..old_folder_.len], old_folder_); std.mem.replaceScalar(u8, cpy, '\\', '/'); if (sentinel) { @@ -1309,7 +1309,7 @@ pub fn gitDiffPreprocessPaths( break :brk cpy; } else old_folder_; const new_folder = if (comptime bun.Environment.isWindows) brk: { - const cpy = allocator.alloc(u8, new_folder_.len + bump) catch bun.outOfMemory(); + const cpy = bun.handleOom(allocator.alloc(u8, new_folder_.len + bump)); @memcpy(cpy[0..new_folder_.len], new_folder_); std.mem.replaceScalar(u8, cpy, '\\', '/'); if (sentinel) { @@ -1321,8 +1321,8 @@ pub fn gitDiffPreprocessPaths( if (bun.Environment.isPosix and sentinel) { return .{ - allocator.dupeZ(u8, old_folder) catch bun.outOfMemory(), - allocator.dupeZ(u8, new_folder) catch bun.outOfMemory(), + bun.handleOom(allocator.dupeZ(u8, old_folder)), + bun.handleOom(allocator.dupeZ(u8, new_folder)), }; } diff --git a/src/ptr/ref_count.zig b/src/ptr/ref_count.zig index bb4112cd4f..46b17cc048 100644 --- a/src/ptr/ref_count.zig +++ b/src/ptr/ref_count.zig @@ -474,7 +474,7 @@ pub fn DebugData(thread_safe: bool) type { const id = nextId(debug); debug.map.put(bun.default_allocator, id, .{ .acquired_at = .capture(return_address), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); return id; } @@ -487,7 +487,7 @@ pub fn DebugData(thread_safe: bool) type { debug.frees.put(bun.default_allocator, id, .{ .acquired_at = entry.value.acquired_at, .released_at = .capture(return_address), - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } fn deinit(debug: *@This(), data: []const u8, ret_addr: usize) void { diff --git a/src/resolver/data_url.zig b/src/resolver/data_url.zig index 279a5a3d9a..508335a544 100644 --- a/src/resolver/data_url.zig +++ b/src/resolver/data_url.zig @@ -143,7 +143,7 @@ pub const DataURL = struct { return buf.items; } - const base64buf = allocator.alloc(u8, total_base64_encode_len) catch bun.outOfMemory(); + const base64buf = bun.handleOom(allocator.alloc(u8, total_base64_encode_len)); return std.fmt.bufPrint(base64buf, "data:{s};base64,{s}", .{ mime_type, text }) catch unreachable; } diff --git a/src/resolver/resolve_path.zig b/src/resolver/resolve_path.zig index a884316479..941b73daa3 100644 --- a/src/resolver/resolve_path.zig +++ b/src/resolver/resolve_path.zig @@ -1260,7 +1260,7 @@ pub fn joinStringBufT(comptime T: type, buf: []T, parts: anytype, comptime platf } if (count * 2 > temp_buf.len) { - temp_buf = bun.default_allocator.alloc(T, count * 2) catch bun.outOfMemory(); + temp_buf = bun.handleOom(bun.default_allocator.alloc(T, count * 2)); free_temp_buf = true; } diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig index dcbc379e56..3b2caec0f7 100644 --- a/src/resolver/resolver.zig +++ b/src/resolver/resolver.zig @@ -1303,7 +1303,7 @@ pub const Resolver = struct { } return .{ .success = .{ - .path_pair = .{ .primary = Path.init(r.fs.dirname_store.append(@TypeOf(abs_path), abs_path) catch bun.outOfMemory()) }, + .path_pair = .{ .primary = Path.init(bun.handleOom(r.fs.dirname_store.append(@TypeOf(abs_path), abs_path))) }, .is_external = true, } }; } @@ -2169,13 +2169,13 @@ pub const Resolver = struct { const dir_path = strings.withoutTrailingSlashWindowsPath(dir_path_maybe_trail_slash); assertValidCacheKey(dir_path); - var dir_cache_info_result = r.dir_cache.getOrPut(dir_path) catch bun.outOfMemory(); + var dir_cache_info_result = bun.handleOom(r.dir_cache.getOrPut(dir_path)); if (dir_cache_info_result.status == .exists) { // we've already looked up this package before return r.dir_cache.atIndex(dir_cache_info_result.index).?; } var rfs = &r.fs.fs; - var cached_dir_entry_result = rfs.entries.getOrPut(dir_path) catch bun.outOfMemory(); + var cached_dir_entry_result = bun.handleOom(rfs.entries.getOrPut(dir_path)); var dir_entries_option: *Fs.FileSystem.RealFS.EntriesOption = undefined; var needs_iter = true; @@ -3443,7 +3443,7 @@ pub const Resolver = struct { root_path, it.buffer[0 .. (if (it.index) |i| i + 1 else 0) + part.len], }, - ) catch bun.outOfMemory()) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err)) catch |err| bun.handleOom(err); } } @@ -3454,7 +3454,7 @@ pub const Resolver = struct { list.append(bun.String.createFormat( "{s}" ++ std.fs.path.sep_str ++ "node_modules", .{root_path}, - ) catch bun.outOfMemory()) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err)) catch |err| bun.handleOom(err); return bun.String.toJSArray(globalObject, list.items) catch .zero; } diff --git a/src/router.zig b/src/router.zig index 872d053687..2bea8ac7a6 100644 --- a/src/router.zig +++ b/src/router.zig @@ -760,7 +760,7 @@ pub const Route = struct { } const abs_path = if (comptime Environment.isWindows) - allocator.dupe(u8, bun.path.platformToPosixBuf(u8, abs_path_str, &normalized_abs_path_buf)) catch bun.outOfMemory() + bun.handleOom(allocator.dupe(u8, bun.path.platformToPosixBuf(u8, abs_path_str, &normalized_abs_path_buf))) else PathString.init(abs_path_str); diff --git a/src/s3/client.zig b/src/s3/client.zig index c41b6ae126..8225d211ab 100644 --- a/src/s3/client.zig +++ b/src/s3/client.zig @@ -65,10 +65,10 @@ pub fn downloadSlice( if (size_ > 0) { end -= 1; } - break :brk std.fmt.allocPrint(bun.default_allocator, "bytes={}-{}", .{ offset, end }) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "bytes={}-{}", .{ offset, end })); } if (offset == 0) break :brk null; - break :brk std.fmt.allocPrint(bun.default_allocator, "bytes={}-", .{offset}) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "bytes={}-", .{offset})); }; S3SimpleRequest.executeSimpleS3Request(this, .{ @@ -104,61 +104,65 @@ pub fn listObjects( ) void { var search_params: bun.ByteList = .{}; - search_params.append(bun.default_allocator, "?") catch bun.outOfMemory(); + bun.handleOom(search_params.append(bun.default_allocator, "?")); if (listOptions.continuation_token) |continuation_token| { var buff: [1024]u8 = undefined; - const encoded = S3Credentials.encodeURIComponent(continuation_token, &buff, true) catch bun.outOfMemory(); - search_params.appendFmt(bun.default_allocator, "continuation-token={s}", .{encoded}) catch bun.outOfMemory(); + const encoded = S3Credentials.encodeURIComponent(continuation_token, &buff, true) catch |err| + std.debug.panic("unexpected error from S3Credentials.encodeURIComponent: {}", .{err}); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "continuation-token={s}", .{encoded})); } if (listOptions.delimiter) |delimiter| { var buff: [1024]u8 = undefined; - const encoded = S3Credentials.encodeURIComponent(delimiter, &buff, true) catch bun.outOfMemory(); + const encoded = S3Credentials.encodeURIComponent(delimiter, &buff, true) catch |err| + std.debug.panic("unexpected error from S3Credentials.encodeURIComponent: {}", .{err}); if (listOptions.continuation_token != null) { - search_params.appendFmt(bun.default_allocator, "&delimiter={s}", .{encoded}) catch bun.outOfMemory(); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "&delimiter={s}", .{encoded})); } else { - search_params.appendFmt(bun.default_allocator, "delimiter={s}", .{encoded}) catch bun.outOfMemory(); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "delimiter={s}", .{encoded})); } } if (listOptions.encoding_type != null) { if (listOptions.continuation_token != null or listOptions.delimiter != null) { - search_params.append(bun.default_allocator, "&encoding-type=url") catch bun.outOfMemory(); + bun.handleOom(search_params.append(bun.default_allocator, "&encoding-type=url")); } else { - search_params.append(bun.default_allocator, "encoding-type=url") catch bun.outOfMemory(); + bun.handleOom(search_params.append(bun.default_allocator, "encoding-type=url")); } } if (listOptions.fetch_owner) |fetch_owner| { if (listOptions.continuation_token != null or listOptions.delimiter != null or listOptions.encoding_type != null) { - search_params.appendFmt(bun.default_allocator, "&fetch-owner={}", .{fetch_owner}) catch bun.outOfMemory(); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "&fetch-owner={}", .{fetch_owner})); } else { - search_params.appendFmt(bun.default_allocator, "fetch-owner={}", .{fetch_owner}) catch bun.outOfMemory(); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "fetch-owner={}", .{fetch_owner})); } } if (listOptions.continuation_token != null or listOptions.delimiter != null or listOptions.encoding_type != null or listOptions.fetch_owner != null) { - search_params.append(bun.default_allocator, "&list-type=2") catch bun.outOfMemory(); + bun.handleOom(search_params.append(bun.default_allocator, "&list-type=2")); } else { - search_params.append(bun.default_allocator, "list-type=2") catch bun.outOfMemory(); + bun.handleOom(search_params.append(bun.default_allocator, "list-type=2")); } if (listOptions.max_keys) |max_keys| { - search_params.appendFmt(bun.default_allocator, "&max-keys={}", .{max_keys}) catch bun.outOfMemory(); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "&max-keys={}", .{max_keys})); } if (listOptions.prefix) |prefix| { var buff: [1024]u8 = undefined; - const encoded = S3Credentials.encodeURIComponent(prefix, &buff, true) catch bun.outOfMemory(); - search_params.appendFmt(bun.default_allocator, "&prefix={s}", .{encoded}) catch bun.outOfMemory(); + const encoded = S3Credentials.encodeURIComponent(prefix, &buff, true) catch |err| + std.debug.panic("unexpected error from S3Credentials.encodeURIComponent: {}", .{err}); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "&prefix={s}", .{encoded})); } if (listOptions.start_after) |start_after| { var buff: [1024]u8 = undefined; - const encoded = S3Credentials.encodeURIComponent(start_after, &buff, true) catch bun.outOfMemory(); - search_params.appendFmt(bun.default_allocator, "&start-after={s}", .{encoded}) catch bun.outOfMemory(); + const encoded = S3Credentials.encodeURIComponent(start_after, &buff, true) catch |err| + std.debug.panic("unexpected error from S3Credentials.encodeURIComponent: {}", .{err}); + bun.handleOom(search_params.appendFmt(bun.default_allocator, "&start-after={s}", .{encoded})); } const result = this.signRequest(.{ @@ -176,7 +180,7 @@ pub fn listObjects( search_params.deinitWithAllocator(bun.default_allocator); - const headers = bun.http.Headers.fromPicoHttpHeaders(result.headers(), bun.default_allocator) catch bun.outOfMemory(); + const headers = bun.handleOom(bun.http.Headers.fromPicoHttpHeaders(result.headers(), bun.default_allocator)); const task = bun.new(S3HttpSimpleTask, .{ .http = undefined, @@ -288,9 +292,9 @@ pub fn writableStream( const task = bun.new(MultiPartUpload, .{ .ref_count = .initExactRefs(2), // +1 for the stream .credentials = this, - .path = bun.default_allocator.dupe(u8, path) catch bun.outOfMemory(), - .proxy = if (proxy_url.len > 0) bun.default_allocator.dupe(u8, proxy_url) catch bun.outOfMemory() else "", - .content_type = if (content_type) |ct| bun.default_allocator.dupe(u8, ct) catch bun.outOfMemory() else null, + .path = bun.handleOom(bun.default_allocator.dupe(u8, path)), + .proxy = if (proxy_url.len > 0) bun.handleOom(bun.default_allocator.dupe(u8, proxy_url)) else "", + .content_type = if (content_type) |ct| bun.handleOom(bun.default_allocator.dupe(u8, ct)) else null, .storage_class = storage_class, .callback = @ptrCast(&Wrapper.callback), @@ -357,7 +361,7 @@ pub const S3UploadStreamWrapper = struct { pub fn writeRequestData(this: *@This(), data: []const u8) bool { log("writeRequestData {}", .{data.len}); - return this.task.writeBytes(data, false) catch bun.outOfMemory(); + return bun.handleOom(this.task.writeBytes(data, false)); } pub fn writeEndRequest(this: *@This(), err: ?jsc.JSValue) void { @@ -379,7 +383,7 @@ pub const S3UploadStreamWrapper = struct { }); } } else { - _ = this.task.writeBytes("", true) catch bun.outOfMemory(); + _ = bun.handleOom(this.task.writeBytes("", true)); } } @@ -463,9 +467,9 @@ pub fn uploadStream( const task = bun.new(MultiPartUpload, .{ .ref_count = .initExactRefs(2), // +1 for the stream ctx (only deinit after task and context ended) .credentials = this, - .path = bun.default_allocator.dupe(u8, path) catch bun.outOfMemory(), - .proxy = if (proxy_url.len > 0) bun.default_allocator.dupe(u8, proxy_url) catch bun.outOfMemory() else "", - .content_type = if (content_type) |ct| bun.default_allocator.dupe(u8, ct) catch bun.outOfMemory() else null, + .path = bun.handleOom(bun.default_allocator.dupe(u8, path)), + .proxy = if (proxy_url.len > 0) bun.handleOom(bun.default_allocator.dupe(u8, proxy_url)) else "", + .content_type = if (content_type) |ct| bun.handleOom(bun.default_allocator.dupe(u8, ct)) else null, .callback = @ptrCast(&S3UploadStreamWrapper.resolve), .callback_context = undefined, .globalThis = globalThis, @@ -514,10 +518,10 @@ pub fn downloadStream( if (size_ > 0) { end -= 1; } - break :brk std.fmt.allocPrint(bun.default_allocator, "bytes={}-{}", .{ offset, end }) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "bytes={}-{}", .{ offset, end })); } if (offset == 0) break :brk null; - break :brk std.fmt.allocPrint(bun.default_allocator, "bytes={}-", .{offset}) catch bun.outOfMemory(); + break :brk bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "bytes={}-", .{offset})); }; var result = this.signRequest(.{ @@ -537,13 +541,13 @@ pub fn downloadStream( const headers = brk: { if (range) |range_| { const _headers = result.mixWithHeader(&header_buffer, .{ .name = "range", .value = range_ }); - break :brk bun.http.Headers.fromPicoHttpHeaders(_headers, bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.http.Headers.fromPicoHttpHeaders(_headers, bun.default_allocator)); } else { - break :brk bun.http.Headers.fromPicoHttpHeaders(result.headers(), bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.http.Headers.fromPicoHttpHeaders(result.headers(), bun.default_allocator)); } }; const proxy = proxy_url orelse ""; - const owned_proxy = if (proxy.len > 0) bun.default_allocator.dupe(u8, proxy) catch bun.outOfMemory() else ""; + const owned_proxy = if (proxy.len > 0) bun.handleOom(bun.default_allocator.dupe(u8, proxy)) else ""; const task = S3HttpDownloadStreamingTask.new(.{ .http = undefined, .sign_result = result, @@ -666,7 +670,7 @@ pub fn readableStream( .ptr = .{ .Bytes = &reader.context }, .value = readable_value, }, globalThis), - .path = bun.default_allocator.dupe(u8, path) catch bun.outOfMemory(), + .path = bun.handleOom(bun.default_allocator.dupe(u8, path)), .global = globalThis, }), ); diff --git a/src/s3/credentials.zig b/src/s3/credentials.zig index dbd0148698..5a615b89c0 100644 --- a/src/s3/credentials.zig +++ b/src/s3/credentials.zig @@ -220,32 +220,32 @@ pub const S3Credentials = struct { return bun.new(S3Credentials, .{ .ref_count = .init(), .accessKeyId = if (this.accessKeyId.len > 0) - bun.default_allocator.dupe(u8, this.accessKeyId) catch bun.outOfMemory() + bun.handleOom(bun.default_allocator.dupe(u8, this.accessKeyId)) else "", .secretAccessKey = if (this.secretAccessKey.len > 0) - bun.default_allocator.dupe(u8, this.secretAccessKey) catch bun.outOfMemory() + bun.handleOom(bun.default_allocator.dupe(u8, this.secretAccessKey)) else "", .region = if (this.region.len > 0) - bun.default_allocator.dupe(u8, this.region) catch bun.outOfMemory() + bun.handleOom(bun.default_allocator.dupe(u8, this.region)) else "", .endpoint = if (this.endpoint.len > 0) - bun.default_allocator.dupe(u8, this.endpoint) catch bun.outOfMemory() + bun.handleOom(bun.default_allocator.dupe(u8, this.endpoint)) else "", .bucket = if (this.bucket.len > 0) - bun.default_allocator.dupe(u8, this.bucket) catch bun.outOfMemory() + bun.handleOom(bun.default_allocator.dupe(u8, this.bucket)) else "", .sessionToken = if (this.sessionToken.len > 0) - bun.default_allocator.dupe(u8, this.sessionToken) catch bun.outOfMemory() + bun.handleOom(bun.default_allocator.dupe(u8, this.sessionToken)) else "", @@ -316,7 +316,7 @@ pub const S3Credentials = struct { hours, minutes, seconds, - }) catch bun.outOfMemory(), + }) catch |err| bun.handleOom(err), }; } @@ -498,7 +498,7 @@ pub const S3Credentials = struct { if (content_md5) |content_md5_val| { const len = bun.base64.encodeLen(content_md5_val); - const content_md5_as_base64 = bun.default_allocator.alloc(u8, len) catch bun.outOfMemory(); + const content_md5_as_base64 = bun.handleOom(bun.default_allocator.alloc(u8, len)); content_md5 = content_md5_as_base64[0..bun.base64.encode(content_md5_as_base64, content_md5_val)]; } @@ -1074,14 +1074,14 @@ pub const S3Credentials = struct { } if (session_token) |token| { - const session_token_value = bun.default_allocator.dupe(u8, token) catch bun.outOfMemory(); + const session_token_value = bun.handleOom(bun.default_allocator.dupe(u8, token)); result.session_token = session_token_value; result._headers[result._headers_len] = .{ .name = "x-amz-security-token", .value = session_token_value }; result._headers_len += 1; } if (content_disposition) |cd| { - const content_disposition_value = bun.default_allocator.dupe(u8, cd) catch bun.outOfMemory(); + const content_disposition_value = bun.handleOom(bun.default_allocator.dupe(u8, cd)); result.content_disposition = content_disposition_value; result._headers[result._headers_len] = .{ .name = "Content-Disposition", .value = content_disposition_value }; result._headers_len += 1; @@ -1093,7 +1093,7 @@ pub const S3Credentials = struct { } if (content_md5) |c_md5| { - const content_md5_value = bun.default_allocator.dupe(u8, c_md5) catch bun.outOfMemory(); + const content_md5_value = bun.handleOom(bun.default_allocator.dupe(u8, c_md5)); result.content_md5 = content_md5_value; result._headers[result._headers_len] = .{ .name = "content-md5", .value = content_md5_value }; result._headers_len += 1; diff --git a/src/s3/download_stream.zig b/src/s3/download_stream.zig index 89a75a0d7e..cdb610f465 100644 --- a/src/s3/download_stream.zig +++ b/src/s3/download_stream.zig @@ -206,7 +206,7 @@ pub const S3HttpDownloadStreamingTask = struct { if (result.body) |body| { this.response_buffer = body.*; if (body.list.items.len > 0) { - _ = this.reported_response_buffer.write(body.list.items) catch bun.outOfMemory(); + _ = bun.handleOom(this.reported_response_buffer.write(body.list.items)); } this.response_buffer.reset(); if (this.reported_response_buffer.list.items.len == 0 and !is_done) { diff --git a/src/s3/multipart.zig b/src/s3/multipart.zig index f47e9d31bc..18fe0a8308 100644 --- a/src/s3/multipart.zig +++ b/src/s3/multipart.zig @@ -214,8 +214,8 @@ pub const MultiPartUpload = struct { // we will need to order this this.ctx.multipart_etags.append(bun.default_allocator, .{ .number = this.partNumber, - .etag = bun.default_allocator.dupe(u8, etag) catch bun.outOfMemory(), - }) catch bun.outOfMemory(); + .etag = bun.handleOom(bun.default_allocator.dupe(u8, etag)), + }) catch |err| bun.handleOom(err); this.state = .not_assigned; defer this.ctx.deref(); // mark as available @@ -337,7 +337,7 @@ pub const MultiPartUpload = struct { defer this.currentPartNumber += 1; if (this.queue == null) { // queueSize will never change and is small (max 255) - const queue = bun.default_allocator.alloc(UploadPart, queueSize) catch bun.outOfMemory(); + const queue = bun.handleOom(bun.default_allocator.alloc(UploadPart, queueSize)); // zero set just in case @memset(queue, UploadPart{ .data = "", @@ -350,7 +350,7 @@ pub const MultiPartUpload = struct { }); this.queue = queue; } - const data = if (needs_clone) bun.default_allocator.dupe(u8, chunk) catch bun.outOfMemory() else chunk; + const data = if (needs_clone) bun.handleOom(bun.default_allocator.dupe(u8, chunk)) else chunk; const allocated_len = if (needs_clone) data.len else allocated_size; const queue_item = &this.queue.?[index]; @@ -438,15 +438,15 @@ pub const MultiPartUpload = struct { // sort the etags std.sort.block(UploadPart.UploadPartResult, this.multipart_etags.items, this, UploadPart.sortEtags); // start the multipart upload list - this.multipart_upload_list.append(bun.default_allocator, "") catch bun.outOfMemory(); + bun.handleOom(this.multipart_upload_list.append(bun.default_allocator, "")); for (this.multipart_etags.items) |tag| { - this.multipart_upload_list.appendFmt(bun.default_allocator, "{}{s}", .{ tag.number, tag.etag }) catch bun.outOfMemory(); + bun.handleOom(this.multipart_upload_list.appendFmt(bun.default_allocator, "{}{s}", .{ tag.number, tag.etag })); bun.default_allocator.free(tag.etag); } this.multipart_etags.deinit(bun.default_allocator); this.multipart_etags = .{}; - this.multipart_upload_list.append(bun.default_allocator, "") catch bun.outOfMemory(); + bun.handleOom(this.multipart_upload_list.append(bun.default_allocator, "")); // will deref and ends after commit this.commitMultiPartRequest(); } else if (this.state == .singlefile_started) { diff --git a/src/s3/simple_request.zig b/src/s3/simple_request.zig index bbff79df19..3ee6d60e60 100644 --- a/src/s3/simple_request.zig +++ b/src/s3/simple_request.zig @@ -384,16 +384,16 @@ pub fn executeSimpleS3Request( var header_buffer: [10]picohttp.Header = undefined; if (options.range) |range_| { const _headers = result.mixWithHeader(&header_buffer, .{ .name = "range", .value = range_ }); - break :brk bun.http.Headers.fromPicoHttpHeaders(_headers, bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.http.Headers.fromPicoHttpHeaders(_headers, bun.default_allocator)); } else { if (options.content_type) |content_type| { if (content_type.len > 0) { const _headers = result.mixWithHeader(&header_buffer, .{ .name = "Content-Type", .value = content_type }); - break :brk bun.http.Headers.fromPicoHttpHeaders(_headers, bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.http.Headers.fromPicoHttpHeaders(_headers, bun.default_allocator)); } } - break :brk bun.http.Headers.fromPicoHttpHeaders(result.headers(), bun.default_allocator) catch bun.outOfMemory(); + break :brk bun.handleOom(bun.http.Headers.fromPicoHttpHeaders(result.headers(), bun.default_allocator)); } }; const task = S3HttpSimpleTask.new(.{ diff --git a/src/shell/Builtin.zig b/src/shell/Builtin.zig index 4957aca821..1fe2761be0 100644 --- a/src/shell/Builtin.zig +++ b/src/shell/Builtin.zig @@ -619,11 +619,11 @@ pub fn done(this: *Builtin, exit_code: anytype) Yield { // Aggregate output data if shell state is piped and this cmd is piped if (cmd.io.stdout == .pipe and cmd.io.stdout == .pipe and this.stdout == .buf) { - cmd.base.shell.buffered_stdout().append(bun.default_allocator, this.stdout.buf.items[0..]) catch bun.outOfMemory(); + bun.handleOom(cmd.base.shell.buffered_stdout().append(bun.default_allocator, this.stdout.buf.items[0..])); } // Aggregate output data if shell state is piped and this cmd is piped if (cmd.io.stderr == .pipe and cmd.io.stderr == .pipe and this.stderr == .buf) { - cmd.base.shell.buffered_stderr().append(bun.default_allocator, this.stderr.buf.items[0..]) catch bun.outOfMemory(); + bun.handleOom(cmd.base.shell.buffered_stderr().append(bun.default_allocator, this.stderr.buf.items[0..])); } return cmd.parent.childDone(cmd, this.exit_code.?); @@ -683,7 +683,7 @@ pub fn writeNoIO(this: *Builtin, comptime io_kind: @Type(.enum_literal), buf: [] .fd => @panic("writeNoIO(. " ++ @tagName(io_kind) ++ ", buf) can't write to a file descriptor, did you check that needsIO(." ++ @tagName(io_kind) ++ ") was false?"), .buf => { log("{s} write to buf len={d} str={s}{s}\n", .{ @tagName(this.kind), buf.len, buf[0..@min(buf.len, 16)], if (buf.len > 16) "..." else "" }); - io.buf.appendSlice(buf) catch bun.outOfMemory(); + bun.handleOom(io.buf.appendSlice(buf)); return Maybe(usize).initResult(buf.len); }, .arraybuf => { @@ -742,7 +742,7 @@ pub fn taskErrorToString(this: *Builtin, comptime kind: Kind, err: anytype) []co pub fn fmtErrorArena(this: *Builtin, comptime kind: ?Kind, comptime fmt_: []const u8, args: anytype) []u8 { const cmd_str = comptime if (kind) |k| @tagName(k) ++ ": " else ""; const fmt = cmd_str ++ fmt_; - return std.fmt.allocPrint(this.arena.allocator(), fmt, args) catch bun.outOfMemory(); + return bun.handleOom(std.fmt.allocPrint(this.arena.allocator(), fmt, args)); } // --- Shell Builtin Commands --- diff --git a/src/shell/EnvMap.zig b/src/shell/EnvMap.zig index a7ccbab0ee..46d4baa812 100644 --- a/src/shell/EnvMap.zig +++ b/src/shell/EnvMap.zig @@ -28,7 +28,7 @@ pub fn init(alloc: Allocator) EnvMap { pub fn initWithCapacity(alloc: Allocator, cap: usize) EnvMap { var map = MapType.init(alloc); - map.ensureTotalCapacity(cap) catch bun.outOfMemory(); + bun.handleOom(map.ensureTotalCapacity(cap)); return .{ .map = map }; } @@ -40,7 +40,7 @@ pub fn deinit(this: *EnvMap) void { /// NOTE: This will `.ref()` value, so you should `defer value.deref()` it /// before handing it to this function!!! pub fn insert(this: *EnvMap, key: EnvStr, val: EnvStr) void { - const result = this.map.getOrPut(key) catch bun.outOfMemory(); + const result = bun.handleOom(this.map.getOrPut(key)); if (!result.found_existing) { key.ref(); } else { @@ -60,7 +60,7 @@ pub fn clearRetainingCapacity(this: *EnvMap) void { } pub fn ensureTotalCapacity(this: *EnvMap, new_capacity: usize) void { - this.map.ensureTotalCapacity(new_capacity) catch bun.outOfMemory(); + bun.handleOom(this.map.ensureTotalCapacity(new_capacity)); } /// NOTE: Make sure you deref the string when done! @@ -72,7 +72,7 @@ pub fn get(this: *EnvMap, key: EnvStr) ?EnvStr { pub fn clone(this: *EnvMap) EnvMap { var new: EnvMap = .{ - .map = this.map.clone() catch bun.outOfMemory(), + .map = bun.handleOom(this.map.clone()), }; new.refStrings(); return new; @@ -80,7 +80,7 @@ pub fn clone(this: *EnvMap) EnvMap { pub fn cloneWithAllocator(this: *EnvMap, allocator: Allocator) EnvMap { var new: EnvMap = .{ - .map = this.map.cloneWithAllocator(allocator) catch bun.outOfMemory(), + .map = bun.handleOom(this.map.cloneWithAllocator(allocator)), }; new.refStrings(); return new; diff --git a/src/shell/EnvStr.zig b/src/shell/EnvStr.zig index cc613d4c0a..37aff365e1 100644 --- a/src/shell/EnvStr.zig +++ b/src/shell/EnvStr.zig @@ -46,7 +46,7 @@ pub const EnvStr = packed struct(u128) { if (old_str.len == 0) return .{ .tag = .empty, .ptr = 0, .len = 0 }; - const str = bun.default_allocator.dupe(u8, old_str) catch bun.outOfMemory(); + const str = bun.handleOom(bun.default_allocator.dupe(u8, old_str)); return .{ .ptr = toPtr(RefCountedStr.init(str)), .len = str.len, diff --git a/src/shell/IOWriter.zig b/src/shell/IOWriter.zig index dda47780a3..a594687ae7 100644 --- a/src/shell/IOWriter.zig +++ b/src/shell/IOWriter.zig @@ -323,7 +323,7 @@ pub fn doFileWrite(this: *IOWriter) Yield { }; if (child.bytelist) |bl| { const written_slice = this.buf.items[this.total_bytes_written .. this.total_bytes_written + amt]; - bl.append(bun.default_allocator, written_slice) catch bun.outOfMemory(); + bun.handleOom(bl.append(bun.default_allocator, written_slice)); } child.written += amt; if (!child.wroteEverything()) { @@ -347,7 +347,7 @@ pub fn onWritePollable(this: *IOWriter, amount: usize, status: bun.io.WriteStatu } else { if (child.bytelist) |bl| { const written_slice = this.buf.items[this.total_bytes_written .. this.total_bytes_written + amount]; - bl.append(bun.default_allocator, written_slice) catch bun.outOfMemory(); + bun.handleOom(bl.append(bun.default_allocator, written_slice)); } this.total_bytes_written += amount; child.written += amount; @@ -436,7 +436,7 @@ pub fn onError(this: *IOWriter, err__: bun.sys.Error) void { this.err = ee; log("IOWriter(0x{x}, fd={}) onError errno={s} errmsg={} errsyscall={}", .{ @intFromPtr(this), this.fd, @tagName(ee.getErrno()), ee.message, ee.syscall }); var seen_alloc = std.heap.stackFallback(@sizeOf(usize) * 64, bun.default_allocator); - var seen = std.ArrayList(usize).initCapacity(seen_alloc.get(), 64) catch bun.outOfMemory(); + var seen = bun.handleOom(std.ArrayList(usize).initCapacity(seen_alloc.get(), 64)); defer seen.deinit(); writer_loop: for (this.writers.slice()) |w| { if (w.isDead()) continue; @@ -451,7 +451,7 @@ pub fn onError(this: *IOWriter, err__: bun.sys.Error) void { continue :writer_loop; } - seen.append(@intFromPtr(ptr)) catch bun.outOfMemory(); + bun.handleOom(seen.append(@intFromPtr(ptr))); // TODO: This probably shouldn't call .run() w.ptr.onIOWriterChunk(0, this.err).run(); } @@ -468,7 +468,7 @@ pub fn getBuffer(this: *IOWriter) []const u8 { const result = this.getBufferImpl(); if (comptime bun.Environment.isWindows) { this.winbuf.clearRetainingCapacity(); - this.winbuf.appendSlice(bun.default_allocator, result) catch bun.outOfMemory(); + bun.handleOom(this.winbuf.appendSlice(bun.default_allocator, result)); return this.winbuf.items; } log("IOWriter(0x{x}, fd={}) getBuffer = {d} bytes", .{ @intFromPtr(this), this.fd, result.len }); @@ -602,7 +602,7 @@ pub fn enqueue(this: *IOWriter, ptr: anytype, bytelist: ?*bun.ByteList, buf: []c .bytelist = bytelist, }; log("IOWriter(0x{x}, fd={}) enqueue(0x{x} {s}, buf_len={d}, buf={s}, writer_len={d})", .{ @intFromPtr(this), this.fd, @intFromPtr(writer.rawPtr()), @tagName(writer.ptr.ptr.tag()), buf.len, buf[0..@min(128, buf.len)], this.writers.len() + 1 }); - this.buf.appendSlice(bun.default_allocator, buf) catch bun.outOfMemory(); + bun.handleOom(this.buf.appendSlice(bun.default_allocator, buf)); this.writers.append(writer); return this.enqueueInternal(); } @@ -629,7 +629,7 @@ pub fn enqueueFmt( ) Yield { var buf_writer = this.buf.writer(bun.default_allocator); const start = this.buf.items.len; - buf_writer.print(fmt, args) catch bun.outOfMemory(); + bun.handleOom(buf_writer.print(fmt, args)); const childptr = if (@TypeOf(ptr) == ChildPtr) ptr else ChildPtr.init(ptr); if (this.handleBrokenPipe(childptr)) |yield| return yield; diff --git a/src/shell/ParsedShellScript.zig b/src/shell/ParsedShellScript.zig index 783406ba01..1f53b19059 100644 --- a/src/shell/ParsedShellScript.zig +++ b/src/shell/ParsedShellScript.zig @@ -82,12 +82,12 @@ pub fn setEnv(this: *ParsedShellScript, globalThis: *JSGlobalObject, callframe: // PATH = ""; while (try object_iter.next()) |key| { - const keyslice = key.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory(); + const keyslice = bun.handleOom(key.toOwnedSlice(bun.default_allocator)); var value = object_iter.value; if (value.isUndefined()) continue; const value_str = try value.getZigString(globalThis); - const slice = value_str.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory(); + const slice = bun.handleOom(value_str.toOwnedSlice(bun.default_allocator)); const keyref = EnvStr.initRefCounted(keyslice); defer keyref.deref(); const valueref = EnvStr.initRefCounted(slice); diff --git a/src/shell/RefCountedStr.zig b/src/shell/RefCountedStr.zig index 26601c232d..597ab7702d 100644 --- a/src/shell/RefCountedStr.zig +++ b/src/shell/RefCountedStr.zig @@ -8,7 +8,7 @@ const debug = bun.Output.scoped(.RefCountedEnvStr, .hidden); pub fn init(slice: []const u8) *RefCountedStr { debug("init: {s}", .{slice}); - const this = bun.default_allocator.create(RefCountedStr) catch bun.outOfMemory(); + const this = bun.handleOom(bun.default_allocator.create(RefCountedStr)); this.* = .{ .refcount = 1, .len = @intCast(slice.len), diff --git a/src/shell/Yield.zig b/src/shell/Yield.zig index 967522a823..1f86d1bcf9 100644 --- a/src/shell/Yield.zig +++ b/src/shell/Yield.zig @@ -93,7 +93,7 @@ pub const Yield = union(enum) { // there can be nested pipelines, so we need a stack. var sfb = std.heap.stackFallback(@sizeOf(*Pipeline) * 4, bun.default_allocator); const alloc = sfb.get(); - var pipeline_stack = std.ArrayList(*Pipeline).initCapacity(alloc, 4) catch bun.outOfMemory(); + var pipeline_stack = bun.handleOom(std.ArrayList(*Pipeline).initCapacity(alloc, 4)); defer pipeline_stack.deinit(); // Note that we're using labelled switch statements but _not_ @@ -109,7 +109,7 @@ pub const Yield = union(enum) { continue :state x.next(); } bun.assert_eql(std.mem.indexOfScalar(*Pipeline, pipeline_stack.items, x), null); - pipeline_stack.append(x) catch bun.outOfMemory(); + bun.handleOom(pipeline_stack.append(x)); continue :state x.next(); }, .cmd => |x| continue :state x.next(), diff --git a/src/shell/builtin/basename.zig b/src/shell/builtin/basename.zig index c3b36c1c7e..f13c789795 100644 --- a/src/shell/builtin/basename.zig +++ b/src/shell/builtin/basename.zig @@ -36,7 +36,7 @@ fn fail(this: *@This(), msg: []const u8) Yield { fn print(this: *@This(), msg: []const u8) void { if (this.bltn().stdout.needsIO() != null) { - this.buf.appendSlice(bun.default_allocator, msg) catch bun.outOfMemory(); + bun.handleOom(this.buf.appendSlice(bun.default_allocator, msg)); return; } _ = this.bltn().writeNoIO(.stdout, msg); diff --git a/src/shell/builtin/cp.zig b/src/shell/builtin/cp.zig index 2a0ef9830c..af918bb941 100644 --- a/src/shell/builtin/cp.zig +++ b/src/shell/builtin/cp.zig @@ -219,17 +219,17 @@ pub fn onShellCpTaskDone(this: *Cp, task: *ShellCpTask) void { err.sys.path.eqlUTF8(task.src_absolute.?))) { log("{} got ebusy {d} {d}", .{ this, this.state.exec.ebusy.tasks.items.len, this.state.exec.paths_to_copy.len }); - this.state.exec.ebusy.tasks.append(bun.default_allocator, task) catch bun.outOfMemory(); + bun.handleOom(this.state.exec.ebusy.tasks.append(bun.default_allocator, task)); this.next().run(); return; } } else { const tgt_absolute = task.tgt_absolute; task.tgt_absolute = null; - if (tgt_absolute) |tgt| this.state.exec.ebusy.absolute_targets.put(bun.default_allocator, tgt, {}) catch bun.outOfMemory(); + if (tgt_absolute) |tgt| this.state.exec.ebusy.absolute_targets.put(bun.default_allocator, tgt, {}) catch |err| bun.handleOom(err); const src_absolute = task.src_absolute; task.src_absolute = null; - if (src_absolute) |tgt| this.state.exec.ebusy.absolute_srcs.put(bun.default_allocator, tgt, {}) catch bun.outOfMemory(); + if (src_absolute) |tgt| this.state.exec.ebusy.absolute_srcs.put(bun.default_allocator, tgt, {}) catch |err| bun.handleOom(err); } } @@ -466,12 +466,12 @@ pub const ShellCpTask = struct { // Any source directory without -R is an error if (src_is_dir and !this.opts.recursive) { - const errmsg = std.fmt.allocPrint(bun.default_allocator, "{s} is a directory (not copied)", .{this.src}) catch bun.outOfMemory(); + const errmsg = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s} is a directory (not copied)", .{this.src})); return .{ .custom = errmsg }; } if (!src_is_dir and bun.strings.eql(src, tgt)) { - const errmsg = std.fmt.allocPrint(bun.default_allocator, "{s} and {s} are identical (not copied)", .{ this.src, this.src }) catch bun.outOfMemory(); + const errmsg = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s} and {s} are identical (not copied)", .{ this.src, this.src })); return .{ .custom = errmsg }; } @@ -509,15 +509,15 @@ pub const ShellCpTask = struct { } else if (this.operands == 2) { // source_dir -> new_target_dir } else { - const errmsg = std.fmt.allocPrint(bun.default_allocator, "directory {s} does not exist", .{this.tgt}) catch bun.outOfMemory(); + const errmsg = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "directory {s} does not exist", .{this.tgt})); return .{ .custom = errmsg }; } copying_many = true; } // Handle the "3rd synopsis": source_files... -> target else { - if (src_is_dir) return .{ .custom = std.fmt.allocPrint(bun.default_allocator, "{s} is a directory (not copied)", .{this.src}) catch bun.outOfMemory() }; - if (!tgt_exists or !tgt_is_dir) return .{ .custom = std.fmt.allocPrint(bun.default_allocator, "{s} is not a directory", .{this.tgt}) catch bun.outOfMemory() }; + if (src_is_dir) return .{ .custom = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s} is a directory (not copied)", .{this.src})) }; + if (!tgt_exists or !tgt_is_dir) return .{ .custom = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s} is not a directory", .{this.tgt})) }; const basename = ResolvePath.basename(src[0..src.len]); const parts: []const []const u8 = &.{ tgt[0..tgt.len], @@ -527,8 +527,8 @@ pub const ShellCpTask = struct { copying_many = true; } - this.src_absolute = bun.default_allocator.dupeZ(u8, src[0..src.len]) catch bun.outOfMemory(); - this.tgt_absolute = bun.default_allocator.dupeZ(u8, tgt[0..tgt.len]) catch bun.outOfMemory(); + this.src_absolute = bun.handleOom(bun.default_allocator.dupeZ(u8, src[0..src.len])); + this.tgt_absolute = bun.handleOom(bun.default_allocator.dupeZ(u8, tgt[0..tgt.len])); const args = jsc.Node.fs.Arguments.Cp{ .src = jsc.Node.PathLike{ .string = bun.PathString.init(this.src_absolute.?) }, @@ -579,7 +579,7 @@ pub const ShellCpTask = struct { log("onCopy: {s} -> {s}\n", .{ src, dest }); defer this.verbose_output_lock.unlock(); var writer = this.verbose_output.writer(); - writer.print("{s} -> {s}\n", .{ src, dest }) catch bun.outOfMemory(); + bun.handleOom(writer.print("{s} -> {s}\n", .{ src, dest })); } pub fn cpOnCopy(this: *ShellCpTask, src_: anytype, dest_: anytype) void { diff --git a/src/shell/builtin/dirname.zig b/src/shell/builtin/dirname.zig index 588017019d..702c98f692 100644 --- a/src/shell/builtin/dirname.zig +++ b/src/shell/builtin/dirname.zig @@ -36,7 +36,7 @@ fn fail(this: *@This(), msg: []const u8) Yield { fn print(this: *@This(), msg: []const u8) Maybe(void) { if (this.bltn().stdout.needsIO() != null) { - this.buf.appendSlice(bun.default_allocator, msg) catch bun.outOfMemory(); + bun.handleOom(this.buf.appendSlice(bun.default_allocator, msg)); return .success; } const res = this.bltn().writeNoIO(.stdout, msg); diff --git a/src/shell/builtin/echo.zig b/src/shell/builtin/echo.zig index 2935c7d098..600dd83b90 100644 --- a/src/shell/builtin/echo.zig +++ b/src/shell/builtin/echo.zig @@ -22,17 +22,17 @@ pub fn start(this: *Echo) Yield { for (args, 0..) |arg, i| { const thearg = std.mem.span(arg); if (i < args_len - 1) { - this.output.appendSlice(thearg) catch bun.outOfMemory(); - this.output.append(' ') catch bun.outOfMemory(); + bun.handleOom(this.output.appendSlice(thearg)); + bun.handleOom(this.output.append(' ')); } else { if (thearg.len > 0 and thearg[thearg.len - 1] == '\n') { has_leading_newline = true; } - this.output.appendSlice(bun.strings.trimSubsequentLeadingChars(thearg, '\n')) catch bun.outOfMemory(); + bun.handleOom(this.output.appendSlice(bun.strings.trimSubsequentLeadingChars(thearg, '\n'))); } } - if (!has_leading_newline and !no_newline) this.output.append('\n') catch bun.outOfMemory(); + if (!has_leading_newline and !no_newline) bun.handleOom(this.output.append('\n')); if (this.bltn().stdout.needsIO()) |safeguard| { this.state = .waiting; diff --git a/src/shell/builtin/export.zig b/src/shell/builtin/export.zig index f1678e451e..1c782b0c57 100644 --- a/src/shell/builtin/export.zig +++ b/src/shell/builtin/export.zig @@ -49,7 +49,7 @@ pub fn start(this: *Export) Yield { keys.append(.{ .key = entry.key_ptr.*, .value = entry.value_ptr.*, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } std.mem.sort(Entry, keys.items[0..], {}, Entry.compare); @@ -61,7 +61,7 @@ pub fn start(this: *Export) Yield { } break :brk len; }; - var buf = arena.allocator().alloc(u8, len) catch bun.outOfMemory(); + var buf = bun.handleOom(arena.allocator().alloc(u8, len)); { var i: usize = 0; for (keys.items) |entry| { diff --git a/src/shell/builtin/ls.zig b/src/shell/builtin/ls.zig index 14f143fa36..3b81f47b30 100644 --- a/src/shell/builtin/ls.zig +++ b/src/shell/builtin/ls.zig @@ -61,7 +61,7 @@ fn next(this: *Ls) Yield { if (paths) |p| { const print_directory = p.len > 1; for (p) |path_raw| { - const path = this.alloc_scope.allocator().dupeZ(u8, path_raw[0..std.mem.len(path_raw) :0]) catch bun.outOfMemory(); + const path = bun.handleOom(this.alloc_scope.allocator().dupeZ(u8, path_raw[0..std.mem.len(path_raw) :0])); var task = ShellLsTask.create( this, this.opts, @@ -249,7 +249,7 @@ pub const ShellLsTask = struct { // scope and NOT a string literal or other string we don't own. if (owned_string) ls.alloc_scope.assertInScope(path); - const task = ls.alloc_scope.allocator().create(@This()) catch bun.outOfMemory(); + const task = bun.handleOom(ls.alloc_scope.allocator().create(@This())); task.* = @This(){ .ls = ls, .opts = opts, @@ -286,10 +286,10 @@ pub const ShellLsTask = struct { if (!is_absolute) { // If relative paths enabled, stdlib join is preferred over // ResolvePath.joinBuf because it doesn't try to normalize the path - return std.fs.path.joinZ(alloc, subdir_parts) catch bun.outOfMemory(); + return bun.handleOom(std.fs.path.joinZ(alloc, subdir_parts)); } - const out = alloc.dupeZ(u8, bun.path.join(subdir_parts, .auto)) catch bun.outOfMemory(); + const out = bun.handleOom(alloc.dupeZ(u8, bun.path.join(subdir_parts, .auto))); return out; } @@ -322,7 +322,7 @@ pub const ShellLsTask = struct { if (!this.opts.list_directories) { if (this.print_directory) { const writer = this.output.writer(); - std.fmt.format(writer, "{s}:\n", .{this.path}) catch bun.outOfMemory(); + bun.handleOom(std.fmt.format(writer, "{s}:\n", .{this.path})); } var iterator = DirIterator.iterate(fd, .u8); @@ -350,7 +350,7 @@ pub const ShellLsTask = struct { } const writer = this.output.writer(); - std.fmt.format(writer, "{s}\n", .{this.path}) catch bun.outOfMemory(); + bun.handleOom(std.fmt.format(writer, "{s}\n", .{this.path})); return; } @@ -373,9 +373,9 @@ pub const ShellLsTask = struct { const skip = this.shouldSkipEntry(name); debug("Entry: (skip={}) {s} :: {s}", .{ skip, this.path, name }); if (skip) return; - this.output.ensureUnusedCapacity(name.len + 1) catch bun.outOfMemory(); - this.output.appendSlice(name) catch bun.outOfMemory(); - this.output.append('\n') catch bun.outOfMemory(); + bun.handleOom(this.output.ensureUnusedCapacity(name.len + 1)); + bun.handleOom(this.output.appendSlice(name)); + bun.handleOom(this.output.append('\n')); } fn addDotEntriesIfNeeded(this: *@This()) void { @@ -387,7 +387,7 @@ pub const ShellLsTask = struct { fn errorWithPath(this: *@This(), err: Syscall.Error, path: [:0]const u8) Syscall.Error { debug("Ls(0x{x}).errorWithPath({s})", .{ @intFromPtr(this), path }); - return err.withPath(this.ls.alloc_scope.allocator().dupeZ(u8, path[0..path.len]) catch bun.outOfMemory()); + return err.withPath(bun.handleOom(this.ls.alloc_scope.allocator().dupeZ(u8, path[0..path.len]))); } pub fn workPoolCallback(task: *jsc.WorkPoolTask) void { diff --git a/src/shell/builtin/mkdir.zig b/src/shell/builtin/mkdir.zig index f52a438fd6..d27173249c 100644 --- a/src/shell/builtin/mkdir.zig +++ b/src/shell/builtin/mkdir.zig @@ -201,7 +201,7 @@ pub const ShellMkdirTask = struct { filepath: [:0]const u8, cwd_path: [:0]const u8, ) *ShellMkdirTask { - const task = bun.default_allocator.create(ShellMkdirTask) catch bun.outOfMemory(); + const task = bun.handleOom(bun.default_allocator.create(ShellMkdirTask)); const evtloop = mkdir.bltn().parentCmd().base.eventLoop(); task.* = ShellMkdirTask{ .mkdir = mkdir, @@ -258,7 +258,7 @@ pub const ShellMkdirTask = struct { switch (node_fs.mkdirRecursiveImpl(args, *MkdirVerboseVTable, &vtable)) { .result => {}, .err => |e| { - this.err = e.withPath(bun.default_allocator.dupe(u8, filepath) catch bun.outOfMemory()).toShellSystemError(); + this.err = e.withPath(bun.handleOom(bun.default_allocator.dupe(u8, filepath))).toShellSystemError(); std.mem.doNotOptimizeAway(&node_fs); }, } @@ -271,12 +271,12 @@ pub const ShellMkdirTask = struct { switch (node_fs.mkdirNonRecursive(args)) { .result => { if (this.opts.verbose) { - this.created_directories.appendSlice(filepath[0..filepath.len]) catch bun.outOfMemory(); - this.created_directories.append('\n') catch bun.outOfMemory(); + bun.handleOom(this.created_directories.appendSlice(filepath[0..filepath.len])); + bun.handleOom(this.created_directories.append('\n')); } }, .err => |e| { - this.err = e.withPath(bun.default_allocator.dupe(u8, filepath) catch bun.outOfMemory()).toShellSystemError(); + this.err = e.withPath(bun.handleOom(bun.default_allocator.dupe(u8, filepath))).toShellSystemError(); std.mem.doNotOptimizeAway(&node_fs); }, } @@ -298,11 +298,11 @@ pub const ShellMkdirTask = struct { if (bun.Environment.isWindows) { var buf: bun.PathBuffer = undefined; const str = bun.strings.fromWPath(&buf, dirpath[0..dirpath.len]); - vtable.inner.created_directories.appendSlice(str) catch bun.outOfMemory(); - vtable.inner.created_directories.append('\n') catch bun.outOfMemory(); + bun.handleOom(vtable.inner.created_directories.appendSlice(str)); + bun.handleOom(vtable.inner.created_directories.append('\n')); } else { - vtable.inner.created_directories.appendSlice(dirpath) catch bun.outOfMemory(); - vtable.inner.created_directories.append('\n') catch bun.outOfMemory(); + bun.handleOom(vtable.inner.created_directories.appendSlice(dirpath)); + bun.handleOom(vtable.inner.created_directories.append('\n')); } return; } diff --git a/src/shell/builtin/mv.zig b/src/shell/builtin/mv.zig index 1440ff74de..63f4a3687d 100644 --- a/src/shell/builtin/mv.zig +++ b/src/shell/builtin/mv.zig @@ -120,7 +120,7 @@ pub const ShellMvBatchedTask = struct { ResolvePath.basename(src), }, .auto); - this.err = e.withPath(bun.default_allocator.dupeZ(u8, target_path[0..]) catch bun.outOfMemory()); + this.err = e.withPath(bun.handleOom(bun.default_allocator.dupeZ(u8, target_path[0..]))); return false; }, else => {}, @@ -257,7 +257,7 @@ pub fn next(this: *Mv) Yield { this.args.target_fd = maybe_fd; const cwd_fd = this.bltn().parentCmd().base.shell.cwd_fd; - const tasks = this.bltn().arena.allocator().alloc(ShellMvBatchedTask, task_count) catch bun.outOfMemory(); + const tasks = bun.handleOom(this.bltn().arena.allocator().alloc(ShellMvBatchedTask, task_count)); // Initialize tasks { var i: usize = 0; diff --git a/src/shell/builtin/rm.zig b/src/shell/builtin/rm.zig index 5f5dc33f09..817ce3aa22 100644 --- a/src/shell/builtin/rm.zig +++ b/src/shell/builtin/rm.zig @@ -545,7 +545,7 @@ pub const ShellRmTask = struct { if (this.parent_task == null) { var buf: bun.PathBuffer = undefined; const cwd_path = switch (Syscall.getFdPath(this.task_manager.cwd, &buf)) { - .result => |p| bun.default_allocator.dupeZ(u8, p) catch bun.outOfMemory(), + .result => |p| bun.handleOom(bun.default_allocator.dupeZ(u8, p)), .err => |err| { debug("[runFromThreadPoolImpl:getcwd] DirTask({x}) failed: {s}: {s}", .{ @intFromPtr(this), @tagName(err.getErrno()), err.path }); this.task_manager.err_mutex.lock(); @@ -680,7 +680,7 @@ pub const ShellRmTask = struct { }; pub fn create(root_path: bun.PathString, rm: *Rm, cwd: bun.FileDescriptor, error_signal: *std.atomic.Value(bool), is_absolute: bool) *ShellRmTask { - const task = bun.default_allocator.create(ShellRmTask) catch bun.outOfMemory(); + const task = bun.handleOom(bun.default_allocator.create(ShellRmTask)); task.* = ShellRmTask{ .rm = rm, .opts = rm.opts, @@ -730,7 +730,7 @@ pub const ShellRmTask = struct { return; } - var subtask = bun.default_allocator.create(DirTask) catch bun.outOfMemory(); + var subtask = bun.handleOom(bun.default_allocator.create(DirTask)); subtask.* = DirTask{ .task_manager = this, .path = path, @@ -760,8 +760,8 @@ pub const ShellRmTask = struct { debug("DirTask(0x{x}, {s}) Incrementing output count (deleted={s})", .{ @intFromPtr(dir_task), dir_task.path, path }); _ = this.rm.state.exec.incrementOutputCount(.output_count); } - dir_task.deleted_entries.appendSlice(path[0..path.len]) catch bun.outOfMemory(); - dir_task.deleted_entries.append('\n') catch bun.outOfMemory(); + bun.handleOom(dir_task.deleted_entries.appendSlice(path[0..path.len])); + bun.handleOom(dir_task.deleted_entries.append('\n')); return .success; } @@ -829,7 +829,7 @@ pub const ShellRmTask = struct { } if (!this.opts.recursive) { - return Maybe(void).initErr(Syscall.Error.fromCode(bun.sys.E.ISDIR, .TODO).withPath(bun.default_allocator.dupeZ(u8, dir_task.path) catch bun.outOfMemory())); + return Maybe(void).initErr(Syscall.Error.fromCode(bun.sys.E.ISDIR, .TODO).withPath(bun.handleOom(bun.default_allocator.dupeZ(u8, dir_task.path)))); } const flags = bun.O.DIRECTORY | bun.O.RDONLY; @@ -980,14 +980,14 @@ pub const ShellRmTask = struct { pub fn onIsDir(this: *@This(), parent_dir_task: *DirTask, path: [:0]const u8, is_absolute: bool, buf: *bun.PathBuffer) Maybe(void) { if (this.child_of_dir) { - this.task.enqueueNoJoin(parent_dir_task, bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(), .dir); + this.task.enqueueNoJoin(parent_dir_task, bun.handleOom(bun.default_allocator.dupeZ(u8, path)), .dir); return .success; } return this.task.removeEntryDir(parent_dir_task, is_absolute, buf); } pub fn onDirNotEmpty(this: *@This(), parent_dir_task: *DirTask, path: [:0]const u8, is_absolute: bool, buf: *bun.PathBuffer) Maybe(void) { - if (this.child_of_dir) return .{ .result = this.task.enqueueNoJoin(parent_dir_task, bun.default_allocator.dupeZ(u8, path) catch bun.outOfMemory(), .dir) }; + if (this.child_of_dir) return .{ .result = this.task.enqueueNoJoin(parent_dir_task, bun.handleOom(bun.default_allocator.dupeZ(u8, path)), .dir) }; return this.task.removeEntryDir(parent_dir_task, is_absolute, buf); } }; @@ -1142,7 +1142,7 @@ pub const ShellRmTask = struct { fn errorWithPath(this: *ShellRmTask, err: Syscall.Error, path: [:0]const u8) Syscall.Error { _ = this; - return err.withPath(bun.default_allocator.dupeZ(u8, path[0..path.len]) catch bun.outOfMemory()); + return err.withPath(bun.handleOom(bun.default_allocator.dupeZ(u8, path[0..path.len]))); } inline fn join(this: *ShellRmTask, alloc: Allocator, subdir_parts: []const []const u8, is_absolute: bool) [:0]const u8 { @@ -1150,10 +1150,10 @@ pub const ShellRmTask = struct { if (!is_absolute) { // If relative paths enabled, stdlib join is preferred over // ResolvePath.joinBuf because it doesn't try to normalize the path - return std.fs.path.joinZ(alloc, subdir_parts) catch bun.outOfMemory(); + return bun.handleOom(std.fs.path.joinZ(alloc, subdir_parts)); } - const out = alloc.dupeZ(u8, bun.path.join(subdir_parts, .auto)) catch bun.outOfMemory(); + const out = bun.handleOom(alloc.dupeZ(u8, bun.path.join(subdir_parts, .auto))); return out; } diff --git a/src/shell/builtin/seq.zig b/src/shell/builtin/seq.zig index a41a17b675..f5b0061fa7 100644 --- a/src/shell/builtin/seq.zig +++ b/src/shell/builtin/seq.zig @@ -86,7 +86,7 @@ fn do(this: *@This()) Yield { defer arena.deinit(); while (if (this.increment > 0) current <= this._end else current >= this._end) : (current += this.increment) { - const str = std.fmt.allocPrint(arena.allocator(), "{d}", .{current}) catch bun.outOfMemory(); + const str = bun.handleOom(std.fmt.allocPrint(arena.allocator(), "{d}", .{current})); defer _ = arena.reset(.retain_capacity); _ = this.print(str); _ = this.print(this.separator); @@ -102,7 +102,7 @@ fn do(this: *@This()) Yield { fn print(this: *@This(), msg: []const u8) void { if (this.bltn().stdout.needsIO() != null) { - this.buf.appendSlice(bun.default_allocator, msg) catch bun.outOfMemory(); + bun.handleOom(this.buf.appendSlice(bun.default_allocator, msg)); return; } _ = this.bltn().writeNoIO(.stdout, msg); diff --git a/src/shell/builtin/touch.zig b/src/shell/builtin/touch.zig index 6e88e9ba27..1213f8cb6c 100644 --- a/src/shell/builtin/touch.zig +++ b/src/shell/builtin/touch.zig @@ -192,7 +192,7 @@ pub const ShellTouchTask = struct { } pub fn create(touch: *Touch, opts: Opts, filepath: [:0]const u8, cwd_path: [:0]const u8) *ShellTouchTask { - const task = bun.default_allocator.create(ShellTouchTask) catch bun.outOfMemory(); + const task = bun.handleOom(bun.default_allocator.create(ShellTouchTask)); task.* = ShellTouchTask{ .touch = touch, .opts = opts, @@ -253,12 +253,12 @@ pub const ShellTouchTask = struct { break :out; }, .err => |e| { - this.err = e.withPath(bun.default_allocator.dupe(u8, filepath) catch bun.outOfMemory()).toShellSystemError(); + this.err = e.withPath(bun.handleOom(bun.default_allocator.dupe(u8, filepath))).toShellSystemError(); break :out; }, } } - this.err = err.withPath(bun.default_allocator.dupe(u8, filepath) catch bun.outOfMemory()).toShellSystemError(); + this.err = err.withPath(bun.handleOom(bun.default_allocator.dupe(u8, filepath))).toShellSystemError(); } if (this.event_loop == .js) { diff --git a/src/shell/builtin/yes.zig b/src/shell/builtin/yes.zig index badd090102..4c0868671d 100644 --- a/src/shell/builtin/yes.zig +++ b/src/shell/builtin/yes.zig @@ -30,7 +30,7 @@ pub fn start(this: *@This()) Yield { bufalloc = BUFSIZ; } - this.buffer = this.alloc_scope.allocator().alloc(u8, bufalloc) catch bun.outOfMemory(); + this.buffer = bun.handleOom(this.alloc_scope.allocator().alloc(u8, bufalloc)); // Fill buffer with one copy of the output this.buffer_used = 0; diff --git a/src/shell/interpreter.zig b/src/shell/interpreter.zig index 1797b6dcaa..e6d1a1db50 100644 --- a/src/shell/interpreter.zig +++ b/src/shell/interpreter.zig @@ -143,7 +143,7 @@ pub const CowFd = struct { const debug = bun.Output.scoped(.CowFd, .hidden); pub fn init(fd: bun.FileDescriptor) *CowFd { - const this = bun.default_allocator.create(CowFd) catch bun.outOfMemory(); + const this = bun.handleOom(bun.default_allocator.create(CowFd)); this.* = .{ .__fd = fd, }; @@ -441,7 +441,7 @@ pub const Interpreter = struct { io: IO, kind: Kind, ) Maybe(*ShellExecEnv) { - const duped = alloc.create(ShellExecEnv) catch bun.outOfMemory(); + const duped = bun.handleOom(alloc.create(ShellExecEnv)); const dupedfd = switch (Syscall.dup(this.cwd_fd)) { .err => |err| return .{ .err = err }, @@ -480,8 +480,8 @@ pub const Interpreter = struct { .cmd_local_env = EnvMap.init(alloc), .export_env = this.export_env.clone(), - .__prev_cwd = this.__prev_cwd.clone() catch bun.outOfMemory(), - .__cwd = this.__cwd.clone() catch bun.outOfMemory(), + .__prev_cwd = bun.handleOom(this.__prev_cwd.clone()), + .__cwd = bun.handleOom(this.__cwd.clone()), // TODO probably need to use os.dup here .cwd_fd = dupedfd, .__alloc_scope = alloc_scope, @@ -562,10 +562,10 @@ pub const Interpreter = struct { _ = this.cwd_fd.closeAllowingBadFileDescriptor(null); this.__prev_cwd.clearRetainingCapacity(); - this.__prev_cwd.appendSlice(this.__cwd.items[0..]) catch bun.outOfMemory(); + bun.handleOom(this.__prev_cwd.appendSlice(this.__cwd.items[0..])); this.__cwd.clearRetainingCapacity(); - this.__cwd.appendSlice(new_cwd[0 .. new_cwd.len + 1]) catch bun.outOfMemory(); + bun.handleOom(this.__cwd.appendSlice(new_cwd[0 .. new_cwd.len + 1])); if (comptime bun.Environment.allow_assert) { assert(this.__cwd.items[this.__cwd.items.len -| 1] == 0); @@ -605,7 +605,7 @@ pub const Interpreter = struct { }, .pipe => { const bufio: *bun.ByteList = this.buffered_stderr(); - bufio.appendFmt(bun.default_allocator, fmt, args) catch bun.outOfMemory(); + bun.handleOom(bufio.appendFmt(bun.default_allocator, fmt, args)); return ctx.parent.childDone(ctx, 1); }, // FIXME: This is not correct? This would just make the entire shell hang I think? @@ -814,8 +814,8 @@ pub const Interpreter = struct { }, }; - var cwd_arr = std.ArrayList(u8).initCapacity(bun.default_allocator, cwd.len + 1) catch bun.outOfMemory(); - cwd_arr.appendSlice(cwd[0 .. cwd.len + 1]) catch bun.outOfMemory(); + var cwd_arr = bun.handleOom(std.ArrayList(u8).initCapacity(bun.default_allocator, cwd.len + 1)); + bun.handleOom(cwd_arr.appendSlice(cwd[0 .. cwd.len + 1])); if (comptime bun.Environment.allow_assert) { assert(cwd_arr.items[cwd_arr.items.len -| 1] == 0); @@ -829,7 +829,7 @@ pub const Interpreter = struct { const stdin_reader = IOReader.init(stdin_fd, event_loop); - const interpreter = allocator.create(ThisInterpreter) catch bun.outOfMemory(); + const interpreter = bun.handleOom(allocator.create(ThisInterpreter)); interpreter.* = .{ .command_ctx = ctx, .event_loop = event_loop, @@ -844,7 +844,7 @@ pub const Interpreter = struct { .export_env = export_env, .__cwd = cwd_arr, - .__prev_cwd = cwd_arr.clone() catch bun.outOfMemory(), + .__prev_cwd = bun.handleOom(cwd_arr.clone()), .cwd_fd = cwd_fd, .__alloc_scope = undefined, @@ -1245,12 +1245,12 @@ pub const Interpreter = struct { // PATH = ""; while (object_iter.next()) |key| { - const keyslice = key.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory(); + const keyslice = bun.handleOom(key.toOwnedSlice(bun.default_allocator)); var value = object_iter.value; if (value.isUndefined()) continue; const value_str = value.getZigString(globalThis); - const slice = value_str.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory(); + const slice = bun.handleOom(value_str.toOwnedSlice(bun.default_allocator)); const keyref = EnvStr.initRefCounted(keyslice); defer keyref.deref(); const valueref = EnvStr.initRefCounted(slice); @@ -1306,9 +1306,9 @@ pub const Interpreter = struct { pub fn getVmArgsUtf8(this: *Interpreter, argv: []const *WTFStringImplStruct, idx: u8) []const u8 { if (this.vm_args_utf8.items.len != argv.len) { - this.vm_args_utf8.ensureTotalCapacity(argv.len) catch bun.outOfMemory(); + bun.handleOom(this.vm_args_utf8.ensureTotalCapacity(argv.len)); for (argv) |arg| { - this.vm_args_utf8.append(arg.toUTF8(bun.default_allocator)) catch bun.outOfMemory(); + bun.handleOom(this.vm_args_utf8.append(arg.toUTF8(bun.default_allocator))); } } return this.vm_args_utf8.items[idx].slice(); @@ -1395,9 +1395,9 @@ pub fn StatePtrUnion(comptime TypesValue: anytype) type { pub fn create(this: @This(), comptime Ty: type) *Ty { if (comptime bun.Environment.enableAllocScopes) { - return this.allocator().create(Ty) catch bun.outOfMemory(); + return bun.handleOom(this.allocator().create(Ty)); } - return bun.default_allocator.create(Ty) catch bun.outOfMemory(); + return bun.handleOom(bun.default_allocator.create(Ty)); } pub fn destroy(this: @This(), ptr: anytype) void { diff --git a/src/shell/shell.zig b/src/shell/shell.zig index d3a7aec44e..270fe85148 100644 --- a/src/shell/shell.zig +++ b/src/shell/shell.zig @@ -175,13 +175,13 @@ pub const GlobalJS = struct { pub inline fn throwInvalidArguments(this: @This(), comptime fmt: []const u8, args: anytype) ShellErr { return .{ - .invalid_arguments = .{ .val = std.fmt.allocPrint(this.globalThis.bunVM().allocator, fmt, args) catch bun.outOfMemory() }, + .invalid_arguments = .{ .val = bun.handleOom(std.fmt.allocPrint(this.globalThis.bunVM().allocator, fmt, args)) }, }; } pub inline fn throwTODO(this: @This(), msg: []const u8) ShellErr { return .{ - .todo = std.fmt.allocPrint(this.globalThis.bunVM().allocator, "{s}", .{msg}) catch bun.outOfMemory(), + .todo = bun.handleOom(std.fmt.allocPrint(this.globalThis.bunVM().allocator, "{s}", .{msg})), }; } @@ -190,14 +190,14 @@ pub const GlobalJS = struct { } pub inline fn handleError(this: @This(), err: anytype, comptime fmt: []const u8) ShellErr { - const str = std.fmt.allocPrint(this.globalThis.bunVM().allocator, "{s} " ++ fmt, .{@errorName(err)}) catch bun.outOfMemory(); + const str = bun.handleOom(std.fmt.allocPrint(this.globalThis.bunVM().allocator, "{s} " ++ fmt, .{@errorName(err)})); return .{ .custom = str, }; } pub inline fn throw(this: @This(), comptime fmt: []const u8, args: anytype) ShellErr { - const str = std.fmt.allocPrint(this.globalThis.bunVM().allocator, fmt, args) catch bun.outOfMemory(); + const str = bun.handleOom(std.fmt.allocPrint(this.globalThis.bunVM().allocator, fmt, args)); return .{ .custom = str, }; @@ -258,18 +258,18 @@ pub const GlobalMini = struct { pub inline fn throwTODO(this: @This(), msg: []const u8) ShellErr { return .{ - .todo = std.fmt.allocPrint(this.mini.allocator, "{s}", .{msg}) catch bun.outOfMemory(), + .todo = bun.handleOom(std.fmt.allocPrint(this.mini.allocator, "{s}", .{msg})), }; } pub inline fn throwInvalidArguments(this: @This(), comptime fmt: []const u8, args: anytype) ShellErr { return .{ - .invalid_arguments = .{ .val = std.fmt.allocPrint(this.allocator(), fmt, args) catch bun.outOfMemory() }, + .invalid_arguments = .{ .val = bun.handleOom(std.fmt.allocPrint(this.allocator(), fmt, args)) }, }; } pub inline fn handleError(this: @This(), err: anytype, comptime fmt: []const u8) ShellErr { - const str = std.fmt.allocPrint(this.mini.allocator, "{s} " ++ fmt, .{@errorName(err)}) catch bun.outOfMemory(); + const str = bun.handleOom(std.fmt.allocPrint(this.mini.allocator, "{s} " ++ fmt, .{@errorName(err)})); return .{ .custom = str, }; @@ -284,7 +284,7 @@ pub const GlobalMini = struct { } pub inline fn enqueueTaskConcurrentWaitPid(this: @This(), task: anytype) void { - var anytask = bun.default_allocator.create(jsc.AnyTaskWithExtraContext) catch bun.outOfMemory(); + var anytask = bun.handleOom(bun.default_allocator.create(jsc.AnyTaskWithExtraContext)); _ = anytask.from(task, "runFromMainThreadMini"); this.mini.enqueueTaskConcurrent(anytask); } @@ -294,7 +294,7 @@ pub const GlobalMini = struct { } pub inline fn throw(this: @This(), comptime fmt: []const u8, args: anytype) ShellErr { - const str = std.fmt.allocPrint(this.allocator(), fmt, args) catch bun.outOfMemory(); + const str = bun.handleOom(std.fmt.allocPrint(this.allocator(), fmt, args)); return .{ .custom = str, }; @@ -1937,7 +1937,7 @@ pub const Parser = struct { } break :size i; }; - var buf = self.alloc.alloc(u8, size) catch bun.outOfMemory(); + var buf = bun.handleOom(self.alloc.alloc(u8, size)); var i: usize = 0; for (errors) |e| { @memcpy(buf[i .. i + e.msg.len], e.msg); @@ -2123,7 +2123,7 @@ pub const LexResult = struct { } break :size i; }; - var buf = arena.alloc(u8, size) catch bun.outOfMemory(); + var buf = bun.handleOom(arena.alloc(u8, size)); var i: usize = 0; for (errors) |e| { @memcpy(buf[i .. i + e.msg.len()], e.msg.slice(this.strpool)); @@ -2221,9 +2221,9 @@ pub fn NewLexer(comptime encoding: StringEncoding) type { pub fn add_error(self: *@This(), msg: []const u8) void { const start = self.strpool.items.len; - self.strpool.appendSlice(msg) catch bun.outOfMemory(); + bun.handleOom(self.strpool.appendSlice(msg)); const end = self.strpool.items.len; - self.errors.append(.{ .msg = .{ .start = @intCast(start), .end = @intCast(end) } }) catch bun.outOfMemory(); + bun.handleOom(self.errors.append(.{ .msg = .{ .start = @intCast(start), .end = @intCast(end) } })); } fn make_sublexer(self: *@This(), kind: SubShellKind) @This() { @@ -4072,7 +4072,7 @@ pub fn SmolList(comptime T: type, comptime INLINED_MAX: comptime_int) type { return this; } var this: @This() = .{ - .heap = ByteList.initCapacity(bun.default_allocator, vals.len) catch bun.outOfMemory(), + .heap = bun.handleOom(ByteList.initCapacity(bun.default_allocator, vals.len)), }; this.heap.appendSliceAssumeCapacity(vals); return this; @@ -4097,9 +4097,9 @@ pub fn SmolList(comptime T: type, comptime INLINED_MAX: comptime_int) type { len: u32 = 0, pub fn promote(this: *Inlined, n: usize, new: T) bun.BabyList(T) { - var list = bun.BabyList(T).initCapacity(bun.default_allocator, n) catch bun.outOfMemory(); - list.append(bun.default_allocator, this.items[0..INLINED_MAX]) catch bun.outOfMemory(); - list.push(bun.default_allocator, new) catch bun.outOfMemory(); + var list = bun.handleOom(bun.BabyList(T).initCapacity(bun.default_allocator, n)); + bun.handleOom(list.append(bun.default_allocator, this.items[0..INLINED_MAX])); + bun.handleOom(list.push(bun.default_allocator, new)); return list; } @@ -4244,7 +4244,7 @@ pub fn SmolList(comptime T: type, comptime INLINED_MAX: comptime_int) type { this.inlined.len += 1; }, .heap => { - this.heap.push(bun.default_allocator, new) catch bun.outOfMemory(); + bun.handleOom(this.heap.push(bun.default_allocator, new)); }, } } diff --git a/src/shell/states/Assigns.zig b/src/shell/states/Assigns.zig index f9421070d3..9f6cc9301f 100644 --- a/src/shell/states/Assigns.zig +++ b/src/shell/states/Assigns.zig @@ -169,7 +169,7 @@ pub fn childDone(this: *Assigns, child: ChildPtr, exit_code: ExitCode) Yield { const value: []const u8 = brk: { if (size == 0) break :brk ""; - var merged = this.base.allocator().alloc(u8, size) catch bun.outOfMemory(); + var merged = bun.handleOom(this.base.allocator().alloc(u8, size)); var i: usize = 0; const last = expanding.current_expansion_result.items.len -| 1; for (expanding.current_expansion_result.items, 0..) |slice, j| { diff --git a/src/shell/states/Cmd.zig b/src/shell/states/Cmd.zig index 4e6f08f3a1..4bda507b16 100644 --- a/src/shell/states/Cmd.zig +++ b/src/shell/states/Cmd.zig @@ -157,7 +157,7 @@ const BufferedIoClosed = struct { // If the shell state is piped (inside a cmd substitution) aggregate the output of this command if (cmd.io.stdout == .pipe and cmd.io.stdout == .pipe and !cmd.node.redirect.redirectsElsewhere(.stdout)) { const the_slice = readable.pipe.slice(); - cmd.base.shell.buffered_stdout().append(bun.default_allocator, the_slice) catch bun.outOfMemory(); + bun.handleOom(cmd.base.shell.buffered_stdout().append(bun.default_allocator, the_slice)); } stdout.state = .{ .closed = bun.ByteList.fromList(readable.pipe.takeBuffer()) }; @@ -170,7 +170,7 @@ const BufferedIoClosed = struct { // If the shell state is piped (inside a cmd substitution) aggregate the output of this command if (cmd.io.stderr == .pipe and cmd.io.stderr == .pipe and !cmd.node.redirect.redirectsElsewhere(.stderr)) { const the_slice = readable.pipe.slice(); - cmd.base.shell.buffered_stderr().append(bun.default_allocator, the_slice) catch bun.outOfMemory(); + bun.handleOom(cmd.base.shell.buffered_stderr().append(bun.default_allocator, the_slice)); } stderr.state = .{ .closed = bun.ByteList.fromList(readable.pipe.takeBuffer()) }; @@ -247,7 +247,7 @@ pub fn init( .state = .idle, }; cmd.spawn_arena = bun.ArenaAllocator.init(cmd.base.allocator()); - cmd.args = std.ArrayList(?[*:0]const u8).initCapacity(cmd.base.allocator(), node.name_and_args.len) catch bun.outOfMemory(); + cmd.args = bun.handleOom(std.ArrayList(?[*:0]const u8).initCapacity(cmd.base.allocator(), node.name_and_args.len)); cmd.redirection_file = std.ArrayList(u8).init(cmd.spawn_arena.allocator()); return cmd; @@ -308,7 +308,7 @@ pub fn next(this: *Cmd) Yield { return this.transitionToExecStateAndYield(); } - this.args.ensureUnusedCapacity(1) catch bun.outOfMemory(); + bun.handleOom(this.args.ensureUnusedCapacity(1)); Expansion.init( this.base.interpreter, this.base.shell, @@ -424,7 +424,7 @@ fn initSubproc(this: *Cmd) Yield { spawn_args.cwd = this.base.shell.cwdZ(); { - this.args.append(null) catch bun.outOfMemory(); + bun.handleOom(this.args.append(null)); log("Cmd(0x{x}, {s}) IO: {}", .{ @intFromPtr(this), if (this.args.items.len > 0) this.args.items[0] orelse "" else "", this.io }); if (bun.Environment.isDebug) { @@ -494,7 +494,7 @@ fn initSubproc(this: *Cmd) Yield { }; this.base.allocator().free(first_arg_real); - const duped = this.base.allocator().dupeZ(u8, bun.span(resolved)) catch bun.outOfMemory(); + const duped = bun.handleOom(this.base.allocator().dupeZ(u8, bun.span(resolved))); this.args.items[0] = duped; } @@ -767,7 +767,7 @@ pub fn bufferedOutputCloseStdout(this: *Cmd, err: ?jsc.SystemError) void { if (this.io.stdout == .fd and this.io.stdout.fd.captured != null and !this.node.redirect.redirectsElsewhere(.stdout)) { var buf = this.io.stdout.fd.captured.?; const the_slice = this.exec.subproc.child.stdout.pipe.slice(); - buf.append(bun.default_allocator, the_slice) catch bun.outOfMemory(); + bun.handleOom(buf.append(bun.default_allocator, the_slice)); } this.exec.subproc.buffered_closed.close(this, .{ .stdout = &this.exec.subproc.child.stdout }); this.exec.subproc.child.closeIO(.stdout); @@ -783,7 +783,7 @@ pub fn bufferedOutputCloseStderr(this: *Cmd, err: ?jsc.SystemError) void { } if (this.io.stderr == .fd and this.io.stderr.fd.captured != null and !this.node.redirect.redirectsElsewhere(.stderr)) { var buf = this.io.stderr.fd.captured.?; - buf.append(bun.default_allocator, this.exec.subproc.child.stderr.pipe.slice()) catch bun.outOfMemory(); + bun.handleOom(buf.append(bun.default_allocator, this.exec.subproc.child.stderr.pipe.slice())); } this.exec.subproc.buffered_closed.close(this, .{ .stderr = &this.exec.subproc.child.stderr }); this.exec.subproc.child.closeIO(.stderr); diff --git a/src/shell/states/CondExpr.zig b/src/shell/states/CondExpr.zig index 2faa63d256..99c4888cfa 100644 --- a/src/shell/states/CondExpr.zig +++ b/src/shell/states/CondExpr.zig @@ -100,7 +100,7 @@ pub fn next(this: *CondExpr) Yield { return this.commandImplStart(); } - this.args.ensureUnusedCapacity(1) catch bun.outOfMemory(); + bun.handleOom(this.args.ensureUnusedCapacity(1)); Expansion.init( this.base.interpreter, this.base.shell, diff --git a/src/shell/states/Expansion.zig b/src/shell/states/Expansion.zig index 876dfef8a2..cbc56f236d 100644 --- a/src/shell/states/Expansion.zig +++ b/src/shell/states/Expansion.zig @@ -73,16 +73,16 @@ pub const Result = union(enum) { switch (this.*) { .array_of_slice => { - this.array_of_slice.append(buf) catch bun.outOfMemory(); + bun.handleOom(this.array_of_slice.append(buf)); return .moved; }, .array_of_ptr => { - this.array_of_ptr.append(@as([*:0]const u8, @ptrCast(buf.ptr))) catch bun.outOfMemory(); + bun.handleOom(this.array_of_ptr.append(@as([*:0]const u8, @ptrCast(buf.ptr)))); return .moved; }, .single => { if (this.single.done) return .copied; - this.single.list.appendSlice(buf[0 .. buf.len + 1]) catch bun.outOfMemory(); + bun.handleOom(this.single.list.appendSlice(buf[0 .. buf.len + 1])); this.single.done = true; return .copied; }, @@ -96,16 +96,16 @@ pub const Result = union(enum) { switch (this.*) { .array_of_slice => { - this.array_of_slice.append(buf.items[0 .. buf.items.len - 1 :0]) catch bun.outOfMemory(); + bun.handleOom(this.array_of_slice.append(buf.items[0 .. buf.items.len - 1 :0])); return .moved; }, .array_of_ptr => { - this.array_of_ptr.append(@as([*:0]const u8, @ptrCast(buf.items.ptr))) catch bun.outOfMemory(); + bun.handleOom(this.array_of_ptr.append(@as([*:0]const u8, @ptrCast(buf.items.ptr)))); return .moved; }, .single => { if (this.single.done) return .copied; - this.single.list.appendSlice(buf.items[0..]) catch bun.outOfMemory(); + bun.handleOom(this.single.list.appendSlice(buf.items[0..])); return .copied; }, } @@ -172,7 +172,7 @@ pub fn next(this: *Expansion) Yield { var has_unknown = false; // + 1 for sentinel const string_size = this.expansionSizeHint(this.node, &has_unknown); - this.current_out.ensureUnusedCapacity(string_size + 1) catch bun.outOfMemory(); + bun.handleOom(this.current_out.ensureUnusedCapacity(string_size + 1)); } while (this.word_idx < this.node.atomsLen()) { @@ -186,11 +186,11 @@ pub fn next(this: *Expansion) Yield { if (this.current_out.items.len > 0) { switch (this.current_out.items[0]) { '/', '\\' => { - this.current_out.insertSlice(0, homedir.slice()) catch bun.outOfMemory(); + bun.handleOom(this.current_out.insertSlice(0, homedir.slice())); }, else => { // TODO: Handle username - this.current_out.insert(0, '~') catch bun.outOfMemory(); + bun.handleOom(this.current_out.insert(0, '~')); }, } } @@ -225,9 +225,9 @@ pub fn next(this: *Expansion) Yield { const brace_str = this.current_out.items[0..]; var lexer_output = if (bun.strings.isAllASCII(brace_str)) lexer_output: { @branchHint(.likely); - break :lexer_output Braces.Lexer.tokenize(arena_allocator, brace_str) catch bun.outOfMemory(); + break :lexer_output bun.handleOom(Braces.Lexer.tokenize(arena_allocator, brace_str)); } else lexer_output: { - break :lexer_output Braces.NewLexer(.wtf8).tokenize(arena_allocator, brace_str) catch bun.outOfMemory(); + break :lexer_output bun.handleOom(Braces.NewLexer(.wtf8).tokenize(arena_allocator, brace_str)); }; const expansion_count = Braces.calculateExpandedAmount(lexer_output.tokens.items[0..]); @@ -237,7 +237,7 @@ pub fn next(this: *Expansion) Yield { } var maybe_stack_alloc = std.heap.stackFallback(@sizeOf([]std.ArrayList(u8)) * stack_max, arena_allocator); const stack_alloc = maybe_stack_alloc.get(); - const expanded_strings = stack_alloc.alloc(std.ArrayList(u8), expansion_count) catch bun.outOfMemory(); + const expanded_strings = bun.handleOom(stack_alloc.alloc(std.ArrayList(u8), expansion_count)); for (0..expansion_count) |i| { expanded_strings[i] = std.ArrayList(u8).init(this.base.allocator()); @@ -248,13 +248,19 @@ pub fn next(this: *Expansion) Yield { lexer_output.tokens.items[0..], expanded_strings, lexer_output.contains_nested, - ) catch bun.outOfMemory(); + ) catch |err| switch (err) { + error.OutOfMemory => bun.outOfMemory(), + error.UnexpectedToken => std.debug.panic( + "unexpected error from Braces.expand: UnexpectedToken", + .{}, + ), + }; this.outEnsureUnusedCapacity(expansion_count); // Add sentinel values for (0..expansion_count) |i| { - expanded_strings[i].append(0) catch bun.outOfMemory(); + bun.handleOom(expanded_strings[i].append(0)); switch (this.out.pushResult(&expanded_strings[i])) { .copied => { expanded_strings[i].deinit(); @@ -307,7 +313,7 @@ fn transitionToGlobState(this: *Expansion) Yield { false, false, false, - ) catch bun.outOfMemory()) { + ) catch |err| bun.handleOom(err)) { .result => {}, .err => |e| { this.state = .{ .err = bun.shell.ShellErr.newSys(e) }; @@ -426,13 +432,13 @@ fn postSubshellExpansion(this: *Expansion, stdout_: []u8) void { if (c == ' ') { b = i; prev_whitespace = true; - this.current_out.appendSlice(stdout[a..b]) catch bun.outOfMemory(); + bun.handleOom(this.current_out.appendSlice(stdout[a..b])); this.pushCurrentOut(); } } // "aa bbb" - this.current_out.appendSlice(stdout[a..b]) catch bun.outOfMemory(); + bun.handleOom(this.current_out.appendSlice(stdout[a..b])); } fn convertNewlinesToSpaces(stdout_: []u8) []u8 { @@ -504,7 +510,7 @@ pub fn childDone(this: *Expansion, child: ChildPtr, exit_code: ExitCode) Yield { this.postSubshellExpansion(stdout); } else { const trimmed = std.mem.trimRight(u8, stdout, " \n\t\r"); - this.current_out.appendSlice(trimmed) catch bun.outOfMemory(); + bun.handleOom(this.current_out.appendSlice(trimmed)); } this.word_idx += 1; @@ -529,7 +535,7 @@ fn onGlobWalkDone(this: *Expansion, task: *ShellGlobTask) Yield { }, .unknown => |errtag| { this.base.throw(&.{ - .custom = this.base.allocator().dupe(u8, @errorName(errtag)) catch bun.outOfMemory(), + .custom = bun.handleOom(this.base.allocator().dupe(u8, @errorName(errtag))), }); }, } @@ -545,7 +551,7 @@ fn onGlobWalkDone(this: *Expansion, task: *ShellGlobTask) Yield { return .{ .expansion = this }; } - const msg = std.fmt.allocPrint(this.base.allocator(), "no matches found: {s}", .{this.child_state.glob.walker.pattern}) catch bun.outOfMemory(); + const msg = bun.handleOom(std.fmt.allocPrint(this.base.allocator(), "no matches found: {s}", .{this.child_state.glob.walker.pattern})); this.state = .{ .err = bun.shell.ShellErr{ .custom = msg, @@ -558,7 +564,7 @@ fn onGlobWalkDone(this: *Expansion, task: *ShellGlobTask) Yield { for (task.result.items) |sentinel_str| { // The string is allocated in the glob walker arena and will be freed, so needs to be duped here - const duped = this.base.allocator().dupeZ(u8, sentinel_str[0..sentinel_str.len]) catch bun.outOfMemory(); + const duped = bun.handleOom(this.base.allocator().dupeZ(u8, sentinel_str[0..sentinel_str.len])); switch (this.out.pushResultSliceOwned(duped)) { .copied => { this.base.allocator().free(duped); @@ -578,35 +584,35 @@ fn onGlobWalkDone(this: *Expansion, task: *ShellGlobTask) Yield { pub fn expandSimpleNoIO(this: *Expansion, atom: *const ast.SimpleAtom, str_list: *std.ArrayList(u8), comptime expand_tilde: bool) bool { switch (atom.*) { .Text => |txt| { - str_list.appendSlice(txt) catch bun.outOfMemory(); + bun.handleOom(str_list.appendSlice(txt)); }, .Var => |label| { - str_list.appendSlice(this.expandVar(label)) catch bun.outOfMemory(); + bun.handleOom(str_list.appendSlice(this.expandVar(label))); }, .VarArgv => |int| { - str_list.appendSlice(this.expandVarArgv(int)) catch bun.outOfMemory(); + bun.handleOom(str_list.appendSlice(this.expandVarArgv(int))); }, .asterisk => { - str_list.append('*') catch bun.outOfMemory(); + bun.handleOom(str_list.append('*')); }, .double_asterisk => { - str_list.appendSlice("**") catch bun.outOfMemory(); + bun.handleOom(str_list.appendSlice("**")); }, .brace_begin => { - str_list.append('{') catch bun.outOfMemory(); + bun.handleOom(str_list.append('{')); }, .brace_end => { - str_list.append('}') catch bun.outOfMemory(); + bun.handleOom(str_list.append('}')); }, .comma => { - str_list.append(',') catch bun.outOfMemory(); + bun.handleOom(str_list.append(',')); }, .tilde => { if (expand_tilde) { const homedir = this.base.shell.getHomedir(); defer homedir.deref(); - str_list.appendSlice(homedir.slice()) catch bun.outOfMemory(); - } else str_list.append('~') catch bun.outOfMemory(); + bun.handleOom(str_list.appendSlice(homedir.slice())); + } else bun.handleOom(str_list.append('~')); }, .cmd_subst => { // TODO: @@ -620,12 +626,12 @@ pub fn expandSimpleNoIO(this: *Expansion, atom: *const ast.SimpleAtom, str_list: pub fn appendSlice(this: *Expansion, buf: *std.ArrayList(u8), slice: []const u8) void { _ = this; - buf.appendSlice(slice) catch bun.outOfMemory(); + bun.handleOom(buf.appendSlice(slice)); } pub fn pushCurrentOut(this: *Expansion) void { if (this.current_out.items.len == 0) return; - if (this.current_out.items[this.current_out.items.len - 1] != 0) this.current_out.append(0) catch bun.outOfMemory(); + if (this.current_out.items[this.current_out.items.len - 1] != 0) bun.handleOom(this.current_out.append(0)); switch (this.out.pushResult(&this.current_out)) { .copied => { this.current_out.clearRetainingCapacity(); @@ -727,10 +733,10 @@ fn expansionSizeHintSimple(this: *const Expansion, simple: *const ast.SimpleAtom fn outEnsureUnusedCapacity(this: *Expansion, additional: usize) void { switch (this.out) { .array_of_ptr => { - this.out.array_of_ptr.ensureUnusedCapacity(additional) catch bun.outOfMemory(); + bun.handleOom(this.out.array_of_ptr.ensureUnusedCapacity(additional)); }, .array_of_slice => { - this.out.array_of_slice.ensureUnusedCapacity(additional) catch bun.outOfMemory(); + bun.handleOom(this.out.array_of_slice.ensureUnusedCapacity(additional)); }, .single => {}, } @@ -771,7 +777,7 @@ pub const ShellGlobTask = struct { pub fn createOnMainThread(walker: *GlobWalker, expansion: *Expansion) *This { debug("createOnMainThread", .{}); var alloc_scope = bun.AllocationScope.init(bun.default_allocator); - var this = alloc_scope.allocator().create(This) catch bun.outOfMemory(); + var this = bun.handleOom(alloc_scope.allocator().create(This)); this.* = .{ .alloc_scope = alloc_scope, .event_loop = expansion.base.eventLoop(), @@ -803,7 +809,7 @@ pub const ShellGlobTask = struct { var iter = GlobWalker.Iterator{ .walker = this.walker }; defer iter.deinit(); - switch (iter.init() catch bun.outOfMemory()) { + switch (bun.handleOom(iter.init())) { .err => |err| return .{ .err = err }, else => {}, } @@ -812,7 +818,7 @@ pub const ShellGlobTask = struct { .err => |err| return .{ .err = err }, .result => |matched_path| matched_path, }) |path| { - this.result.append(path) catch bun.outOfMemory(); + bun.handleOom(this.result.append(path)); } return .success; diff --git a/src/shell/states/Pipeline.zig b/src/shell/states/Pipeline.zig index a466d892e1..a644ebeb36 100644 --- a/src/shell/states/Pipeline.zig +++ b/src/shell/states/Pipeline.zig @@ -95,9 +95,9 @@ fn setupCommands(this: *Pipeline) ?Yield { break :brk i; }; - this.cmds = if (cmd_count >= 1) this.base.allocator().alloc(CmdOrResult, this.node.items.len) catch bun.outOfMemory() else null; + this.cmds = if (cmd_count >= 1) bun.handleOom(this.base.allocator().alloc(CmdOrResult, this.node.items.len)) else null; if (this.cmds == null) return null; - var pipes = this.base.allocator().alloc(Pipe, if (cmd_count > 1) cmd_count - 1 else 1) catch bun.outOfMemory(); + var pipes = bun.handleOom(this.base.allocator().alloc(Pipe, if (cmd_count > 1) cmd_count - 1 else 1)); if (cmd_count > 1) { var pipes_set: u32 = 0; diff --git a/src/shell/subproc.zig b/src/shell/subproc.zig index 7aaa16c52c..9a8f838be8 100644 --- a/src/shell/subproc.zig +++ b/src/shell/subproc.zig @@ -696,7 +696,7 @@ pub const ShellSubprocess = struct { ) void { const allocator = this.arena.allocator(); this.override_env = true; - this.env_array.ensureTotalCapacityPrecise(allocator, env_iter.len) catch bun.outOfMemory(); + bun.handleOom(this.env_array.ensureTotalCapacityPrecise(allocator, env_iter.len)); if (disable_path_lookup_for_arv0) { // If the env object does not include a $PATH, it must disable path lookup for argv[0] @@ -707,13 +707,13 @@ pub const ShellSubprocess = struct { const key = entry.key_ptr.*.slice(); const value = entry.value_ptr.*.slice(); - var line = std.fmt.allocPrintZ(allocator, "{s}={s}", .{ key, value }) catch bun.outOfMemory(); + var line = bun.handleOom(std.fmt.allocPrintZ(allocator, "{s}={s}", .{ key, value })); if (bun.strings.eqlComptime(key, "PATH")) { this.PATH = bun.asByteSlice(line["PATH=".len..]); } - this.env_array.append(allocator, line) catch bun.outOfMemory(); + bun.handleOom(this.env_array.append(allocator, line)); } } }; @@ -764,8 +764,8 @@ pub const ShellSubprocess = struct { const is_sync = config.is_sync; if (!spawn_args.override_env and spawn_args.env_array.items.len == 0) { - // spawn_args.env_array.items = jsc_vm.transpiler.env.map.createNullDelimitedEnvMap(allocator) catch bun.outOfMemory(); - spawn_args.env_array.items = event_loop.createNullDelimitedEnvMap(allocator) catch bun.outOfMemory(); + // spawn_args.env_array.items = bun.handleOom(jsc_vm.transpiler.env.map.createNullDelimitedEnvMap(allocator)); + spawn_args.env_array.items = bun.handleOom(event_loop.createNullDelimitedEnvMap(allocator)); spawn_args.env_array.capacity = spawn_args.env_array.items.len; } @@ -790,7 +790,7 @@ pub const ShellSubprocess = struct { .result => |opt| opt, .err => |e| { return .{ .err = .{ - .custom = bun.default_allocator.dupe(u8, e.toStr()) catch bun.outOfMemory(), + .custom = bun.handleOom(bun.default_allocator.dupe(u8, e.toStr())), } }; }, }, @@ -798,7 +798,7 @@ pub const ShellSubprocess = struct { .result => |opt| opt, .err => |e| { return .{ .err = .{ - .custom = bun.default_allocator.dupe(u8, e.toStr()) catch bun.outOfMemory(), + .custom = bun.handleOom(bun.default_allocator.dupe(u8, e.toStr())), } }; }, }, @@ -806,7 +806,7 @@ pub const ShellSubprocess = struct { .result => |opt| opt, .err => |e| { return .{ .err = .{ - .custom = bun.default_allocator.dupe(u8, e.toStr()) catch bun.outOfMemory(), + .custom = bun.handleOom(bun.default_allocator.dupe(u8, e.toStr())), } }; }, }, @@ -821,11 +821,11 @@ pub const ShellSubprocess = struct { } spawn_args.cmd_parent.args.append(null) catch { - return .{ .err = .{ .custom = bun.default_allocator.dupe(u8, "out of memory") catch bun.outOfMemory() } }; + return .{ .err = .{ .custom = bun.handleOom(bun.default_allocator.dupe(u8, "out of memory")) } }; }; spawn_args.env_array.append(allocator, null) catch { - return .{ .err = .{ .custom = bun.default_allocator.dupe(u8, "out of memory") catch bun.outOfMemory() } }; + return .{ .err = .{ .custom = bun.handleOom(bun.default_allocator.dupe(u8, "out of memory")) } }; }; var spawn_result = switch (bun.spawn.spawnProcess( @@ -833,13 +833,13 @@ pub const ShellSubprocess = struct { @ptrCast(spawn_args.cmd_parent.args.items.ptr), @ptrCast(spawn_args.env_array.items.ptr), ) catch |err| { - return .{ .err = .{ .custom = std.fmt.allocPrint(bun.default_allocator, "Failed to spawn process: {s}", .{@errorName(err)}) catch bun.outOfMemory() } }; + return .{ .err = .{ .custom = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to spawn process: {s}", .{@errorName(err)})) } }; }) { .err => |err| return .{ .err = .{ .sys = err.toShellSystemError() } }, .result => |result| result, }; - var subprocess = event_loop.allocator().create(Subprocess) catch bun.outOfMemory(); + var subprocess = bun.handleOom(event_loop.allocator().create(Subprocess)); out_subproc.* = subprocess; subprocess.* = Subprocess{ .event_loop = event_loop, @@ -847,7 +847,17 @@ pub const ShellSubprocess = struct { event_loop, is_sync, ), - .stdin = Subprocess.Writable.init(spawn_args.stdio[0], event_loop, subprocess, spawn_result.stdin) catch bun.outOfMemory(), + .stdin = Subprocess.Writable.init( + spawn_args.stdio[0], + event_loop, + subprocess, + spawn_result.stdin, + ) catch |err| switch (err) { + error.UnexpectedCreatingStdin => std.debug.panic( + "unexpected error while creating stdin", + .{}, + ), + }, .stdout = Subprocess.Readable.init(.stdout, spawn_args.stdio[1], shellio.stdout, event_loop, subprocess, spawn_result.stdout, event_loop.allocator(), ShellSubprocess.default_max_buffer_size, true), .stderr = Subprocess.Readable.init(.stderr, spawn_args.stdio[2], shellio.stderr, event_loop, subprocess, spawn_result.stderr, event_loop.allocator(), ShellSubprocess.default_max_buffer_size, true), @@ -975,7 +985,7 @@ pub const PipeReader = struct { pub fn append(this: *BufferedOutput, bytes: []const u8) void { switch (this.*) { .bytelist => { - this.bytelist.append(bun.default_allocator, bytes) catch bun.outOfMemory(); + bun.handleOom(this.bytelist.append(bun.default_allocator, bytes)); }, .array_buffer => { const array_buf_slice = this.array_buffer.buf.slice(); diff --git a/src/sourcemap/CodeCoverage.zig b/src/sourcemap/CodeCoverage.zig index a6a4116e9a..eebaa4a7ea 100644 --- a/src/sourcemap/CodeCoverage.zig +++ b/src/sourcemap/CodeCoverage.zig @@ -26,7 +26,7 @@ pub const Report = struct { total_lines: u32 = 0, pub fn linesCoverageFraction(this: *const Report) f64 { - var intersected = this.executable_lines.clone(bun.default_allocator) catch bun.outOfMemory(); + var intersected = bun.handleOom(this.executable_lines.clone(bun.default_allocator)); defer intersected.deinit(bun.default_allocator); intersected.setIntersection(this.lines_which_have_executed); @@ -153,7 +153,7 @@ pub const Report = struct { try writer.writeAll(comptime prettyFmt(" | ", enable_colors)); - var executable_lines_that_havent_been_executed = report.lines_which_have_executed.clone(bun.default_allocator) catch bun.outOfMemory(); + var executable_lines_that_havent_been_executed = bun.handleOom(report.lines_which_have_executed.clone(bun.default_allocator)); defer executable_lines_that_havent_been_executed.deinit(bun.default_allocator); executable_lines_that_havent_been_executed.toggleAll(); @@ -237,7 +237,7 @@ pub const Report = struct { // ** Track all executable lines ** // Executable lines that were not hit should be marked as 0 - var executable_lines = report.executable_lines.clone(bun.default_allocator) catch bun.outOfMemory(); + var executable_lines = bun.handleOom(report.executable_lines.clone(bun.default_allocator)); defer executable_lines.deinit(bun.default_allocator); var iter = executable_lines.iterator(.{}); @@ -373,13 +373,13 @@ pub const ByteRangeMapping = struct { pub threadlocal var map: ?*HashMap = null; pub fn generate(str: bun.String, source_contents_str: bun.String, source_id: i32) callconv(.C) void { var _map = map orelse brk: { - map = bun.jsc.VirtualMachine.get().allocator.create(HashMap) catch bun.outOfMemory(); + map = bun.handleOom(bun.jsc.VirtualMachine.get().allocator.create(HashMap)); map.?.* = HashMap.init(bun.jsc.VirtualMachine.get().allocator); break :brk map.?; }; var slice = str.toUTF8(bun.default_allocator); const hash = bun.hash(slice.slice()); - var entry = _map.getOrPut(hash) catch bun.outOfMemory(); + var entry = bun.handleOom(_map.getOrPut(hash)); if (entry.found_existing) { entry.value_ptr.deinit(); } diff --git a/src/sourcemap/sourcemap.zig b/src/sourcemap/sourcemap.zig index d79452384d..4b8378ef7b 100644 --- a/src/sourcemap/sourcemap.zig +++ b/src/sourcemap/sourcemap.zig @@ -73,7 +73,7 @@ pub fn parseUrl( const base64_data = source[data_prefix.len + ";base64,".len ..]; const len = bun.base64.decodeLen(base64_data); - const bytes = arena.alloc(u8, len) catch bun.outOfMemory(); + const bytes = bun.handleOom(arena.alloc(u8, len)); const decoded = bun.base64.decode(bytes, base64_data); if (!decoded.isSuccessful()) { return error.InvalidBase64; @@ -153,7 +153,7 @@ pub fn parseJSON( var i: usize = 0; const source_paths_slice = if (hint != .source_only) - alloc.alloc([]const u8, sources_content.items.len) catch bun.outOfMemory() + bun.handleOom(alloc.alloc([]const u8, sources_content.items.len)) else null; errdefer if (hint != .source_only) { @@ -234,7 +234,7 @@ pub fn parseJSON( break :content null; } - const str = item.data.e_string.string(arena) catch bun.outOfMemory(); + const str = bun.handleOom(item.data.e_string.string(arena)); if (str.len == 0) { break :content null; } @@ -821,7 +821,7 @@ pub const Mapping = struct { .original = original, .source_index = source_index, .name_index = name_index, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); } if (needs_sort and options.sort) { @@ -1030,7 +1030,7 @@ fn findSourceMappingURL(comptime T: type, source: []const T, alloc: std.mem.Allo u8 => bun.jsc.ZigString.Slice.fromUTF8NeverFree(url), u16 => bun.jsc.ZigString.Slice.init( alloc, - bun.strings.toUTF8Alloc(alloc, url) catch bun.outOfMemory(), + bun.handleOom(bun.strings.toUTF8Alloc(alloc, url)), ), else => @compileError("Not Supported"), }; diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 7d58ab8ae7..040c49b7a7 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -352,7 +352,7 @@ pub fn getQueriesArray(this: *const @This()) JSValue { return js.queriesGetCached(this.js_value) orelse .zero; } pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [:0]const u8, args: anytype) void { - const message = std.fmt.allocPrint(bun.default_allocator, fmt, args) catch bun.outOfMemory(); + const message = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, fmt, args)); defer bun.default_allocator.free(message); const err = AnyMySQLError.mysqlErrorToJS(this.globalObject, message, error_code); diff --git a/src/sql/mysql/MySQLStatement.zig b/src/sql/mysql/MySQLStatement.zig index 437389b141..3933a2e63d 100644 --- a/src/sql/mysql/MySQLStatement.zig +++ b/src/sql/mysql/MySQLStatement.zig @@ -65,7 +65,7 @@ pub fn checkForDuplicateFields(this: *@This()) void { var seen_numbers = std.ArrayList(u32).init(bun.default_allocator); defer seen_numbers.deinit(); var seen_fields = bun.StringHashMap(void).init(bun.default_allocator); - seen_fields.ensureUnusedCapacity(@intCast(this.columns.len)) catch bun.outOfMemory(); + bun.handleOom(seen_fields.ensureUnusedCapacity(@intCast(this.columns.len))); defer seen_fields.deinit(); // iterate backwards @@ -89,7 +89,7 @@ pub fn checkForDuplicateFields(this: *@This()) void { field.name_or_index = .duplicate; flags.has_duplicate_columns = true; } else { - seen_numbers.append(index) catch bun.outOfMemory(); + bun.handleOom(seen_numbers.append(index)); } flags.has_indexed_columns = true; @@ -118,7 +118,7 @@ pub fn structure(this: *MySQLStatement, owner: JSValue, globalObject: *jsc.JSGlo nonDuplicatedCount -= 1; } } - const ids = if (nonDuplicatedCount <= jsc.JSObject.maxInlineCapacity()) stack_ids[0..nonDuplicatedCount] else bun.default_allocator.alloc(jsc.JSObject.ExternColumnIdentifier, nonDuplicatedCount) catch bun.outOfMemory(); + const ids = if (nonDuplicatedCount <= jsc.JSObject.maxInlineCapacity()) stack_ids[0..nonDuplicatedCount] else bun.handleOom(bun.default_allocator.alloc(jsc.JSObject.ExternColumnIdentifier, nonDuplicatedCount)); var i: usize = 0; for (this.columns) |*column| { diff --git a/src/sql/postgres/PostgresSQLConnection.zig b/src/sql/postgres/PostgresSQLConnection.zig index 5c394074d5..0ddbd7c13e 100644 --- a/src/sql/postgres/PostgresSQLConnection.zig +++ b/src/sql/postgres/PostgresSQLConnection.zig @@ -333,7 +333,7 @@ pub fn failWithJSValue(this: *PostgresSQLConnection, value: JSValue) void { } pub fn failFmt(this: *PostgresSQLConnection, code: []const u8, comptime fmt: [:0]const u8, args: anytype) void { - const message = std.fmt.allocPrint(bun.default_allocator, fmt, args) catch bun.outOfMemory(); + const message = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, fmt, args)); defer bun.default_allocator.free(message); const err = createPostgresError(this.globalObject, message, .{ .code = code }) catch |e| this.globalObject.takeError(e); diff --git a/src/sql/postgres/PostgresSQLStatement.zig b/src/sql/postgres/PostgresSQLStatement.zig index 5604cf3106..adf57f0e59 100644 --- a/src/sql/postgres/PostgresSQLStatement.zig +++ b/src/sql/postgres/PostgresSQLStatement.zig @@ -49,7 +49,7 @@ pub fn checkForDuplicateFields(this: *PostgresSQLStatement) void { var seen_numbers = std.ArrayList(u32).init(bun.default_allocator); defer seen_numbers.deinit(); var seen_fields = bun.StringHashMap(void).init(bun.default_allocator); - seen_fields.ensureUnusedCapacity(@intCast(this.fields.len)) catch bun.outOfMemory(); + bun.handleOom(seen_fields.ensureUnusedCapacity(@intCast(this.fields.len))); defer seen_fields.deinit(); // iterate backwards @@ -73,7 +73,7 @@ pub fn checkForDuplicateFields(this: *PostgresSQLStatement) void { field.name_or_index = .duplicate; flags.has_duplicate_columns = true; } else { - seen_numbers.append(index) catch bun.outOfMemory(); + bun.handleOom(seen_numbers.append(index)); } flags.has_indexed_columns = true; @@ -122,7 +122,7 @@ pub fn structure(this: *PostgresSQLStatement, owner: JSValue, globalObject: *jsc nonDuplicatedCount -= 1; } } - const ids = if (nonDuplicatedCount <= jsc.JSObject.maxInlineCapacity()) stack_ids[0..nonDuplicatedCount] else bun.default_allocator.alloc(jsc.JSObject.ExternColumnIdentifier, nonDuplicatedCount) catch bun.outOfMemory(); + const ids = if (nonDuplicatedCount <= jsc.JSObject.maxInlineCapacity()) stack_ids[0..nonDuplicatedCount] else bun.handleOom(bun.default_allocator.alloc(jsc.JSObject.ExternColumnIdentifier, nonDuplicatedCount)); var i: usize = 0; for (this.fields) |*field| { diff --git a/src/string.zig b/src/string.zig index ab6a4351c4..02abda0165 100644 --- a/src/string.zig +++ b/src/string.zig @@ -826,7 +826,7 @@ pub const String = extern struct { jsc.markBinding(@src()); var builder = std.ArrayList(u8).init(bun.default_allocator); defer builder.deinit(); - builder.writer().print(fmt, args) catch bun.outOfMemory(); + bun.handleOom(builder.writer().print(fmt, args)); return bun.cpp.BunString__createUTF8ForJS(globalObject, builder.items.ptr, builder.items.len); } diff --git a/src/string/MutableString.zig b/src/string/MutableString.zig index cae69222cf..163808dd91 100644 --- a/src/string/MutableString.zig +++ b/src/string/MutableString.zig @@ -241,7 +241,7 @@ pub inline fn lenI(self: *MutableString) i32 { } pub fn toOwnedSlice(self: *MutableString) []u8 { - return bun.handleOom(self.list.toOwnedSlice(self.allocator)); + return bun.handleOom(self.list.toOwnedSlice(self.allocator)); // TODO } pub fn toDynamicOwned(self: *MutableString) DynamicOwned([]u8) { diff --git a/src/string/StringJoiner.zig b/src/string/StringJoiner.zig index bb2083d053..c00bf44292 100644 --- a/src/string/StringJoiner.zig +++ b/src/string/StringJoiner.zig @@ -22,7 +22,7 @@ const Node = struct { next: ?*Node = null, pub fn init(joiner_alloc: Allocator, slice: []const u8, slice_alloc: ?Allocator) *Node { - const node = joiner_alloc.create(Node) catch bun.outOfMemory(); + const node = bun.handleOom(joiner_alloc.create(Node)); node.* = .{ .slice = slice, .allocator = NullableAllocator.init(slice_alloc), @@ -51,7 +51,7 @@ pub fn pushStatic(this: *StringJoiner, data: []const u8) void { pub fn pushCloned(this: *StringJoiner, data: []const u8) void { if (data.len == 0) return; this.push( - this.allocator.dupe(u8, data) catch bun.outOfMemory(), + bun.handleOom(this.allocator.dupe(u8, data)), this.allocator, ); } diff --git a/src/string/WTFStringImpl.zig b/src/string/WTFStringImpl.zig index 43fa4cd260..48810d2a3e 100644 --- a/src/string/WTFStringImpl.zig +++ b/src/string/WTFStringImpl.zig @@ -124,7 +124,7 @@ pub const WTFStringImplStruct = extern struct { pub fn toUTF8(this: WTFStringImpl, allocator: std.mem.Allocator) ZigString.Slice { if (this.is8Bit()) { - if (bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| { + if (bun.handleOom(bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()))) |utf8| { return ZigString.Slice.init(allocator, utf8.items); } @@ -133,7 +133,7 @@ pub const WTFStringImplStruct = extern struct { return ZigString.Slice.init( allocator, - bun.strings.toUTF8Alloc(allocator, this.utf16Slice()) catch bun.outOfMemory(), + bun.handleOom(bun.strings.toUTF8Alloc(allocator, this.utf16Slice())), ); } @@ -141,7 +141,7 @@ pub const WTFStringImplStruct = extern struct { pub fn toUTF8WithoutRef(this: WTFStringImpl, allocator: std.mem.Allocator) ZigString.Slice { if (this.is8Bit()) { - if (bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| { + if (bun.handleOom(bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()))) |utf8| { return ZigString.Slice.init(allocator, utf8.items); } @@ -150,24 +150,24 @@ pub const WTFStringImplStruct = extern struct { return ZigString.Slice.init( allocator, - bun.strings.toUTF8Alloc(allocator, this.utf16Slice()) catch bun.outOfMemory(), + bun.handleOom(bun.strings.toUTF8Alloc(allocator, this.utf16Slice())), ); } pub fn toOwnedSliceZ(this: WTFStringImpl, allocator: std.mem.Allocator) [:0]u8 { if (this.is8Bit()) { - if (bun.strings.toUTF8FromLatin1Z(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| { + if (bun.handleOom(bun.strings.toUTF8FromLatin1Z(allocator, this.latin1Slice()))) |utf8| { return utf8.items[0 .. utf8.items.len - 1 :0]; } - return allocator.dupeZ(u8, this.latin1Slice()) catch bun.outOfMemory(); + return bun.handleOom(allocator.dupeZ(u8, this.latin1Slice())); } - return bun.strings.toUTF8AllocZ(allocator, this.utf16Slice()) catch bun.outOfMemory(); + return bun.handleOom(bun.strings.toUTF8AllocZ(allocator, this.utf16Slice())); } pub fn toUTF8IfNeeded(this: WTFStringImpl, allocator: std.mem.Allocator) ?ZigString.Slice { if (this.is8Bit()) { - if (bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()) catch bun.outOfMemory()) |utf8| { + if (bun.handleOom(bun.strings.toUTF8FromLatin1(allocator, this.latin1Slice()))) |utf8| { return ZigString.Slice.init(allocator, utf8.items); } @@ -176,7 +176,7 @@ pub const WTFStringImplStruct = extern struct { return ZigString.Slice.init( allocator, - bun.strings.toUTF8Alloc(allocator, this.utf16Slice()) catch bun.outOfMemory(), + bun.handleOom(bun.strings.toUTF8Alloc(allocator, this.utf16Slice())), ); } diff --git a/src/sys/Error.zig b/src/sys/Error.zig index a5fae58431..7a72e2a5fb 100644 --- a/src/sys/Error.zig +++ b/src/sys/Error.zig @@ -24,8 +24,8 @@ dest: []const u8 = "", pub fn clone(this: *const Error, allocator: std.mem.Allocator) Error { var copy = this.*; - copy.path = allocator.dupe(u8, copy.path) catch bun.outOfMemory(); - copy.dest = allocator.dupe(u8, copy.dest) catch bun.outOfMemory(); + copy.path = bun.handleOom(allocator.dupe(u8, copy.path)); + copy.dest = bun.handleOom(allocator.dupe(u8, copy.dest)); return copy; } diff --git a/src/sys/File.zig b/src/sys/File.zig index aa0abe7b80..921d3d57ac 100644 --- a/src/sys/File.zig +++ b/src/sys/File.zig @@ -277,7 +277,7 @@ pub fn readFillBuf(this: File, buf: []u8) Maybe([]u8) { pub fn readToEndWithArrayList(this: File, list: *std.ArrayList(u8), probably_small: bool) Maybe(usize) { if (probably_small) { - list.ensureUnusedCapacity(64) catch bun.outOfMemory(); + bun.handleOom(list.ensureUnusedCapacity(64)); } else { list.ensureTotalCapacityPrecise( switch (this.getEndPos()) { @@ -286,13 +286,13 @@ pub fn readToEndWithArrayList(this: File, list: *std.ArrayList(u8), probably_sma }, .result => |s| s, } + 16, - ) catch bun.outOfMemory(); + ) catch |err| bun.handleOom(err); } var total: i64 = 0; while (true) { if (list.unusedCapacitySlice().len == 0) { - list.ensureUnusedCapacity(16) catch bun.outOfMemory(); + bun.handleOom(list.ensureUnusedCapacity(16)); } switch (if (comptime Environment.isPosix) @@ -421,7 +421,7 @@ pub fn toSourceAt(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator, if (opts.convert_bom) { if (bun.strings.BOM.detect(bytes)) |bom| { - bytes = bom.removeAndConvertToUTF8AndFree(allocator, bytes) catch bun.outOfMemory(); + bytes = bun.handleOom(bom.removeAndConvertToUTF8AndFree(allocator, bytes)); } } diff --git a/src/transpiler.zig b/src/transpiler.zig index 0b8fbfe805..ecbbd382a5 100644 --- a/src/transpiler.zig +++ b/src/transpiler.zig @@ -376,7 +376,7 @@ pub const Transpiler = struct { } } - transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{s} resolving \"{s}\" (entry point)", .{ @errorName(err), entry_point }) catch bun.outOfMemory(); + bun.handleOom(transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{s} resolving \"{s}\" (entry point)", .{ @errorName(err), entry_point })); return err; }; } @@ -713,7 +713,7 @@ pub const Transpiler = struct { }, }; if (sheet.minify(alloc, bun.css.MinifyOptions.default(), &extra).asErr()) |e| { - transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{} while minifying", .{e.kind}) catch bun.outOfMemory(); + bun.handleOom(transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{} while minifying", .{e.kind})); return null; } const symbols = bun.ast.Symbol.Map{}; @@ -729,7 +729,7 @@ pub const Transpiler = struct { )) { .result => |v| v, .err => |e| { - transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{} while printing", .{e}) catch bun.outOfMemory(); + bun.handleOom(transpiler.log.addErrorFmt(null, logger.Loc.Empty, transpiler.allocator, "{} while printing", .{e})); return null; }, }; diff --git a/src/valkey/valkey.zig b/src/valkey/valkey.zig index 4c5e99cc6b..db21cec0c9 100644 --- a/src/valkey/valkey.zig +++ b/src/valkey/valkey.zig @@ -254,7 +254,7 @@ pub const ValkeyClient = struct { this.in_flight.writeItem(.{ .meta = command.meta, .promise = command.promise, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); total += 1; total_bytelength += command.serialized_data.len; @@ -262,9 +262,9 @@ pub const ValkeyClient = struct { break :brk to_process[0..total]; }; - this.write_buffer.byte_list.ensureUnusedCapacity(this.allocator, total_bytelength) catch bun.outOfMemory(); + bun.handleOom(this.write_buffer.byte_list.ensureUnusedCapacity(this.allocator, total_bytelength)); for (pipelineable_commands) |*command| { - this.write_buffer.write(this.allocator, command.serialized_data) catch bun.outOfMemory(); + bun.handleOom(this.write_buffer.write(this.allocator, command.serialized_data)); // Free the serialized data since we've copied it to the write buffer this.allocator.free(command.serialized_data); } @@ -388,7 +388,7 @@ pub const ValkeyClient = struct { const vm = this.vm; const deferred_failrue = bun.new(DeferredFailure, .{ // This memory is not owned by us. - .message = bun.default_allocator.dupe(u8, message) catch bun.outOfMemory(), + .message = bun.handleOom(bun.default_allocator.dupe(u8, message)), .err = err, .globalThis = vm.global, @@ -789,7 +789,7 @@ pub const ValkeyClient = struct { this.in_flight.writeItem(.{ .meta = offline_cmd.meta, .promise = offline_cmd.promise, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); const data = offline_cmd.serialized_data; if (this.flags.is_authenticated and this.write_buffer.remaining().len == 0) { @@ -801,14 +801,14 @@ pub const ValkeyClient = struct { if (unwritten.len > 0) { // Handle incomplete write. - this.write_buffer.write(this.allocator, unwritten) catch bun.outOfMemory(); + bun.handleOom(this.write_buffer.write(this.allocator, unwritten)); } return true; } // Write the pre-serialized data directly to the output buffer - _ = this.write(data) catch bun.outOfMemory(); + _ = bun.handleOom(this.write(data)); bun.default_allocator.free(data); return true; diff --git a/src/walker_skippable.zig b/src/walker_skippable.zig index f3a443ddaf..079cf90c98 100644 --- a/src/walker_skippable.zig +++ b/src/walker_skippable.zig @@ -71,12 +71,12 @@ pub fn next(self: *Walker) bun.sys.Maybe(?WalkerEntry) { self.name_buffer.shrinkRetainingCapacity(dirname_len); if (self.name_buffer.items.len != 0) { - self.name_buffer.append(path.sep) catch bun.outOfMemory(); + bun.handleOom(self.name_buffer.append(path.sep)); dirname_len += 1; } - self.name_buffer.appendSlice(base.name.slice()) catch bun.outOfMemory(); + bun.handleOom(self.name_buffer.appendSlice(base.name.slice())); const cur_len = self.name_buffer.items.len; - self.name_buffer.append(0) catch bun.outOfMemory(); + bun.handleOom(self.name_buffer.append(0)); if (base.kind == .directory) { const new_dir = switch (bun.openDirForIterationOSPath(top.iter.iter.dir, base.name.slice())) { @@ -87,7 +87,7 @@ pub fn next(self: *Walker) bun.sys.Maybe(?WalkerEntry) { self.stack.append(StackItem{ .iter = DirIterator.iterate(new_dir, if (Environment.isWindows) .u16 else .u8), .dirname_len = cur_len, - }) catch bun.outOfMemory(); + }) catch |err| bun.handleOom(err); top = &self.stack.items[self.stack.items.len - 1]; } } diff --git a/test/internal/ban-limits.json b/test/internal/ban-limits.json index 6198d3d4ef..f0d192258c 100644 --- a/test/internal/ban-limits.json +++ b/test/internal/ban-limits.json @@ -1,6 +1,7 @@ { " != undefined": 0, " == undefined": 0, + " catch bun.outOfMemory()": 0, "!= alloc.ptr": 0, "!= allocator.ptr": 0, ".arguments_old(": 276, diff --git a/test/internal/ban-words.test.ts b/test/internal/ban-words.test.ts index 5dad6acd59..3429f20c79 100644 --- a/test/internal/ban-words.test.ts +++ b/test/internal/ban-words.test.ts @@ -51,6 +51,7 @@ const words: Record = { "globalObject.hasException": { reason: "Incompatible with strict exception checks. Use a CatchScope instead." }, "globalThis.hasException": { reason: "Incompatible with strict exception checks. Use a CatchScope instead." }, "EXCEPTION_ASSERT(!scope.exception())": { reason: "Use scope.assertNoException() instead" }, + " catch bun.outOfMemory()": { reason: "Use bun.handleOom to avoid catching unrelated errors" }, }; const words_keys = [...Object.keys(words)];