[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
1 changed files with 41 additions and 10 deletions

51
osx.c
View File

@ -478,34 +478,65 @@ static int os_mkdir(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;
while (true) {
char *np = realloc(p, size);
if (!np)
char *p = realloc(buf, size);
if (!p)
goto fail;
p = np;
if (getcwd(p, size))
buf = p;
if (getcwd(buf, size))
break; // got working directory
if (errno != ERANGE)
goto fail;
size <<= 1;
if (size == 0) // PARANOID
if (size == 0) {
// PARANOID
errno = ERANGE;
goto fail;
}
}
lua_pushstring(L, p);
free(p);
lua_pushstring(L, buf);
free(buf);
return 1;
fail:
free(p);
free(buf);
return os_pusherror(L, NULL);
#endif
}
static int os_chdir(lua_State *L)