lua-users home
lua-l archive

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


> To avoid problems with NUL-bytes when reading lines, Lua 5.3-beta
> reads single bytes in a loop instead of using `fgets` like previous
> Lua versions did. For better performance Lua uses unlocked I/O when
> available (i.e. on POSIX machines, though MS Windows has a similar
> API: `_lock_file`, `_unlock_file`, and `_getc_nolock`). I found the
> following piece of code in `liolib.c`:
> 
>     luaL_buffinit(L, &b);
>     l_lockfile(f);
>     while ((c = l_getc(f)) != EOF && c != '\n')
>       luaL_addchar(&b, c);
>     l_unlockfile(f);
> 
> The problem I see here is that `luaL_addchar` could `longjmp` out of
> the loop when memory allocation fails without unlocking the file
> object. [...]

Thanks for the feedback. We will change that code to this:

  luaL_buffinit(L, &b);
  for (;;) {
    char *buff = luaL_prepbuffer(&b);  /* pre-allocate buffer */
    int i = 0;
    l_lockfile(f);  /* no memory errors can happen inside the lock */
    while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
      buff[i++] = c;
    l_unlockfile(f);
    luaL_addsize(&b, i);
    if (i < LUAL_BUFFERSIZE)
      break;
  }

-- Roberto