From 7eb1ed21b7057ab5f1b921f8271eddcf13659737 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Wed, 5 Jun 2024 11:50:42 -0300 Subject: More permissive use of 'errno' Assume that no function will put garbage on errno (although ISO C allows that). If any function during an operation set errno, and the operation result in an error, assume that errno has something to say. --- lauxlib.c | 2 +- liolib.c | 10 ++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/lauxlib.c b/lauxlib.c index baa67ce6..923105ed 100644 --- a/lauxlib.c +++ b/lauxlib.c @@ -811,9 +811,9 @@ LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, } if (c != EOF) lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ + errno = 0; status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); readstatus = ferror(lf.f); - errno = 0; /* no useful error number until here */ if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ diff --git a/liolib.c b/liolib.c index 82f444b0..c5075f3e 100644 --- a/liolib.c +++ b/liolib.c @@ -570,6 +570,7 @@ static int g_read (lua_State *L, FILE *f, int first) { int nargs = lua_gettop(L) - 1; int n, success; clearerr(f); + errno = 0; if (nargs == 0) { /* no arguments? */ success = read_line(L, f, 1); n = first + 1; /* to return 1 result */ @@ -606,10 +607,8 @@ static int g_read (lua_State *L, FILE *f, int first) { } } } - if (ferror(f)) { - errno = 0; /* no relevant errno here */ + if (ferror(f)) return luaL_fileresult(L, 0, NULL); - } if (!success) { lua_pop(L, 1); /* remove last result */ luaL_pushfail(L); /* push nil instead */ @@ -665,6 +664,7 @@ static int io_readline (lua_State *L) { static int g_write (lua_State *L, FILE *f, int arg) { int nargs = lua_gettop(L) - arg; int status = 1; + errno = 0; for (; nargs--; arg++) { if (lua_type(L, arg) == LUA_TNUMBER) { /* optimization: could be done exactly as for strings */ @@ -683,10 +683,8 @@ static int g_write (lua_State *L, FILE *f, int arg) { } if (l_likely(status)) return 1; /* file handle already on stack top */ - else { - errno = 0; /* no relevant errno here */ + else return luaL_fileresult(L, status, NULL); - } } -- cgit v1.2.3-55-g6feb