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