LCOV - code coverage report
Current view: top level - src - liolib.c Coverage Total Hit
Test: Lua 5.1.5 Lines: 96.8 % 282 273
Test Date: 2024-04-28 10:23:09
Legend: Lines: hit not hit

            Line data    Source code
       1              : /*
       2              : ** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $
       3              : ** Standard I/O (and system) library
       4              : ** See Copyright Notice in lua.h
       5              : */
       6              : 
       7              : 
       8              : #include <errno.h>
       9              : #include <stdio.h>
      10              : #include <stdlib.h>
      11              : #include <string.h>
      12              : 
      13              : #define liolib_c
      14              : #define LUA_LIB
      15              : 
      16              : #include "lua.h"
      17              : 
      18              : #include "lauxlib.h"
      19              : #include "lualib.h"
      20              : 
      21              : 
      22              : 
      23              : #define IO_INPUT        1
      24              : #define IO_OUTPUT       2
      25              : 
      26              : 
      27              : static const char *const fnames[] = {"input", "output"};
      28              : 
      29              : 
      30          145 : static int pushresult (lua_State *L, int i, const char *filename) {
      31          145 :   int en = errno;  /* calls to Lua API may change this value */
      32          145 :   if (i) {
      33          143 :     lua_pushboolean(L, 1);
      34          143 :     return 1;
      35              :   }
      36              :   else {
      37            2 :     lua_pushnil(L);
      38            2 :     if (filename)
      39            2 :       lua_pushfstring(L, "%s: %s", filename, strerror(en));
      40              :     else
      41            0 :       lua_pushfstring(L, "%s", strerror(en));
      42            2 :     lua_pushinteger(L, en);
      43            2 :     return 3;
      44              :   }
      45              : }
      46              : 
      47              : 
      48            2 : static void fileerror (lua_State *L, int arg, const char *filename) {
      49            2 :   lua_pushfstring(L, "%s: %s", filename, strerror(errno));
      50            2 :   luaL_argerror(L, arg, lua_tostring(L, -1));
      51            0 : }
      52              : 
      53              : 
      54              : #define tofilep(L)      ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
      55              : 
      56              : 
      57            9 : static int io_type (lua_State *L) {
      58              :   void *ud;
      59            9 :   luaL_checkany(L, 1);
      60            9 :   ud = lua_touserdata(L, 1);
      61            9 :   lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
      62            9 :   if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
      63            1 :     lua_pushnil(L);  /* not a file */
      64            8 :   else if (*((FILE **)ud) == NULL)
      65            2 :     lua_pushliteral(L, "closed file");
      66              :   else
      67            6 :     lua_pushliteral(L, "file");
      68            9 :   return 1;
      69              : }
      70              : 
      71              : 
      72          233 : static FILE *tofile (lua_State *L) {
      73          233 :   FILE **f = tofilep(L);
      74          233 :   if (*f == NULL)
      75            6 :     luaL_error(L, "attempt to use a closed file");
      76          227 :   return *f;
      77              : }
      78              : 
      79              : 
      80              : 
      81              : /*
      82              : ** When creating file handles, always creates a `closed' file handle
      83              : ** before opening the actual file; so, if there is a memory error, the
      84              : ** file is not left opened.
      85              : */
      86          359 : static FILE **newfile (lua_State *L) {
      87          359 :   FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
      88          359 :   *pf = NULL;  /* file handle is currently `closed' */
      89          359 :   luaL_getmetatable(L, LUA_FILEHANDLE);
      90          359 :   lua_setmetatable(L, -2);
      91          359 :   return pf;
      92              : }
      93              : 
      94              : 
      95              : /*
      96              : ** function to (not) close the standard files stdin, stdout, and stderr
      97              : */
      98          225 : static int io_noclose (lua_State *L) {
      99          225 :   lua_pushnil(L);
     100          225 :   lua_pushliteral(L, "cannot close standard file");
     101          225 :   return 2;
     102              : }
     103              : 
     104              : 
     105              : /*
     106              : ** function to close 'popen' files
     107              : */
     108           53 : static int io_pclose (lua_State *L) {
     109           53 :   FILE **p = tofilep(L);
     110           53 :   int ok = lua_pclose(L, *p);
     111           53 :   *p = NULL;
     112           53 :   return pushresult(L, ok, NULL);
     113              : }
     114              : 
     115              : 
     116              : /*
     117              : ** function to close regular files
     118              : */
     119           53 : static int io_fclose (lua_State *L) {
     120           53 :   FILE **p = tofilep(L);
     121           53 :   int ok = (fclose(*p) == 0);
     122           53 :   *p = NULL;
     123           53 :   return pushresult(L, ok, NULL);
     124              : }
     125              : 
     126              : 
     127          331 : static int aux_close (lua_State *L) {
     128          331 :   lua_getfenv(L, 1);
     129          331 :   lua_getfield(L, -1, "__close");
     130          331 :   return (lua_tocfunction(L, -1))(L);
     131              : }
     132              : 
     133              : 
     134          100 : static int io_close (lua_State *L) {
     135          100 :   if (lua_isnone(L, 1))
     136            3 :     lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
     137          100 :   tofile(L);  /* make sure argument is a file */
     138           98 :   return aux_close(L);
     139              : }
     140              : 
     141              : 
     142          332 : static int io_gc (lua_State *L) {
     143          332 :   FILE *f = *tofilep(L);
     144              :   /* ignore closed files */
     145          332 :   if (f != NULL)
     146          232 :     aux_close(L);
     147          332 :   return 0;
     148              : }
     149              : 
     150              : 
     151           12 : static int io_tostring (lua_State *L) {
     152           12 :   FILE *f = *tofilep(L);
     153           12 :   if (f == NULL)
     154            2 :     lua_pushliteral(L, "file (closed)");
     155              :   else
     156           10 :     lua_pushfstring(L, "file (%p)", f);
     157           12 :   return 1;
     158              : }
     159              : 
     160              : 
     161           50 : static int io_open (lua_State *L) {
     162           50 :   const char *filename = luaL_checkstring(L, 1);
     163           50 :   const char *mode = luaL_optstring(L, 2, "r");
     164           50 :   FILE **pf = newfile(L);
     165           50 :   *pf = fopen(filename, mode);
     166           50 :   return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
     167              : }
     168              : 
     169              : 
     170              : /*
     171              : ** this function has a separated environment, which defines the
     172              : ** correct __close for 'popen' files
     173              : */
     174           53 : static int io_popen (lua_State *L) {
     175           53 :   const char *filename = luaL_checkstring(L, 1);
     176           53 :   const char *mode = luaL_optstring(L, 2, "r");
     177           53 :   FILE **pf = newfile(L);
     178           53 :   *pf = lua_popen(L, filename, mode);
     179           53 :   return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
     180              : }
     181              : 
     182              : 
     183            2 : static int io_tmpfile (lua_State *L) {
     184            2 :   FILE **pf = newfile(L);
     185            2 :   *pf = tmpfile();
     186            2 :   return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
     187              : }
     188              : 
     189              : 
     190            8 : static FILE *getiofile (lua_State *L, int findex) {
     191              :   FILE *f;
     192            8 :   lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
     193            8 :   f = *(FILE **)lua_touserdata(L, -1);
     194            8 :   if (f == NULL)
     195            0 :     luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
     196            8 :   return f;
     197              : }
     198              : 
     199              : 
     200           11 : static int g_iofile (lua_State *L, int f, const char *mode) {
     201           11 :   if (!lua_isnoneornil(L, 1)) {
     202            7 :     const char *filename = lua_tostring(L, 1);
     203            7 :     if (filename) {
     204            3 :       FILE **pf = newfile(L);
     205            3 :       *pf = fopen(filename, mode);
     206            3 :       if (*pf == NULL)
     207            1 :         fileerror(L, 1, filename);
     208              :     }
     209              :     else {
     210            4 :       tofile(L);  /* check that it's a valid file handle */
     211            4 :       lua_pushvalue(L, 1);
     212              :     }
     213            6 :     lua_rawseti(L, LUA_ENVIRONINDEX, f);
     214              :   }
     215              :   /* return current value */
     216           10 :   lua_rawgeti(L, LUA_ENVIRONINDEX, f);
     217           10 :   return 1;
     218              : }
     219              : 
     220              : 
     221            6 : static int io_input (lua_State *L) {
     222            6 :   return g_iofile(L, IO_INPUT, "r");
     223              : }
     224              : 
     225              : 
     226            5 : static int io_output (lua_State *L) {
     227            5 :   return g_iofile(L, IO_OUTPUT, "w");
     228              : }
     229              : 
     230              : 
     231              : static int io_readline (lua_State *L);
     232              : 
     233              : 
     234            7 : static void aux_lines (lua_State *L, int idx, int toclose) {
     235            7 :   lua_pushvalue(L, idx);
     236            7 :   lua_pushboolean(L, toclose);  /* close/not close file when finished */
     237            7 :   lua_pushcclosure(L, io_readline, 2);
     238            7 : }
     239              : 
     240              : 
     241            6 : static int f_lines (lua_State *L) {
     242            6 :   tofile(L);  /* check that it's a valid file handle */
     243            6 :   aux_lines(L, 1, 0);
     244            6 :   return 1;
     245              : }
     246              : 
     247              : 
     248            4 : static int io_lines (lua_State *L) {
     249            4 :   if (lua_isnoneornil(L, 1)) {  /* no arguments? */
     250              :     /* will iterate over default input */
     251            2 :     lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
     252            2 :     return f_lines(L);
     253              :   }
     254              :   else {
     255            2 :     const char *filename = luaL_checkstring(L, 1);
     256            2 :     FILE **pf = newfile(L);
     257            2 :     *pf = fopen(filename, "r");
     258            2 :     if (*pf == NULL)
     259            1 :       fileerror(L, 1, filename);
     260            1 :     aux_lines(L, lua_gettop(L), 1);
     261            1 :     return 1;
     262              :   }
     263              : }
     264              : 
     265              : 
     266              : /*
     267              : ** {======================================================
     268              : ** READ
     269              : ** =======================================================
     270              : */
     271              : 
     272              : 
     273           14 : static int read_number (lua_State *L, FILE *f) {
     274              :   lua_Number d;
     275           14 :   if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
     276           12 :     lua_pushnumber(L, d);
     277           12 :     return 1;
     278              :   }
     279              :   else {
     280            2 :     lua_pushnil(L);  /* "result" to be removed */
     281            2 :     return 0;  /* read fails */
     282              :   }
     283              : }
     284              : 
     285              : 
     286            1 : static int test_eof (lua_State *L, FILE *f) {
     287            1 :   int c = getc(f);
     288            1 :   ungetc(c, f);
     289            1 :   lua_pushlstring(L, NULL, 0);
     290            1 :   return (c != EOF);
     291              : }
     292              : 
     293              : 
     294          249 : static int read_line (lua_State *L, FILE *f) {
     295              :   luaL_Buffer b;
     296          249 :   luaL_buffinit(L, &b);
     297            0 :   for (;;) {
     298              :     size_t l;
     299          249 :     char *p = luaL_prepbuffer(&b);
     300          249 :     if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) {  /* eof? */
     301           16 :       luaL_pushresult(&b);  /* close buffer */
     302           16 :       return (lua_objlen(L, -1) > 0);  /* check whether read something */
     303              :     }
     304          233 :     l = strlen(p);
     305          233 :     if (l == 0 || p[l-1] != '\n')
     306            0 :       luaL_addsize(&b, l);
     307              :     else {
     308          233 :       luaL_addsize(&b, l - 1);  /* do not include `eol' */
     309          233 :       luaL_pushresult(&b);  /* close buffer */
     310          233 :       return 1;  /* read at least an `eol' */
     311              :     }
     312              :   }
     313              : }
     314              : 
     315              : 
     316            4 : static int read_chars (lua_State *L, FILE *f, size_t n) {
     317              :   size_t rlen;  /* how much to read */
     318              :   size_t nr;  /* number of chars actually read */
     319              :   luaL_Buffer b;
     320            4 :   luaL_buffinit(L, &b);
     321            4 :   rlen = LUAL_BUFFERSIZE;  /* try to read that much each time */
     322              :   do {
     323            4 :     char *p = luaL_prepbuffer(&b);
     324            4 :     if (rlen > n) rlen = n;  /* cannot read more than asked */
     325            4 :     nr = fread(p, sizeof(char), rlen, f);
     326            4 :     luaL_addsize(&b, nr);
     327            4 :     n -= nr;  /* still have to read `n' chars */
     328            4 :   } while (n > 0 && nr == rlen);  /* until end of count or eof */
     329            4 :   luaL_pushresult(&b);  /* close buffer */
     330            4 :   return (n == 0 || lua_objlen(L, -1) > 0);
     331              : }
     332              : 
     333              : 
     334           88 : static int g_read (lua_State *L, FILE *f, int first) {
     335           88 :   int nargs = lua_gettop(L) - 1;
     336              :   int success;
     337              :   int n;
     338           88 :   clearerr(f);
     339           88 :   if (nargs == 0) {  /* no arguments? */
     340            3 :     success = read_line(L, f);
     341            3 :     n = first+1;  /* to return 1 result */
     342              :   }
     343              :   else {  /* ensure stack space for all results and for auxlib's buffer */
     344           85 :     luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
     345           85 :     success = 1;
     346          177 :     for (n = first; nargs-- && success; n++) {
     347           93 :       if (lua_type(L, n) == LUA_TNUMBER) {
     348            4 :         size_t l = (size_t)lua_tointeger(L, n);
     349            4 :         success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
     350              :       }
     351              :       else {
     352           89 :         const char *p = lua_tostring(L, n);
     353           89 :         luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
     354           89 :         switch (p[1]) {
     355           14 :           case 'n':  /* number */
     356           14 :             success = read_number(L, f);
     357           14 :             break;
     358           73 :           case 'l':  /* line */
     359           73 :             success = read_line(L, f);
     360           73 :             break;
     361            1 :           case 'a':  /* file */
     362            1 :             read_chars(L, f, ~((size_t)0));  /* read MAX_SIZE_T chars */
     363            1 :             success = 1; /* always success */
     364            1 :             break;
     365            1 :           default:
     366            1 :             return luaL_argerror(L, n, "invalid format");
     367              :         }
     368              :       }
     369              :     }
     370              :   }
     371           87 :   if (ferror(f))
     372            0 :     return pushresult(L, 0, NULL);
     373           87 :   if (!success) {
     374           14 :     lua_pop(L, 1);  /* remove last result */
     375           14 :     lua_pushnil(L);  /* push nil instead */
     376              :   }
     377           87 :   return n - first;
     378              : }
     379              : 
     380              : 
     381            5 : static int io_read (lua_State *L) {
     382            5 :   return g_read(L, getiofile(L, IO_INPUT), 1);
     383              : }
     384              : 
     385              : 
     386           84 : static int f_read (lua_State *L) {
     387           84 :   return g_read(L, tofile(L), 2);
     388              : }
     389              : 
     390              : 
     391          173 : static int io_readline (lua_State *L) {
     392          173 :   FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
     393              :   int sucess;
     394          173 :   if (f == NULL)  /* file is already closed? */
     395            0 :     luaL_error(L, "file is already closed");
     396          173 :   sucess = read_line(L, f);
     397          173 :   if (ferror(f))
     398            0 :     return luaL_error(L, "%s", strerror(errno));
     399          173 :   if (sucess) return 1;
     400              :   else {  /* EOF */
     401            4 :     if (lua_toboolean(L, lua_upvalueindex(2))) {  /* generator created file? */
     402            1 :       lua_settop(L, 0);
     403            1 :       lua_pushvalue(L, lua_upvalueindex(1));
     404            1 :       aux_close(L);  /* close it */
     405              :     }
     406            4 :     return 0;
     407              :   }
     408              : }
     409              : 
     410              : /* }====================================================== */
     411              : 
     412              : 
     413           32 : static int g_write (lua_State *L, FILE *f, int arg) {
     414           32 :   int nargs = lua_gettop(L) - 1;
     415           32 :   int status = 1;
     416           65 :   for (; nargs--; arg++) {
     417           33 :     if (lua_type(L, arg) == LUA_TNUMBER) {
     418              :       /* optimization: could be done exactly as for strings */
     419            2 :       status = status &&
     420            1 :           fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
     421              :     }
     422              :     else {
     423              :       size_t l;
     424           32 :       const char *s = luaL_checklstring(L, arg, &l);
     425           32 :       status = status && (fwrite(s, sizeof(char), l, f) == l);
     426              :     }
     427              :   }
     428           32 :   return pushresult(L, status, NULL);
     429              : }
     430              : 
     431              : 
     432            2 : static int io_write (lua_State *L) {
     433            2 :   return g_write(L, getiofile(L, IO_OUTPUT), 1);
     434              : }
     435              : 
     436              : 
     437           31 : static int f_write (lua_State *L) {
     438           31 :   return g_write(L, tofile(L), 2);
     439              : }
     440              : 
     441              : 
     442            3 : static int f_seek (lua_State *L) {
     443              :   static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
     444              :   static const char *const modenames[] = {"set", "cur", "end", NULL};
     445            3 :   FILE *f = tofile(L);
     446            2 :   int op = luaL_checkoption(L, 2, "cur", modenames);
     447            1 :   long offset = luaL_optlong(L, 3, 0);
     448            1 :   op = fseek(f, offset, mode[op]);
     449            1 :   if (op)
     450            0 :     return pushresult(L, 0, NULL);  /* error */
     451              :   else {
     452            1 :     lua_pushinteger(L, ftell(f));
     453            1 :     return 1;
     454              :   }
     455              : }
     456              : 
     457              : 
     458            3 : static int f_setvbuf (lua_State *L) {
     459              :   static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
     460              :   static const char *const modenames[] = {"no", "full", "line", NULL};
     461            3 :   FILE *f = tofile(L);
     462            3 :   int op = luaL_checkoption(L, 2, NULL, modenames);
     463            3 :   lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
     464            3 :   int res = setvbuf(f, NULL, mode[op], sz);
     465            3 :   return pushresult(L, res == 0, NULL);
     466              : }
     467              : 
     468              : 
     469              : 
     470            1 : static int io_flush (lua_State *L) {
     471            1 :   return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
     472              : }
     473              : 
     474              : 
     475            2 : static int f_flush (lua_State *L) {
     476            2 :   return pushresult(L, fflush(tofile(L)) == 0, NULL);
     477              : }
     478              : 
     479              : 
     480              : static const luaL_Reg iolib[] = {
     481              :   {"close", io_close},
     482              :   {"flush", io_flush},
     483              :   {"input", io_input},
     484              :   {"lines", io_lines},
     485              :   {"open", io_open},
     486              :   {"output", io_output},
     487              :   {"popen", io_popen},
     488              :   {"read", io_read},
     489              :   {"tmpfile", io_tmpfile},
     490              :   {"type", io_type},
     491              :   {"write", io_write},
     492              :   {NULL, NULL}
     493              : };
     494              : 
     495              : 
     496              : static const luaL_Reg flib[] = {
     497              :   {"close", io_close},
     498              :   {"flush", f_flush},
     499              :   {"lines", f_lines},
     500              :   {"read", f_read},
     501              :   {"seek", f_seek},
     502              :   {"setvbuf", f_setvbuf},
     503              :   {"write", f_write},
     504              :   {"__gc", io_gc},
     505              :   {"__tostring", io_tostring},
     506              :   {NULL, NULL}
     507              : };
     508              : 
     509              : 
     510           83 : static void createmeta (lua_State *L) {
     511           83 :   luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */
     512           83 :   lua_pushvalue(L, -1);  /* push metatable */
     513           83 :   lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
     514           83 :   luaL_register(L, NULL, flib);  /* file methods */
     515           83 : }
     516              : 
     517              : 
     518          249 : static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
     519          249 :   *newfile(L) = f;
     520          249 :   if (k > 0) {
     521          166 :     lua_pushvalue(L, -1);
     522          166 :     lua_rawseti(L, LUA_ENVIRONINDEX, k);
     523              :   }
     524          249 :   lua_pushvalue(L, -2);  /* copy environment */
     525          249 :   lua_setfenv(L, -2);  /* set it */
     526          249 :   lua_setfield(L, -3, fname);
     527          249 : }
     528              : 
     529              : 
     530          249 : static void newfenv (lua_State *L, lua_CFunction cls) {
     531          249 :   lua_createtable(L, 0, 1);
     532          249 :   lua_pushcfunction(L, cls);
     533          249 :   lua_setfield(L, -2, "__close");
     534          249 : }
     535              : 
     536              : 
     537           83 : LUALIB_API int luaopen_io (lua_State *L) {
     538           83 :   createmeta(L);
     539              :   /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
     540           83 :   newfenv(L, io_fclose);
     541           83 :   lua_replace(L, LUA_ENVIRONINDEX);
     542              :   /* open library */
     543           83 :   luaL_register(L, LUA_IOLIBNAME, iolib);
     544              :   /* create (and set) default files */
     545           83 :   newfenv(L, io_noclose);  /* close function for default files */
     546           83 :   createstdfile(L, stdin, IO_INPUT, "stdin");
     547           83 :   createstdfile(L, stdout, IO_OUTPUT, "stdout");
     548           83 :   createstdfile(L, stderr, 0, "stderr");
     549           83 :   lua_pop(L, 1);  /* pop environment for default files */
     550           83 :   lua_getfield(L, -1, "popen");
     551           83 :   newfenv(L, io_pclose);  /* create environment for 'popen' */
     552           83 :   lua_setfenv(L, -2);  /* set fenv for 'popen' */
     553           83 :   lua_pop(L, 1);  /* pop 'popen' */
     554           83 :   return 1;
     555              : }
     556              : 
        

Generated by: LCOV version 2.0-1