Skip to content

Commit

Permalink
Merge pull request #417 from vibe-d/fix_gc_filesteam_crash
Browse files Browse the repository at this point in the history
Fix InvalidMemoryOperationError caused by leaking an open FileStream to the GC
  • Loading branch information
l-kramer authored Nov 23, 2024
2 parents ed8ce9d + 99570bc commit 94552db
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
12 changes: 11 additions & 1 deletion source/vibe/core/file.d
Original file line number Diff line number Diff line change
Expand Up @@ -699,9 +699,19 @@ scope:

~this()
nothrow {
import core.memory : GC;
import core.stdc.stdio : fprintf, stderr;

static if (is(typeof(&eventDriver.files.isUnique))) {
if (this.isOpen) {
if (m_ctx.driver is (() @trusted => cast(shared)eventDriver)()) {
if (GC.inFinalizer) {
() @trusted {
auto path = m_ctx.path.toString();
fprintf(stderr, "Warning: Leaking open FileStream handle because the instance was leaked to the GC (%.*s)\n",
cast(int)path.length, path.ptr);
} ();
m_fd = FileFD.invalid;
} else if (m_ctx.driver is (() @trusted => cast(shared)eventDriver)()) {
if (eventDriver.files.isUnique(m_fd)) {
try close();
catch (Exception e) logException(e, "Closing unclosed FileStream during destruction failed");
Expand Down
20 changes: 20 additions & 0 deletions tests/vibe.core.file.gcleak.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/+ dub.sdl:
dependency "vibe-core" path=".."
+/
module test;

import vibe.core.file;


// this test ensures that leaking an open FileStream will not crash the
// application
void main()
{
auto fil = new FileStream;
*fil = openFile("test.tmp", FileMode.createTrunc);
fil = null;

ubyte[] arr;
foreach (i; 0 .. 1000)
arr ~= "1234567890";
}

0 comments on commit 94552db

Please sign in to comment.