From 1cc6bb3a90f9a365e1a2a533e83c0dd01d5da613 Mon Sep 17 00:00:00 2001 From: Lorenzo Cogotti Date: Mon, 12 Dec 2022 15:57:54 +0100 Subject: [PATCH] [osx] Improve os_getcwd() on Lua>=52. --- osx.c | 51 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/osx.c b/osx.c index 7945ad1..9219736 100644 --- a/osx.c +++ b/osx.c @@ -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)