From e171f04ce6233b7d2360902c758b87a72de77dfd Mon Sep 17 00:00:00 2001 From: argosphil Date: Wed, 7 Feb 2024 02:11:25 +0000 Subject: [PATCH] Fix ref-counting of Bun.file(0) etc. (#8687) (#8741) * Test for #8687 * Fix reference counting of Bun.file(0) etc. (#8687) Fixes #8687. --- src/bun.js/webcore/blob.zig | 25 ++++++++++++------------- test/js/bun/io/bun-write.test.js | 8 ++++++++ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index e01a81d86d..f11efabc0a 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -1553,20 +1553,19 @@ pub const Blob = struct { break :brk copy; }, .fd => { - switch (bun.FDTag.get(path_or_fd.fd)) { - .stdin => return Blob.initWithStore( - vm.rareData().stdin(), + const optional_store: ?*Store = switch (bun.FDTag.get(path_or_fd.fd)) { + .stdin => vm.rareData().stdin(), + .stderr => vm.rareData().stderr(), + .stdout => vm.rareData().stdout(), + else => null, + }; + + if (optional_store) |store| { + store.ref(); + return Blob.initWithStore( + store, globalThis, - ), - .stderr => return Blob.initWithStore( - vm.rareData().stderr(), - globalThis, - ), - .stdout => return Blob.initWithStore( - vm.rareData().stdout(), - globalThis, - ), - else => {}, + ); } break :brk path_or_fd.*; }, diff --git a/test/js/bun/io/bun-write.test.js b/test/js/bun/io/bun-write.test.js index e4b31baa8c..33c5c61d41 100644 --- a/test/js/bun/io/bun-write.test.js +++ b/test/js/bun/io/bun-write.test.js @@ -310,6 +310,14 @@ it("Bun.write(Bun.stderr, 'new TextEncoder().encode(Bun.write STDERR TEST'))", a expect(await Bun.write(Bun.stderr, new TextEncoder().encode("\nBun.write STDERR TEST\n\n"))).toBe(24); }); +it("Bun.file(0) survives GC", async () => { + for (let i = 0; i < 10; i++) { + let f = Bun.file(0); + await gcTick(); + expect(Bun.inspect(f)).toContain("FileRef (fd: 0)"); + } +}); + // FLAKY TEST // Since Bun.file is resolved lazily, this needs to specifically be checked it("Bun.write('output.html', HTMLRewriter.transform(Bun.file)))", async done => {