[osx] Improve os_getcwd() on Lua>=52.

This commit is contained in:
Lorenzo Cogotti 2022-12-12 15:57:54 +01:00
parent abb3d56a45
commit 1cc6bb3a90

51
osx.c
View File

@ -478,34 +478,65 @@ static int os_mkdir(lua_State *L)
static int os_getcwd(lua_State *L) static int os_getcwd(lua_State *L)
{ {
char *p = NULL; #if LUA_VERSION_NUM >= 502
luaL_Buffer buf;
char *p;
size_t size = 128;
luaL_buffinit(L, &buf);
while (true) {
p = luaL_prepbuffsize(&buf, size);
if (getcwd(p, size))
break; // got working directory
if (errno != ERANGE)
return os_pusherror(L, NULL);
size <<= 1;
if (size == 0) {
// PARANOID
errno = ERANGE;
return os_pusherror(L, NULL);
}
}
luaL_pushresultsize(&buf, strlen(p));
return 1;
#else
// Unfortunately this leaks memory if Lua ever decides to longjmp().
// After 12 years since Lua 5.2 introduction,
// that's what we get with LuaJIT.
char *buf = NULL;
size_t size = 128; size_t size = 128;
while (true) { while (true) {
char *np = realloc(p, size); char *p = realloc(buf, size);
if (!np) if (!p)
goto fail; goto fail;
p = np; buf = p;
if (getcwd(p, size)) if (getcwd(buf, size))
break; // got working directory break; // got working directory
if (errno != ERANGE) if (errno != ERANGE)
goto fail; goto fail;
size <<= 1; size <<= 1;
if (size == 0) // PARANOID if (size == 0) {
// PARANOID
errno = ERANGE;
goto fail; goto fail;
} }
}
lua_pushstring(L, p); lua_pushstring(L, buf);
free(p); free(buf);
return 1; return 1;
fail: fail:
free(p); free(buf);
return os_pusherror(L, NULL); return os_pusherror(L, NULL);
#endif
} }
static int os_chdir(lua_State *L) static int os_chdir(lua_State *L)