Skip to content

Commit

Permalink
fix: avoid dir be gc early.
Browse files Browse the repository at this point in the history
close #644
  • Loading branch information
zhaozg committed Aug 19, 2023
1 parent ff5e902 commit b75c3d6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/fs.c
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,9 @@ static int push_fs_result(lua_State* L, uv_fs_t* req) {
return 1;
}
case UV_FS_READDIR: {
luaL_unref(L, LUA_REGISTRYINDEX, data->data_ref);
data->data_ref = LUA_NOREF;

if(req->result > 0) {
size_t i;
uv_dir_t *dir = (uv_dir_t*)req->ptr;
Expand Down Expand Up @@ -938,6 +941,11 @@ static int luv_fs_readdir(lua_State* L) {

req = (uv_fs_t*)lua_newuserdata(L, uv_req_size(UV_FS));
req->data = luv_setup_req(L, ctx, ref);

// ref the luv_dir_t so it doesn't get garbage collected before the readdir cb
lua_pushvalue(L, 1);
((luv_req_t*)req->data)->data_ref = luaL_ref(L, LUA_REGISTRYINDEX);

FS_CALL(uv_fs_readdir, req, dir->handle);
}

Expand Down
18 changes: 18 additions & 0 deletions tests/test-fs.lua
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,24 @@ return require('lib/tap')(function (test)
end
end, "1.28.0")

test("fs.{open,read,close}dir ref check", function(print, p, expect, uv)
local dir = assert(uv.fs_opendir('.', nil, 50))

local function readdir_cb(err, dirs)
assert(not err)
if dirs then
p(dirs)
end
end

uv.fs_readdir(dir, readdir_cb)
dir = nil
collectgarbage()
collectgarbage()
collectgarbage()

end, "1.28.0")

test("fs.statfs sync", function (print, p, expect, uv)
local stat = assert(uv.fs_statfs("."))
p(stat)
Expand Down

0 comments on commit b75c3d6

Please sign in to comment.