source: trunk/src/lua/liolib.c @ 2542

Last change on this file since 2542 was 2542, checked in by sam, 10 years ago

lua: compilation fixes for non-quite-POSIX platforms.

File size: 16.7 KB
Line 
1/*
2** $Id: liolib.c,v 2.108 2011/11/25 12:50:03 roberto Exp $
3** Standard I/O (and system) library
4** See Copyright Notice in lua.h
5*/
6
7#if defined HAVE_CONFIG_H // LOL BEGIN
8#   include "config.h"
9#endif // LOL END
10
11/*
12** POSIX idiosyncrasy!
13** This definition must come before the inclusion of 'stdio.h'; it
14** should not affect non-POSIX systems
15*/
16#if !defined(_FILE_OFFSET_BITS)
17#define _FILE_OFFSET_BITS 64
18#endif
19
20
21#include <errno.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25
26#define liolib_c
27#define LUA_LIB
28
29#include "lua.h"
30
31#include "lauxlib.h"
32#include "lualib.h"
33
34
35
36/*
37** {======================================================
38** lua_popen spawns a new process connected to the current
39** one through the file streams.
40** =======================================================
41*/
42
43#if !defined(lua_popen) /* { */
44
45#if defined(LUA_USE_POPEN)      /* { */
46
47#define lua_popen(L,c,m)        ((void)L, fflush(NULL), popen(c,m))
48#define lua_pclose(L,file)      ((void)L, pclose(file))
49
50#elif defined(LUA_WIN)          /* }{ */
51
52#define lua_popen(L,c,m)                ((void)L, _popen(c,m))
53#define lua_pclose(L,file)              ((void)L, _pclose(file))
54
55
56#else                           /* }{ */
57
58#define lua_popen(L,c,m)                ((void)((void)c, m),  \
59                luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
60#define lua_pclose(L,file)              ((void)((void)L, file), -1)
61
62
63#endif                          /* } */
64
65#endif                  /* } */
66
67/* }====================================================== */
68
69
70/*
71** {======================================================
72** lua_fseek/lua_ftell: configuration for longer offsets
73** =======================================================
74*/
75
76#if !defined(lua_fseek) /* { */
77
78#if defined(LUA_USE_POSIX)
79
80#define l_fseek(f,o,w)          fseeko(f,o,w)
81#define l_ftell(f)              ftello(f)
82#define l_seeknum               off_t
83
84#elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
85   && defined(_MSC_VER) && (_MSC_VER >= 1400)
86/* Windows (but not DDK) and Visual C++ 2005 or higher */
87
88#define l_fseek(f,o,w)          _fseeki64(f,o,w)
89#define l_ftell(f)              _ftelli64(f)
90#define l_seeknum               __int64
91
92#else
93
94#define l_fseek(f,o,w)          fseek(f,o,w)
95#define l_ftell(f)              ftell(f)
96#define l_seeknum               long
97
98#endif
99
100#endif                  /* } */
101
102/* }====================================================== */
103
104
105#define IO_PREFIX       "_IO_"
106#define IO_INPUT        (IO_PREFIX "input")
107#define IO_OUTPUT       (IO_PREFIX "output")
108
109
110typedef luaL_Stream LStream;
111
112
113#define tolstream(L)    ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
114
115#define isclosed(p)     ((p)->closef == NULL)
116
117
118static int io_type (lua_State *L) {
119  LStream *p;
120  luaL_checkany(L, 1);
121  p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
122  if (p == NULL)
123    lua_pushnil(L);  /* not a file */
124  else if (isclosed(p))
125    lua_pushliteral(L, "closed file");
126  else
127    lua_pushliteral(L, "file");
128  return 1;
129}
130
131
132static int f_tostring (lua_State *L) {
133  LStream *p = tolstream(L);
134  if (isclosed(p))
135    lua_pushliteral(L, "file (closed)");
136  else
137    lua_pushfstring(L, "file (%p)", p->f);
138  return 1;
139}
140
141
142static FILE *tofile (lua_State *L) {
143  LStream *p = tolstream(L);
144  if (isclosed(p))
145    luaL_error(L, "attempt to use a closed file");
146  lua_assert(p->f);
147  return p->f;
148}
149
150
151/*
152** When creating file handles, always creates a `closed' file handle
153** before opening the actual file; so, if there is a memory error, the
154** file is not left opened.
155*/
156static LStream *newprefile (lua_State *L) {
157  LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
158  p->closef = NULL;  /* mark file handle as 'closed' */
159  luaL_setmetatable(L, LUA_FILEHANDLE);
160  return p;
161}
162
163
164static int aux_close (lua_State *L) {
165  LStream *p = tolstream(L);
166  lua_CFunction cf = p->closef;
167  p->closef = NULL;  /* mark stream as closed */
168  return (*cf)(L);  /* close it */
169}
170
171
172static int io_close (lua_State *L) {
173  if (lua_isnone(L, 1))  /* no argument? */
174    lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT);  /* use standard output */
175  tofile(L);  /* make sure argument is an open stream */
176  return aux_close(L);
177}
178
179
180static int f_gc (lua_State *L) {
181  LStream *p = tolstream(L);
182  if (!isclosed(p) && p->f != NULL)
183    aux_close(L);  /* ignore closed and incompletely open files */
184  return 0;
185}
186
187
188/*
189** function to close regular files
190*/
191static int io_fclose (lua_State *L) {
192  LStream *p = tolstream(L);
193  int res = fclose(p->f);
194  return luaL_fileresult(L, (res == 0), NULL);
195}
196
197
198static LStream *newfile (lua_State *L) {
199  LStream *p = newprefile(L);
200  p->f = NULL;
201  p->closef = &io_fclose;
202  return p;
203}
204
205
206static void opencheck (lua_State *L, const char *fname, const char *mode) {
207  LStream *p = newfile(L);
208  p->f = fopen(fname, mode);
209  if (p->f == NULL)
210    luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
211}
212
213
214static int io_open (lua_State *L) {
215  const char *filename = luaL_checkstring(L, 1);
216  const char *mode = luaL_optstring(L, 2, "r");
217  LStream *p = newfile(L);
218  int i = 0;
219  /* check whether 'mode' matches '[rwa]%+?b?' */
220  if (!(mode[i] != '\0' && strchr("rwa", mode[i++]) != NULL &&
221       (mode[i] != '+' || ++i) &&  /* skip if char is '+' */
222       (mode[i] != 'b' || ++i) &&  /* skip if char is 'b' */
223       (mode[i] == '\0')))
224    return luaL_error(L, "invalid mode " LUA_QS
225                         " (should match " LUA_QL("[rwa]%%+?b?") ")", mode);
226  p->f = fopen(filename, mode);
227  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
228}
229
230
231/*
232** function to close 'popen' files
233*/
234static int io_pclose (lua_State *L) {
235  LStream *p = tolstream(L);
236  return luaL_execresult(L, lua_pclose(L, p->f));
237}
238
239
240static int io_popen (lua_State *L) {
241  const char *filename = luaL_checkstring(L, 1);
242  const char *mode = luaL_optstring(L, 2, "r");
243  LStream *p = newprefile(L);
244  p->f = lua_popen(L, filename, mode);
245  p->closef = &io_pclose;
246  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
247}
248
249
250static int io_tmpfile (lua_State *L) {
251  LStream *p = newfile(L);
252  p->f = tmpfile();
253  return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
254}
255
256
257static FILE *getiofile (lua_State *L, const char *findex) {
258  LStream *p;
259  lua_getfield(L, LUA_REGISTRYINDEX, findex);
260  p = (LStream *)lua_touserdata(L, -1);
261  if (isclosed(p))
262    luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
263  return p->f;
264}
265
266
267static int g_iofile (lua_State *L, const char *f, const char *mode) {
268  if (!lua_isnoneornil(L, 1)) {
269    const char *filename = lua_tostring(L, 1);
270    if (filename)
271      opencheck(L, filename, mode);
272    else {
273      tofile(L);  /* check that it's a valid file handle */
274      lua_pushvalue(L, 1);
275    }
276    lua_setfield(L, LUA_REGISTRYINDEX, f);
277  }
278  /* return current value */
279  lua_getfield(L, LUA_REGISTRYINDEX, f);
280  return 1;
281}
282
283
284static int io_input (lua_State *L) {
285  return g_iofile(L, IO_INPUT, "r");
286}
287
288
289static int io_output (lua_State *L) {
290  return g_iofile(L, IO_OUTPUT, "w");
291}
292
293
294static int io_readline (lua_State *L);
295
296
297static void aux_lines (lua_State *L, int toclose) {
298  int i;
299  int n = lua_gettop(L) - 1;  /* number of arguments to read */
300  /* ensure that arguments will fit here and into 'io_readline' stack */
301  luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
302  lua_pushvalue(L, 1);  /* file handle */
303  lua_pushinteger(L, n);  /* number of arguments to read */
304  lua_pushboolean(L, toclose);  /* close/not close file when finished */
305  for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1);  /* copy arguments */
306  lua_pushcclosure(L, io_readline, 3 + n);
307}
308
309
310static int f_lines (lua_State *L) {
311  tofile(L);  /* check that it's a valid file handle */
312  aux_lines(L, 0);
313  return 1;
314}
315
316
317static int io_lines (lua_State *L) {
318  int toclose;
319  if (lua_isnone(L, 1)) lua_pushnil(L);  /* at least one argument */
320  if (lua_isnil(L, 1)) {  /* no file name? */
321    lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT);  /* get default input */
322    lua_replace(L, 1);  /* put it at index 1 */
323    tofile(L);  /* check that it's a valid file handle */
324    toclose = 0;  /* do not close it after iteration */
325  }
326  else {  /* open a new file */
327    const char *filename = luaL_checkstring(L, 1);
328    opencheck(L, filename, "r");
329    lua_replace(L, 1);  /* put file at index 1 */
330    toclose = 1;  /* close it after iteration */
331  }
332  aux_lines(L, toclose);
333  return 1;
334}
335
336
337/*
338** {======================================================
339** READ
340** =======================================================
341*/
342
343
344static int read_number (lua_State *L, FILE *f) {
345  lua_Number d;
346  if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
347    lua_pushnumber(L, d);
348    return 1;
349  }
350  else {
351   lua_pushnil(L);  /* "result" to be removed */
352   return 0;  /* read fails */
353  }
354}
355
356
357static int test_eof (lua_State *L, FILE *f) {
358  int c = getc(f);
359  ungetc(c, f);
360  lua_pushlstring(L, NULL, 0);
361  return (c != EOF);
362}
363
364
365static int read_line (lua_State *L, FILE *f, int chop) {
366  luaL_Buffer b;
367  luaL_buffinit(L, &b);
368  for (;;) {
369    size_t l;
370    char *p = luaL_prepbuffer(&b);
371    if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) {  /* eof? */
372      luaL_pushresult(&b);  /* close buffer */
373      return (lua_rawlen(L, -1) > 0);  /* check whether read something */
374    }
375    l = strlen(p);
376    if (l == 0 || p[l-1] != '\n')
377      luaL_addsize(&b, l);
378    else {
379      luaL_addsize(&b, l - chop);  /* chop 'eol' if needed */
380      luaL_pushresult(&b);  /* close buffer */
381      return 1;  /* read at least an `eol' */
382    }
383  }
384}
385
386
387#define MAX_SIZE_T      (~(size_t)0)
388
389static void read_all (lua_State *L, FILE *f) {
390  size_t rlen = LUAL_BUFFERSIZE;  /* how much to read in each cycle */
391  luaL_Buffer b;
392  luaL_buffinit(L, &b);
393  for (;;) {
394    char *p = luaL_prepbuffsize(&b, rlen);
395    size_t nr = fread(p, sizeof(char), rlen, f);
396    luaL_addsize(&b, nr);
397    if (nr < rlen) break;  /* eof? */
398    else if (rlen <= (MAX_SIZE_T / 4))  /* avoid buffers too large */
399      rlen *= 2;  /* double buffer size at each iteration */
400  }
401  luaL_pushresult(&b);  /* close buffer */
402}
403
404
405static int read_chars (lua_State *L, FILE *f, size_t n) {
406  size_t nr;  /* number of chars actually read */
407  char *p;
408  luaL_Buffer b;
409  luaL_buffinit(L, &b);
410  p = luaL_prepbuffsize(&b, n);  /* prepare buffer to read whole block */
411  nr = fread(p, sizeof(char), n, f);  /* try to read 'n' chars */
412  luaL_addsize(&b, nr);
413  luaL_pushresult(&b);  /* close buffer */
414  return (nr > 0);  /* true iff read something */
415}
416
417
418static int g_read (lua_State *L, FILE *f, int first) {
419  int nargs = lua_gettop(L) - 1;
420  int success;
421  int n;
422  clearerr(f);
423  if (nargs == 0) {  /* no arguments? */
424    success = read_line(L, f, 1);
425    n = first+1;  /* to return 1 result */
426  }
427  else {  /* ensure stack space for all results and for auxlib's buffer */
428    luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
429    success = 1;
430    for (n = first; nargs-- && success; n++) {
431      if (lua_type(L, n) == LUA_TNUMBER) {
432        size_t l = (size_t)lua_tointeger(L, n);
433        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
434      }
435      else {
436        const char *p = lua_tostring(L, n);
437        luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
438        switch (p[1]) {
439          case 'n':  /* number */
440            success = read_number(L, f);
441            break;
442          case 'l':  /* line */
443            success = read_line(L, f, 1);
444            break;
445          case 'L':  /* line with end-of-line */
446            success = read_line(L, f, 0);
447            break;
448          case 'a':  /* file */
449            read_all(L, f);  /* read entire file */
450            success = 1; /* always success */
451            break;
452          default:
453            return luaL_argerror(L, n, "invalid format");
454        }
455      }
456    }
457  }
458  if (ferror(f))
459    return luaL_fileresult(L, 0, NULL);
460  if (!success) {
461    lua_pop(L, 1);  /* remove last result */
462    lua_pushnil(L);  /* push nil instead */
463  }
464  return n - first;
465}
466
467
468static int io_read (lua_State *L) {
469  return g_read(L, getiofile(L, IO_INPUT), 1);
470}
471
472
473static int f_read (lua_State *L) {
474  return g_read(L, tofile(L), 2);
475}
476
477
478static int io_readline (lua_State *L) {
479  LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
480  int i;
481  int n = (int)lua_tointeger(L, lua_upvalueindex(2));
482  if (isclosed(p))  /* file is already closed? */
483    return luaL_error(L, "file is already closed");
484  lua_settop(L , 1);
485  for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
486    lua_pushvalue(L, lua_upvalueindex(3 + i));
487  n = g_read(L, p->f, 2);  /* 'n' is number of results */
488  lua_assert(n > 0);  /* should return at least a nil */
489  if (!lua_isnil(L, -n))  /* read at least one value? */
490    return n;  /* return them */
491  else {  /* first result is nil: EOF or error */
492    if (n > 1) {  /* is there error information? */
493      /* 2nd result is error message */
494      return luaL_error(L, "%s", lua_tostring(L, -n + 1));
495    }
496    if (lua_toboolean(L, lua_upvalueindex(3))) {  /* generator created file? */
497      lua_settop(L, 0);
498      lua_pushvalue(L, lua_upvalueindex(1));
499      aux_close(L);  /* close it */
500    }
501    return 0;
502  }
503}
504
505/* }====================================================== */
506
507
508static int g_write (lua_State *L, FILE *f, int arg) {
509  int nargs = lua_gettop(L) - arg;
510  int status = 1;
511  for (; nargs--; arg++) {
512    if (lua_type(L, arg) == LUA_TNUMBER) {
513      /* optimization: could be done exactly as for strings */
514      status = status &&
515          fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
516    }
517    else {
518      size_t l;
519      const char *s = luaL_checklstring(L, arg, &l);
520      status = status && (fwrite(s, sizeof(char), l, f) == l);
521    }
522  }
523  if (status) return 1;  /* file handle already on stack top */
524  else return luaL_fileresult(L, status, NULL);
525}
526
527
528static int io_write (lua_State *L) {
529  return g_write(L, getiofile(L, IO_OUTPUT), 1);
530}
531
532
533static int f_write (lua_State *L) {
534  FILE *f = tofile(L);
535  lua_pushvalue(L, 1);  /* push file at the stack top (to be returned) */
536  return g_write(L, f, 2);
537}
538
539
540static int f_seek (lua_State *L) {
541  static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
542  static const char *const modenames[] = {"set", "cur", "end", NULL};
543  FILE *f = tofile(L);
544  int op = luaL_checkoption(L, 2, "cur", modenames);
545  lua_Number p3 = luaL_optnumber(L, 3, 0);
546  l_seeknum offset = (l_seeknum)p3;
547  luaL_argcheck(L, (lua_Number)offset == p3, 3,
548                  "not an integer in proper range");
549  op = l_fseek(f, offset, mode[op]);
550  if (op)
551    return luaL_fileresult(L, 0, NULL);  /* error */
552  else {
553    lua_pushnumber(L, (lua_Number)l_ftell(f));
554    return 1;
555  }
556}
557
558
559static int f_setvbuf (lua_State *L) {
560  static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
561  static const char *const modenames[] = {"no", "full", "line", NULL};
562  FILE *f = tofile(L);
563  int op = luaL_checkoption(L, 2, NULL, modenames);
564  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
565  int res = setvbuf(f, NULL, mode[op], sz);
566  return luaL_fileresult(L, res == 0, NULL);
567}
568
569
570
571static int io_flush (lua_State *L) {
572  return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
573}
574
575
576static int f_flush (lua_State *L) {
577  return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
578}
579
580
581/*
582** functions for 'io' library
583*/
584static const luaL_Reg iolib[] = {
585  {"close", io_close},
586  {"flush", io_flush},
587  {"input", io_input},
588  {"lines", io_lines},
589  {"open", io_open},
590  {"output", io_output},
591  {"popen", io_popen},
592  {"read", io_read},
593  {"tmpfile", io_tmpfile},
594  {"type", io_type},
595  {"write", io_write},
596  {NULL, NULL}
597};
598
599
600/*
601** methods for file handles
602*/
603static const luaL_Reg flib[] = {
604  {"close", io_close},
605  {"flush", f_flush},
606  {"lines", f_lines},
607  {"read", f_read},
608  {"seek", f_seek},
609  {"setvbuf", f_setvbuf},
610  {"write", f_write},
611  {"__gc", f_gc},
612  {"__tostring", f_tostring},
613  {NULL, NULL}
614};
615
616
617static void createmeta (lua_State *L) {
618  luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */
619  lua_pushvalue(L, -1);  /* push metatable */
620  lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
621  luaL_setfuncs(L, flib, 0);  /* add file methods to new metatable */
622  lua_pop(L, 1);  /* pop new metatable */
623}
624
625
626/*
627** function to (not) close the standard files stdin, stdout, and stderr
628*/
629static int io_noclose (lua_State *L) {
630  LStream *p = tolstream(L);
631  p->closef = &io_noclose;  /* keep file opened */
632  lua_pushnil(L);
633  lua_pushliteral(L, "cannot close standard file");
634  return 2;
635}
636
637
638static void createstdfile (lua_State *L, FILE *f, const char *k,
639                           const char *fname) {
640  LStream *p = newprefile(L);
641  p->f = f;
642  p->closef = &io_noclose;
643  if (k != NULL) {
644    lua_pushvalue(L, -1);
645    lua_setfield(L, LUA_REGISTRYINDEX, k);  /* add file to registry */
646  }
647  lua_setfield(L, -2, fname);  /* add file to module */
648}
649
650
651LUAMOD_API int luaopen_io (lua_State *L) {
652  luaL_newlib(L, iolib);  /* new module */
653  createmeta(L);
654  /* create (and set) default files */
655  createstdfile(L, stdin, IO_INPUT, "stdin");
656  createstdfile(L, stdout, IO_OUTPUT, "stdout");
657  createstdfile(L, stderr, NULL, "stderr");
658  return 1;
659}
660
Note: See TracBrowser for help on using the repository browser.