lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I think I've just found a bug in Lua.

In liolib.c, there's the following code in aux_close():

    int ok = (pclose(f) != -1) || (fclose(f) == 0);

That is, it first tries to close the file with pclose(), and if that fails, it 
tries to close the file with fclose(). It does this on all files, regardless 
of how they were opened.

Unfortunately, it's not legal to call pclose() on a file that wasn't allocated 
with popen(). This causes it to fall over on my embedded device. My libc's 
implementation of pclose() calls fclose() and then wait(). wait() is failing 
because there are no children; which means than pclose() is returning an 
error code; which is causing Lua to call fclose() again; which is causing a 
crash.

I refer you to the Posix standard:

http://www.opengroup.org/onlinepubs/009695399/functions/pclose.html
> If the stream pointed to by stream was not created by popen(), historical
> implementations of pclose() return -1 without setting errno. To avoid
> requiring pclose() to set errno in this case, IEEE Std 1003.1-2001 makes the
> behavior unspecified. An application should not use pclose() to close any
> stream that was not created by popen().    

Most desktop libc implementations check to make sure the file was allocated by 
popen() before touching it, which is why this hasn't come up before, but as 
the above document says, this isn't required.

Fixing this is going to be annoying, because it means that the file userdata 
is going to have to become two quads instead of just one, because Lua is 
going to have to keep track of how the file was opened. Alternatively it 
might be easier to keep a table somewhere of fopen() files vs. popen() files. 
I don't think there's any standard-compliant way of distinguishing the two 
types at run-time.

Any comments?

-- 
+- David Given --McQ-+ "Quantum materiae materietur marmota monax si
|  dg@cowlark.com    | marmota monax meteriam possit materiari?" --- Henry
| (dg@tao-group.com) | Beard
+- www.cowlark.com --+