1 /* $NetBSD: liolib.c,v 1.4 2015/10/08 13:21:00 mbalmer Exp $ */
4 ** Id: liolib.c,v 2.144 2015/04/03 18:41:57 roberto Exp
5 ** Standard I/O (and system) library
6 ** See Copyright Notice in lua.h
28 #if !defined(l_checkmode)
31 ** Check whether 'mode' matches '[rwa]%+?b?'.
32 ** Change this macro to accept other modes for 'fopen' besides
35 #define l_checkmode(mode) \
36 (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
37 (*mode != '+' || ++mode) && /* skip if char is '+' */ \
38 (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
44 ** {======================================================
45 ** l_popen spawns a new process connected to the current
46 ** one through the file streams.
47 ** =======================================================
50 #if !defined(l_popen) /* { */
52 #if defined(LUA_USE_POSIX) /* { */
54 #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
55 #define l_pclose(L,file) (pclose(file))
57 #elif defined(LUA_USE_WINDOWS) /* }{ */
59 #define l_popen(L,c,m) (_popen(c,m))
60 #define l_pclose(L,file) (_pclose(file))
64 /* ISO C definitions */
65 #define l_popen(L,c,m) \
66 ((void)((void)c, m), \
67 luaL_error(L, "'popen' not supported"), \
69 #define l_pclose(L,file) ((void)L, (void)file, -1)
75 /* }====================================================== */
78 #if !defined(l_getc) /* { */
80 #if defined(LUA_USE_POSIX)
81 #define l_getc(f) getc_unlocked(f)
82 #define l_lockfile(f) flockfile(f)
83 #define l_unlockfile(f) funlockfile(f)
85 #define l_getc(f) getc(f)
86 #define l_lockfile(f) ((void)0)
87 #define l_unlockfile(f) ((void)0)
94 ** {======================================================
95 ** l_fseek: configuration for longer offsets
96 ** =======================================================
99 #if !defined(l_fseek) /* { */
101 #if defined(LUA_USE_POSIX) /* { */
103 #include <sys/types.h>
105 #define l_fseek(f,o,w) fseeko(f,o,w)
106 #define l_ftell(f) ftello(f)
107 #define l_seeknum off_t
109 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
110 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
112 /* Windows (but not DDK) and Visual C++ 2005 or higher */
113 #define l_fseek(f,o,w) _fseeki64(f,o,w)
114 #define l_ftell(f) _ftelli64(f)
115 #define l_seeknum __int64
119 /* ISO C definitions */
120 #define l_fseek(f,o,w) fseek(f,o,w)
121 #define l_ftell(f) ftell(f)
122 #define l_seeknum long
128 /* }====================================================== */
131 #define IO_PREFIX "_IO_"
132 #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
133 #define IO_INPUT (IO_PREFIX "input")
134 #define IO_OUTPUT (IO_PREFIX "output")
137 typedef luaL_Stream LStream
;
140 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
142 #define isclosed(p) ((p)->closef == NULL)
145 static int io_type (lua_State
*L
) {
148 p
= (LStream
*)luaL_testudata(L
, 1, LUA_FILEHANDLE
);
150 lua_pushnil(L
); /* not a file */
151 else if (isclosed(p
))
152 lua_pushliteral(L
, "closed file");
154 lua_pushliteral(L
, "file");
159 static int f_tostring (lua_State
*L
) {
160 LStream
*p
= tolstream(L
);
162 lua_pushliteral(L
, "file (closed)");
164 lua_pushfstring(L
, "file (%p)", p
->f
);
169 static FILE *tofile (lua_State
*L
) {
170 LStream
*p
= tolstream(L
);
172 luaL_error(L
, "attempt to use a closed file");
179 ** When creating file handles, always creates a 'closed' file handle
180 ** before opening the actual file; so, if there is a memory error, the
181 ** file is not left opened.
183 static LStream
*newprefile (lua_State
*L
) {
184 LStream
*p
= (LStream
*)lua_newuserdata(L
, sizeof(LStream
));
185 p
->closef
= NULL
; /* mark file handle as 'closed' */
186 luaL_setmetatable(L
, LUA_FILEHANDLE
);
192 ** Calls the 'close' function from a file handle. The 'volatile' avoids
193 ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
196 static int aux_close (lua_State
*L
) {
197 LStream
*p
= tolstream(L
);
198 volatile lua_CFunction cf
= p
->closef
;
199 p
->closef
= NULL
; /* mark stream as closed */
200 return (*cf
)(L
); /* close it */
204 static int io_close (lua_State
*L
) {
205 if (lua_isnone(L
, 1)) /* no argument? */
206 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_OUTPUT
); /* use standard output */
207 tofile(L
); /* make sure argument is an open stream */
212 static int f_gc (lua_State
*L
) {
213 LStream
*p
= tolstream(L
);
214 if (!isclosed(p
) && p
->f
!= NULL
)
215 aux_close(L
); /* ignore closed and incompletely open files */
221 ** function to close regular files
223 static int io_fclose (lua_State
*L
) {
224 LStream
*p
= tolstream(L
);
225 int res
= fclose(p
->f
);
226 return luaL_fileresult(L
, (res
== 0), NULL
);
230 static LStream
*newfile (lua_State
*L
) {
231 LStream
*p
= newprefile(L
);
233 p
->closef
= &io_fclose
;
238 static void opencheck (lua_State
*L
, const char *fname
, const char *mode
) {
239 LStream
*p
= newfile(L
);
240 p
->f
= fopen(fname
, mode
);
242 luaL_error(L
, "cannot open file '%s' (%s)", fname
, strerror(errno
));
246 static int io_open (lua_State
*L
) {
247 const char *filename
= luaL_checkstring(L
, 1);
248 const char *mode
= luaL_optstring(L
, 2, "r");
249 LStream
*p
= newfile(L
);
250 const char *md
= mode
; /* to traverse/check mode */
251 luaL_argcheck(L
, l_checkmode(md
), 2, "invalid mode");
252 p
->f
= fopen(filename
, mode
);
253 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
258 ** function to close 'popen' files
260 static int io_pclose (lua_State
*L
) {
261 LStream
*p
= tolstream(L
);
262 return luaL_execresult(L
, l_pclose(L
, p
->f
));
266 static int io_popen (lua_State
*L
) {
267 const char *filename
= luaL_checkstring(L
, 1);
268 const char *mode
= luaL_optstring(L
, 2, "r");
269 LStream
*p
= newprefile(L
);
270 p
->f
= l_popen(L
, filename
, mode
);
271 p
->closef
= &io_pclose
;
272 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
276 static int io_tmpfile (lua_State
*L
) {
277 LStream
*p
= newfile(L
);
279 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, NULL
) : 1;
283 static FILE *getiofile (lua_State
*L
, const char *findex
) {
285 lua_getfield(L
, LUA_REGISTRYINDEX
, findex
);
286 p
= (LStream
*)lua_touserdata(L
, -1);
288 luaL_error(L
, "standard %s file is closed", findex
+ IOPREF_LEN
);
293 static int g_iofile (lua_State
*L
, const char *f
, const char *mode
) {
294 if (!lua_isnoneornil(L
, 1)) {
295 const char *filename
= lua_tostring(L
, 1);
297 opencheck(L
, filename
, mode
);
299 tofile(L
); /* check that it's a valid file handle */
302 lua_setfield(L
, LUA_REGISTRYINDEX
, f
);
304 /* return current value */
305 lua_getfield(L
, LUA_REGISTRYINDEX
, f
);
310 static int io_input (lua_State
*L
) {
311 return g_iofile(L
, IO_INPUT
, "r");
315 static int io_output (lua_State
*L
) {
316 return g_iofile(L
, IO_OUTPUT
, "w");
320 static int io_readline (lua_State
*L
);
323 static void aux_lines (lua_State
*L
, int toclose
) {
324 int n
= lua_gettop(L
) - 1; /* number of arguments to read */
325 lua_pushinteger(L
, n
); /* number of arguments to read */
326 lua_pushboolean(L
, toclose
); /* close/not close file when finished */
327 lua_rotate(L
, 2, 2); /* move 'n' and 'toclose' to their positions */
328 lua_pushcclosure(L
, io_readline
, 3 + n
);
332 static int f_lines (lua_State
*L
) {
333 tofile(L
); /* check that it's a valid file handle */
339 static int io_lines (lua_State
*L
) {
341 if (lua_isnone(L
, 1)) lua_pushnil(L
); /* at least one argument */
342 if (lua_isnil(L
, 1)) { /* no file name? */
343 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_INPUT
); /* get default input */
344 lua_replace(L
, 1); /* put it at index 1 */
345 tofile(L
); /* check that it's a valid file handle */
346 toclose
= 0; /* do not close it after iteration */
348 else { /* open a new file */
349 const char *filename
= luaL_checkstring(L
, 1);
350 opencheck(L
, filename
, "r");
351 lua_replace(L
, 1); /* put file at index 1 */
352 toclose
= 1; /* close it after iteration */
354 aux_lines(L
, toclose
);
360 ** {======================================================
362 ** =======================================================
366 /* maximum length of a numeral */
369 /* auxiliary structure used by 'read_number' */
371 FILE *f
; /* file being read */
372 int c
; /* current character (look ahead) */
373 int n
; /* number of elements in buffer 'buff' */
374 char buff
[MAXRN
+ 1]; /* +1 for ending '\0' */
379 ** Add current char to buffer (if not out of space) and read next one
381 static int nextc (RN
*rn
) {
382 if (rn
->n
>= MAXRN
) { /* buffer overflow? */
383 rn
->buff
[0] = '\0'; /* invalidate result */
387 rn
->buff
[rn
->n
++] = rn
->c
; /* save current char */
388 rn
->c
= l_getc(rn
->f
); /* read next one */
395 ** Accept current char if it is in 'set' (of size 1 or 2)
397 static int test2 (RN
*rn
, const char *set
) {
398 if (rn
->c
== set
[0] || (rn
->c
== set
[1] && rn
->c
!= '\0'))
405 ** Read a sequence of (hex)digits
407 static int readdigits (RN
*rn
, int hex
) {
409 while ((hex
? isxdigit(rn
->c
) : isdigit(rn
->c
)) && nextc(rn
))
416 ** Read a number: first reads a valid prefix of a numeral into a buffer.
417 ** Then it calls 'lua_stringtonumber' to check whether the format is
418 ** correct and to convert it to a Lua number
420 static int read_number (lua_State
*L
, FILE *f
) {
426 decp
[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
429 do { rn
.c
= l_getc(rn
.f
); } while (isspace(rn
.c
)); /* skip spaces */
430 test2(&rn
, "-+"); /* optional signal */
431 if (test2(&rn
, "0")) {
432 if (test2(&rn
, "xX")) hex
= 1; /* numeral is hexadecimal */
433 else count
= 1; /* count initial '0' as a valid digit */
435 count
+= readdigits(&rn
, hex
); /* integral part */
436 if (test2(&rn
, decp
)) /* decimal point? */
437 count
+= readdigits(&rn
, hex
); /* fractional part */
438 if (count
> 0 && test2(&rn
, (hex
? "pP" : "eE"))) { /* exponent mark? */
439 test2(&rn
, "-+"); /* exponent signal */
440 readdigits(&rn
, 0); /* exponent digits */
442 ungetc(rn
.c
, rn
.f
); /* unread look-ahead char */
444 rn
.buff
[rn
.n
] = '\0'; /* finish string */
445 if (lua_stringtonumber(L
, rn
.buff
)) /* is this a valid number? */
447 else { /* invalid format */
448 lua_pushnil(L
); /* "result" to be removed */
449 return 0; /* read fails */
454 static int test_eof (lua_State
*L
, FILE *f
) {
456 ungetc(c
, f
); /* no-op when c == EOF */
457 lua_pushliteral(L
, "");
462 static int read_line (lua_State
*L
, FILE *f
, int chop
) {
465 luaL_buffinit(L
, &b
);
466 while (c
!= EOF
&& c
!= '\n') { /* repeat until end of line */
467 char *buff
= luaL_prepbuffer(&b
); /* pre-allocate buffer */
469 l_lockfile(f
); /* no memory errors can happen inside the lock */
470 while (i
< LUAL_BUFFERSIZE
&& (c
= l_getc(f
)) != EOF
&& c
!= '\n')
475 if (!chop
&& c
== '\n') /* want a newline and have one? */
476 luaL_addchar(&b
, c
); /* add ending newline to result */
477 luaL_pushresult(&b
); /* close buffer */
478 /* return ok if read something (either a newline or something else) */
479 return (c
== '\n' || lua_rawlen(L
, -1) > 0);
483 static void read_all (lua_State
*L
, FILE *f
) {
486 luaL_buffinit(L
, &b
);
487 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
488 char *p
= luaL_prepbuffsize(&b
, LUAL_BUFFERSIZE
);
489 nr
= fread(p
, sizeof(char), LUAL_BUFFERSIZE
, f
);
490 luaL_addsize(&b
, nr
);
491 } while (nr
== LUAL_BUFFERSIZE
);
492 luaL_pushresult(&b
); /* close buffer */
496 static int read_chars (lua_State
*L
, FILE *f
, size_t n
) {
497 size_t nr
; /* number of chars actually read */
500 luaL_buffinit(L
, &b
);
501 p
= luaL_prepbuffsize(&b
, n
); /* prepare buffer to read whole block */
502 nr
= fread(p
, sizeof(char), n
, f
); /* try to read 'n' chars */
503 luaL_addsize(&b
, nr
);
504 luaL_pushresult(&b
); /* close buffer */
505 return (nr
> 0); /* true iff read something */
509 static int g_read (lua_State
*L
, FILE *f
, int first
) {
510 int nargs
= lua_gettop(L
) - 1;
514 if (nargs
== 0) { /* no arguments? */
515 success
= read_line(L
, f
, 1);
516 n
= first
+1; /* to return 1 result */
518 else { /* ensure stack space for all results and for auxlib's buffer */
519 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
521 for (n
= first
; nargs
-- && success
; n
++) {
522 if (lua_type(L
, n
) == LUA_TNUMBER
) {
523 size_t l
= (size_t)luaL_checkinteger(L
, n
);
524 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
527 const char *p
= luaL_checkstring(L
, n
);
528 if (*p
== '*') p
++; /* skip optional '*' (for compatibility) */
530 case 'n': /* number */
531 success
= read_number(L
, f
);
534 success
= read_line(L
, f
, 1);
536 case 'L': /* line with end-of-line */
537 success
= read_line(L
, f
, 0);
540 read_all(L
, f
); /* read entire file */
541 success
= 1; /* always success */
544 return luaL_argerror(L
, n
, "invalid format");
550 return luaL_fileresult(L
, 0, NULL
);
552 lua_pop(L
, 1); /* remove last result */
553 lua_pushnil(L
); /* push nil instead */
559 static int io_read (lua_State
*L
) {
560 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
564 static int f_read (lua_State
*L
) {
565 return g_read(L
, tofile(L
), 2);
569 static int io_readline (lua_State
*L
) {
570 LStream
*p
= (LStream
*)lua_touserdata(L
, lua_upvalueindex(1));
572 int n
= (int)lua_tointeger(L
, lua_upvalueindex(2));
573 if (isclosed(p
)) /* file is already closed? */
574 return luaL_error(L
, "file is already closed");
576 luaL_checkstack(L
, n
, "too many arguments");
577 for (i
= 1; i
<= n
; i
++) /* push arguments to 'g_read' */
578 lua_pushvalue(L
, lua_upvalueindex(3 + i
));
579 n
= g_read(L
, p
->f
, 2); /* 'n' is number of results */
580 lua_assert(n
> 0); /* should return at least a nil */
581 if (lua_toboolean(L
, -n
)) /* read at least one value? */
582 return n
; /* return them */
583 else { /* first result is nil: EOF or error */
584 if (n
> 1) { /* is there error information? */
585 /* 2nd result is error message */
586 return luaL_error(L
, "%s", lua_tostring(L
, -n
+ 1));
588 if (lua_toboolean(L
, lua_upvalueindex(3))) { /* generator created file? */
590 lua_pushvalue(L
, lua_upvalueindex(1));
591 aux_close(L
); /* close it */
597 /* }====================================================== */
600 static int g_write (lua_State
*L
, FILE *f
, int arg
) {
601 int nargs
= lua_gettop(L
) - arg
;
603 for (; nargs
--; arg
++) {
604 if (lua_type(L
, arg
) == LUA_TNUMBER
) {
605 /* optimization: could be done exactly as for strings */
606 int len
= lua_isinteger(L
, arg
)
607 ? fprintf(f
, LUA_INTEGER_FMT
, lua_tointeger(L
, arg
))
608 : fprintf(f
, LUA_NUMBER_FMT
, lua_tonumber(L
, arg
));
609 status
= status
&& (len
> 0);
613 const char *s
= luaL_checklstring(L
, arg
, &l
);
614 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
617 if (status
) return 1; /* file handle already on stack top */
618 else return luaL_fileresult(L
, status
, NULL
);
622 static int io_write (lua_State
*L
) {
623 return g_write(L
, getiofile(L
, IO_OUTPUT
), 1);
627 static int f_write (lua_State
*L
) {
629 lua_pushvalue(L
, 1); /* push file at the stack top (to be returned) */
630 return g_write(L
, f
, 2);
634 static int f_seek (lua_State
*L
) {
635 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
636 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
638 int op
= luaL_checkoption(L
, 2, "cur", modenames
);
639 lua_Integer p3
= luaL_optinteger(L
, 3, 0);
640 l_seeknum offset
= (l_seeknum
)p3
;
641 luaL_argcheck(L
, (lua_Integer
)offset
== p3
, 3,
642 "not an integer in proper range");
643 op
= l_fseek(f
, offset
, mode
[op
]);
645 return luaL_fileresult(L
, 0, NULL
); /* error */
647 lua_pushinteger(L
, (lua_Integer
)l_ftell(f
));
653 static int f_setvbuf (lua_State
*L
) {
654 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
655 static const char *const modenames
[] = {"no", "full", "line", NULL
};
657 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
658 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
659 int res
= setvbuf(f
, NULL
, mode
[op
], (size_t)sz
);
660 return luaL_fileresult(L
, res
== 0, NULL
);
665 static int io_flush (lua_State
*L
) {
666 return luaL_fileresult(L
, fflush(getiofile(L
, IO_OUTPUT
)) == 0, NULL
);
670 static int f_flush (lua_State
*L
) {
671 return luaL_fileresult(L
, fflush(tofile(L
)) == 0, NULL
);
676 ** functions for 'io' library
678 static const luaL_Reg iolib
[] = {
684 {"output", io_output
},
687 {"tmpfile", io_tmpfile
},
695 ** methods for file handles
697 static const luaL_Reg flib
[] = {
703 {"setvbuf", f_setvbuf
},
706 {"__tostring", f_tostring
},
711 static void createmeta (lua_State
*L
) {
712 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* create metatable for file handles */
713 lua_pushvalue(L
, -1); /* push metatable */
714 lua_setfield(L
, -2, "__index"); /* metatable.__index = metatable */
715 luaL_setfuncs(L
, flib
, 0); /* add file methods to new metatable */
716 lua_pop(L
, 1); /* pop new metatable */
721 ** function to (not) close the standard files stdin, stdout, and stderr
723 static int io_noclose (lua_State
*L
) {
724 LStream
*p
= tolstream(L
);
725 p
->closef
= &io_noclose
; /* keep file opened */
727 lua_pushliteral(L
, "cannot close standard file");
732 static void createstdfile (lua_State
*L
, FILE *f
, const char *k
,
734 LStream
*p
= newprefile(L
);
736 p
->closef
= &io_noclose
;
738 lua_pushvalue(L
, -1);
739 lua_setfield(L
, LUA_REGISTRYINDEX
, k
); /* add file to registry */
741 lua_setfield(L
, -2, fname
); /* add file to module */
745 LUAMOD_API
int luaopen_io (lua_State
*L
) {
746 luaL_newlib(L
, iolib
); /* new module */
748 /* create (and set) default files */
749 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
750 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
751 createstdfile(L
, stderr
, NULL
, "stderr");