[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: is it possible to make longjmp-free Lua?
- From: "Juris Kalnins" <juris@...>
- Date: Mon, 27 Jul 2009 12:55:23 +0300
On Mon, 27 Jul 2009 12:35:02 +0300, Jerome Vuarand
<jerome.vuarand@gmail.com> wrote:
2009/7/27 Juris Kalnins <juris@mt.lv>:
For example lua_newuserdata is guaranteed to return a non-NULL
pointer. Therefore C code that use that API is unlikely to check the
validity of that pointer. Another example is lua_touserdata calls in a
userdata metamethod: the metamethod wouldn't be called if the first
argument was not a valid userdata, so the return pointer of
lua_touserdata won't be checked.
Thank you for pointing this out. If I can know likely maximum userdata
allocation size, it might be possible to add a "yellow zone" to the memory
allocator, when it both returns allocated memory and raises out-of-memory
if there is less than specified amount of memory left. (and keep an
emergency piece of continuous memory for this case).
But C resource handling and Lua exceptions are a tricky thing anyway. It
is really easy to write resource leaks.
Just an example, from quickly looking at a random library (lposix.c)
static int Pdir(lua_State *L) /** dir([path]) */
{
const char *path = luaL_optstring(L, 1, ".");
DIR *d = opendir(path);
if (d == NULL)
return pusherror(L, path);
else
{
int i;
struct dirent *entry;
lua_newtable(L);
for (i=1; (entry = readdir(d)) != NULL; i++)
{
lua_pushstring(L, entry->d_name);
-> ^^^^^^ Who is going to close DIR *d, if this call
runs out of memory?
lua_rawseti(L, -2, i);
}
closedir(d);
lua_pushinteger(L, i-1);
return 2;
}
}
Having longjmp-free errors would actually _fix_ this. :)
Lua error mechanism only require setjmp/longjmp, not C++ exceptions.
Are you sure -fexceptions is needed for setjmp/longjmp to work ? IIRC
-fexceptions generate data needed for destructors to be called, which
setjmp/longjmp and thus Lua error mechanism do not need.
But c++ does need it. It runs destructors on function exit. You cannot
simply discard stack frames in C++. (And see above example for why it is
bad for C, too).