]>
git.proxmox.com Git - ceph.git/blob - ceph/src/civetweb/src/third_party/lua-5.3.1/src/liolib.c
2 ** $Id: liolib.c,v 2.144 2015/04/03 18:41:57 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
26 #if !defined(l_checkmode)
29 ** Check whether 'mode' matches '[rwa]%+?b?'.
30 ** Change this macro to accept other modes for 'fopen' besides
33 #define l_checkmode(mode) \
34 (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
35 (*mode != '+' || ++mode) && /* skip if char is '+' */ \
36 (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
42 ** {======================================================
43 ** l_popen spawns a new process connected to the current
44 ** one through the file streams.
45 ** =======================================================
48 #if !defined(l_popen) /* { */
50 #if defined(LUA_USE_POSIX) /* { */
52 #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
53 #define l_pclose(L,file) (pclose(file))
55 #elif defined(LUA_USE_WINDOWS) /* }{ */
57 #define l_popen(L,c,m) (_popen(c,m))
58 #define l_pclose(L,file) (_pclose(file))
62 /* ISO C definitions */
63 #define l_popen(L,c,m) \
64 ((void)((void)c, m), \
65 luaL_error(L, "'popen' not supported"), \
67 #define l_pclose(L,file) ((void)L, (void)file, -1)
73 /* }====================================================== */
76 #if !defined(l_getc) /* { */
78 #if defined(LUA_USE_POSIX)
79 #define l_getc(f) getc_unlocked(f)
80 #define l_lockfile(f) flockfile(f)
81 #define l_unlockfile(f) funlockfile(f)
83 #define l_getc(f) getc(f)
84 #define l_lockfile(f) ((void)0)
85 #define l_unlockfile(f) ((void)0)
92 ** {======================================================
93 ** l_fseek: configuration for longer offsets
94 ** =======================================================
97 #if !defined(l_fseek) /* { */
99 #if defined(LUA_USE_POSIX) /* { */
101 #include <sys/types.h>
103 #define l_fseek(f,o,w) fseeko(f,o,w)
104 #define l_ftell(f) ftello(f)
105 #define l_seeknum off_t
107 #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
108 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
110 /* Windows (but not DDK) and Visual C++ 2005 or higher */
111 #define l_fseek(f,o,w) _fseeki64(f,o,w)
112 #define l_ftell(f) _ftelli64(f)
113 #define l_seeknum __int64
117 /* ISO C definitions */
118 #define l_fseek(f,o,w) fseek(f,o,w)
119 #define l_ftell(f) ftell(f)
120 #define l_seeknum long
126 /* }====================================================== */
129 #define IO_PREFIX "_IO_"
130 #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
131 #define IO_INPUT (IO_PREFIX "input")
132 #define IO_OUTPUT (IO_PREFIX "output")
135 typedef luaL_Stream LStream
;
138 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
140 #define isclosed(p) ((p)->closef == NULL)
143 static int io_type (lua_State
*L
) {
146 p
= (LStream
*)luaL_testudata(L
, 1, LUA_FILEHANDLE
);
148 lua_pushnil(L
); /* not a file */
149 else if (isclosed(p
))
150 lua_pushliteral(L
, "closed file");
152 lua_pushliteral(L
, "file");
157 static int f_tostring (lua_State
*L
) {
158 LStream
*p
= tolstream(L
);
160 lua_pushliteral(L
, "file (closed)");
162 lua_pushfstring(L
, "file (%p)", p
->f
);
167 static FILE *tofile (lua_State
*L
) {
168 LStream
*p
= tolstream(L
);
170 luaL_error(L
, "attempt to use a closed file");
177 ** When creating file handles, always creates a 'closed' file handle
178 ** before opening the actual file; so, if there is a memory error, the
179 ** file is not left opened.
181 static LStream
*newprefile (lua_State
*L
) {
182 LStream
*p
= (LStream
*)lua_newuserdata(L
, sizeof(LStream
));
183 p
->closef
= NULL
; /* mark file handle as 'closed' */
184 luaL_setmetatable(L
, LUA_FILEHANDLE
);
190 ** Calls the 'close' function from a file handle. The 'volatile' avoids
191 ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
194 static int aux_close (lua_State
*L
) {
195 LStream
*p
= tolstream(L
);
196 volatile lua_CFunction cf
= p
->closef
;
197 p
->closef
= NULL
; /* mark stream as closed */
198 return (*cf
)(L
); /* close it */
202 static int io_close (lua_State
*L
) {
203 if (lua_isnone(L
, 1)) /* no argument? */
204 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_OUTPUT
); /* use standard output */
205 tofile(L
); /* make sure argument is an open stream */
210 static int f_gc (lua_State
*L
) {
211 LStream
*p
= tolstream(L
);
212 if (!isclosed(p
) && p
->f
!= NULL
)
213 aux_close(L
); /* ignore closed and incompletely open files */
219 ** function to close regular files
221 static int io_fclose (lua_State
*L
) {
222 LStream
*p
= tolstream(L
);
223 int res
= fclose(p
->f
);
224 return luaL_fileresult(L
, (res
== 0), NULL
);
228 static LStream
*newfile (lua_State
*L
) {
229 LStream
*p
= newprefile(L
);
231 p
->closef
= &io_fclose
;
236 static void opencheck (lua_State
*L
, const char *fname
, const char *mode
) {
237 LStream
*p
= newfile(L
);
238 p
->f
= fopen(fname
, mode
);
240 luaL_error(L
, "cannot open file '%s' (%s)", fname
, strerror(errno
));
244 static int io_open (lua_State
*L
) {
245 const char *filename
= luaL_checkstring(L
, 1);
246 const char *mode
= luaL_optstring(L
, 2, "r");
247 LStream
*p
= newfile(L
);
248 const char *md
= mode
; /* to traverse/check mode */
249 luaL_argcheck(L
, l_checkmode(md
), 2, "invalid mode");
250 p
->f
= fopen(filename
, mode
);
251 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
256 ** function to close 'popen' files
258 static int io_pclose (lua_State
*L
) {
259 LStream
*p
= tolstream(L
);
260 return luaL_execresult(L
, l_pclose(L
, p
->f
));
264 static int io_popen (lua_State
*L
) {
265 const char *filename
= luaL_checkstring(L
, 1);
266 const char *mode
= luaL_optstring(L
, 2, "r");
267 LStream
*p
= newprefile(L
);
268 p
->f
= l_popen(L
, filename
, mode
);
269 p
->closef
= &io_pclose
;
270 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, filename
) : 1;
274 static int io_tmpfile (lua_State
*L
) {
275 LStream
*p
= newfile(L
);
277 return (p
->f
== NULL
) ? luaL_fileresult(L
, 0, NULL
) : 1;
281 static FILE *getiofile (lua_State
*L
, const char *findex
) {
283 lua_getfield(L
, LUA_REGISTRYINDEX
, findex
);
284 p
= (LStream
*)lua_touserdata(L
, -1);
286 luaL_error(L
, "standard %s file is closed", findex
+ IOPREF_LEN
);
291 static int g_iofile (lua_State
*L
, const char *f
, const char *mode
) {
292 if (!lua_isnoneornil(L
, 1)) {
293 const char *filename
= lua_tostring(L
, 1);
295 opencheck(L
, filename
, mode
);
297 tofile(L
); /* check that it's a valid file handle */
300 lua_setfield(L
, LUA_REGISTRYINDEX
, f
);
302 /* return current value */
303 lua_getfield(L
, LUA_REGISTRYINDEX
, f
);
308 static int io_input (lua_State
*L
) {
309 return g_iofile(L
, IO_INPUT
, "r");
313 static int io_output (lua_State
*L
) {
314 return g_iofile(L
, IO_OUTPUT
, "w");
318 static int io_readline (lua_State
*L
);
321 static void aux_lines (lua_State
*L
, int toclose
) {
322 int n
= lua_gettop(L
) - 1; /* number of arguments to read */
323 lua_pushinteger(L
, n
); /* number of arguments to read */
324 lua_pushboolean(L
, toclose
); /* close/not close file when finished */
325 lua_rotate(L
, 2, 2); /* move 'n' and 'toclose' to their positions */
326 lua_pushcclosure(L
, io_readline
, 3 + n
);
330 static int f_lines (lua_State
*L
) {
331 tofile(L
); /* check that it's a valid file handle */
337 static int io_lines (lua_State
*L
) {
339 if (lua_isnone(L
, 1)) lua_pushnil(L
); /* at least one argument */
340 if (lua_isnil(L
, 1)) { /* no file name? */
341 lua_getfield(L
, LUA_REGISTRYINDEX
, IO_INPUT
); /* get default input */
342 lua_replace(L
, 1); /* put it at index 1 */
343 tofile(L
); /* check that it's a valid file handle */
344 toclose
= 0; /* do not close it after iteration */
346 else { /* open a new file */
347 const char *filename
= luaL_checkstring(L
, 1);
348 opencheck(L
, filename
, "r");
349 lua_replace(L
, 1); /* put file at index 1 */
350 toclose
= 1; /* close it after iteration */
352 aux_lines(L
, toclose
);
358 ** {======================================================
360 ** =======================================================
364 /* maximum length of a numeral */
367 /* auxiliary structure used by 'read_number' */
369 FILE *f
; /* file being read */
370 int c
; /* current character (look ahead) */
371 int n
; /* number of elements in buffer 'buff' */
372 char buff
[MAXRN
+ 1]; /* +1 for ending '\0' */
377 ** Add current char to buffer (if not out of space) and read next one
379 static int nextc (RN
*rn
) {
380 if (rn
->n
>= MAXRN
) { /* buffer overflow? */
381 rn
->buff
[0] = '\0'; /* invalidate result */
385 rn
->buff
[rn
->n
++] = rn
->c
; /* save current char */
386 rn
->c
= l_getc(rn
->f
); /* read next one */
393 ** Accept current char if it is in 'set' (of size 1 or 2)
395 static int test2 (RN
*rn
, const char *set
) {
396 if (rn
->c
== set
[0] || (rn
->c
== set
[1] && rn
->c
!= '\0'))
403 ** Read a sequence of (hex)digits
405 static int readdigits (RN
*rn
, int hex
) {
407 while ((hex
? isxdigit(rn
->c
) : isdigit(rn
->c
)) && nextc(rn
))
414 ** Read a number: first reads a valid prefix of a numeral into a buffer.
415 ** Then it calls 'lua_stringtonumber' to check whether the format is
416 ** correct and to convert it to a Lua number
418 static int read_number (lua_State
*L
, FILE *f
) {
424 decp
[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
427 do { rn
.c
= l_getc(rn
.f
); } while (isspace(rn
.c
)); /* skip spaces */
428 test2(&rn
, "-+"); /* optional signal */
429 if (test2(&rn
, "0")) {
430 if (test2(&rn
, "xX")) hex
= 1; /* numeral is hexadecimal */
431 else count
= 1; /* count initial '0' as a valid digit */
433 count
+= readdigits(&rn
, hex
); /* integral part */
434 if (test2(&rn
, decp
)) /* decimal point? */
435 count
+= readdigits(&rn
, hex
); /* fractional part */
436 if (count
> 0 && test2(&rn
, (hex
? "pP" : "eE"))) { /* exponent mark? */
437 test2(&rn
, "-+"); /* exponent signal */
438 readdigits(&rn
, 0); /* exponent digits */
440 ungetc(rn
.c
, rn
.f
); /* unread look-ahead char */
442 rn
.buff
[rn
.n
] = '\0'; /* finish string */
443 if (lua_stringtonumber(L
, rn
.buff
)) /* is this a valid number? */
445 else { /* invalid format */
446 lua_pushnil(L
); /* "result" to be removed */
447 return 0; /* read fails */
452 static int test_eof (lua_State
*L
, FILE *f
) {
454 ungetc(c
, f
); /* no-op when c == EOF */
455 lua_pushliteral(L
, "");
460 static int read_line (lua_State
*L
, FILE *f
, int chop
) {
463 luaL_buffinit(L
, &b
);
464 while (c
!= EOF
&& c
!= '\n') { /* repeat until end of line */
465 char *buff
= luaL_prepbuffer(&b
); /* pre-allocate buffer */
467 l_lockfile(f
); /* no memory errors can happen inside the lock */
468 while (i
< LUAL_BUFFERSIZE
&& (c
= l_getc(f
)) != EOF
&& c
!= '\n')
473 if (!chop
&& c
== '\n') /* want a newline and have one? */
474 luaL_addchar(&b
, c
); /* add ending newline to result */
475 luaL_pushresult(&b
); /* close buffer */
476 /* return ok if read something (either a newline or something else) */
477 return (c
== '\n' || lua_rawlen(L
, -1) > 0);
481 static void read_all (lua_State
*L
, FILE *f
) {
484 luaL_buffinit(L
, &b
);
485 do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
486 char *p
= luaL_prepbuffsize(&b
, LUAL_BUFFERSIZE
);
487 nr
= fread(p
, sizeof(char), LUAL_BUFFERSIZE
, f
);
488 luaL_addsize(&b
, nr
);
489 } while (nr
== LUAL_BUFFERSIZE
);
490 luaL_pushresult(&b
); /* close buffer */
494 static int read_chars (lua_State
*L
, FILE *f
, size_t n
) {
495 size_t nr
; /* number of chars actually read */
498 luaL_buffinit(L
, &b
);
499 p
= luaL_prepbuffsize(&b
, n
); /* prepare buffer to read whole block */
500 nr
= fread(p
, sizeof(char), n
, f
); /* try to read 'n' chars */
501 luaL_addsize(&b
, nr
);
502 luaL_pushresult(&b
); /* close buffer */
503 return (nr
> 0); /* true iff read something */
507 static int g_read (lua_State
*L
, FILE *f
, int first
) {
508 int nargs
= lua_gettop(L
) - 1;
512 if (nargs
== 0) { /* no arguments? */
513 success
= read_line(L
, f
, 1);
514 n
= first
+1; /* to return 1 result */
516 else { /* ensure stack space for all results and for auxlib's buffer */
517 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
519 for (n
= first
; nargs
-- && success
; n
++) {
520 if (lua_type(L
, n
) == LUA_TNUMBER
) {
521 size_t l
= (size_t)luaL_checkinteger(L
, n
);
522 success
= (l
== 0) ? test_eof(L
, f
) : read_chars(L
, f
, l
);
525 const char *p
= luaL_checkstring(L
, n
);
526 if (*p
== '*') p
++; /* skip optional '*' (for compatibility) */
528 case 'n': /* number */
529 success
= read_number(L
, f
);
532 success
= read_line(L
, f
, 1);
534 case 'L': /* line with end-of-line */
535 success
= read_line(L
, f
, 0);
538 read_all(L
, f
); /* read entire file */
539 success
= 1; /* always success */
542 return luaL_argerror(L
, n
, "invalid format");
548 return luaL_fileresult(L
, 0, NULL
);
550 lua_pop(L
, 1); /* remove last result */
551 lua_pushnil(L
); /* push nil instead */
557 static int io_read (lua_State
*L
) {
558 return g_read(L
, getiofile(L
, IO_INPUT
), 1);
562 static int f_read (lua_State
*L
) {
563 return g_read(L
, tofile(L
), 2);
567 static int io_readline (lua_State
*L
) {
568 LStream
*p
= (LStream
*)lua_touserdata(L
, lua_upvalueindex(1));
570 int n
= (int)lua_tointeger(L
, lua_upvalueindex(2));
571 if (isclosed(p
)) /* file is already closed? */
572 return luaL_error(L
, "file is already closed");
574 luaL_checkstack(L
, n
, "too many arguments");
575 for (i
= 1; i
<= n
; i
++) /* push arguments to 'g_read' */
576 lua_pushvalue(L
, lua_upvalueindex(3 + i
));
577 n
= g_read(L
, p
->f
, 2); /* 'n' is number of results */
578 lua_assert(n
> 0); /* should return at least a nil */
579 if (lua_toboolean(L
, -n
)) /* read at least one value? */
580 return n
; /* return them */
581 else { /* first result is nil: EOF or error */
582 if (n
> 1) { /* is there error information? */
583 /* 2nd result is error message */
584 return luaL_error(L
, "%s", lua_tostring(L
, -n
+ 1));
586 if (lua_toboolean(L
, lua_upvalueindex(3))) { /* generator created file? */
588 lua_pushvalue(L
, lua_upvalueindex(1));
589 aux_close(L
); /* close it */
595 /* }====================================================== */
598 static int g_write (lua_State
*L
, FILE *f
, int arg
) {
599 int nargs
= lua_gettop(L
) - arg
;
601 for (; nargs
--; arg
++) {
602 if (lua_type(L
, arg
) == LUA_TNUMBER
) {
603 /* optimization: could be done exactly as for strings */
604 int len
= lua_isinteger(L
, arg
)
605 ? fprintf(f
, LUA_INTEGER_FMT
, lua_tointeger(L
, arg
))
606 : fprintf(f
, LUA_NUMBER_FMT
, lua_tonumber(L
, arg
));
607 status
= status
&& (len
> 0);
611 const char *s
= luaL_checklstring(L
, arg
, &l
);
612 status
= status
&& (fwrite(s
, sizeof(char), l
, f
) == l
);
615 if (status
) return 1; /* file handle already on stack top */
616 else return luaL_fileresult(L
, status
, NULL
);
620 static int io_write (lua_State
*L
) {
621 return g_write(L
, getiofile(L
, IO_OUTPUT
), 1);
625 static int f_write (lua_State
*L
) {
627 lua_pushvalue(L
, 1); /* push file at the stack top (to be returned) */
628 return g_write(L
, f
, 2);
632 static int f_seek (lua_State
*L
) {
633 static const int mode
[] = {SEEK_SET
, SEEK_CUR
, SEEK_END
};
634 static const char *const modenames
[] = {"set", "cur", "end", NULL
};
636 int op
= luaL_checkoption(L
, 2, "cur", modenames
);
637 lua_Integer p3
= luaL_optinteger(L
, 3, 0);
638 l_seeknum offset
= (l_seeknum
)p3
;
639 luaL_argcheck(L
, (lua_Integer
)offset
== p3
, 3,
640 "not an integer in proper range");
641 op
= l_fseek(f
, offset
, mode
[op
]);
643 return luaL_fileresult(L
, 0, NULL
); /* error */
645 lua_pushinteger(L
, (lua_Integer
)l_ftell(f
));
651 static int f_setvbuf (lua_State
*L
) {
652 static const int mode
[] = {_IONBF
, _IOFBF
, _IOLBF
};
653 static const char *const modenames
[] = {"no", "full", "line", NULL
};
655 int op
= luaL_checkoption(L
, 2, NULL
, modenames
);
656 lua_Integer sz
= luaL_optinteger(L
, 3, LUAL_BUFFERSIZE
);
657 int res
= setvbuf(f
, NULL
, mode
[op
], (size_t)sz
);
658 return luaL_fileresult(L
, res
== 0, NULL
);
663 static int io_flush (lua_State
*L
) {
664 return luaL_fileresult(L
, fflush(getiofile(L
, IO_OUTPUT
)) == 0, NULL
);
668 static int f_flush (lua_State
*L
) {
669 return luaL_fileresult(L
, fflush(tofile(L
)) == 0, NULL
);
674 ** functions for 'io' library
676 static const luaL_Reg iolib
[] = {
682 {"output", io_output
},
685 {"tmpfile", io_tmpfile
},
693 ** methods for file handles
695 static const luaL_Reg flib
[] = {
701 {"setvbuf", f_setvbuf
},
704 {"__tostring", f_tostring
},
709 static void createmeta (lua_State
*L
) {
710 luaL_newmetatable(L
, LUA_FILEHANDLE
); /* create metatable for file handles */
711 lua_pushvalue(L
, -1); /* push metatable */
712 lua_setfield(L
, -2, "__index"); /* metatable.__index = metatable */
713 luaL_setfuncs(L
, flib
, 0); /* add file methods to new metatable */
714 lua_pop(L
, 1); /* pop new metatable */
719 ** function to (not) close the standard files stdin, stdout, and stderr
721 static int io_noclose (lua_State
*L
) {
722 LStream
*p
= tolstream(L
);
723 p
->closef
= &io_noclose
; /* keep file opened */
725 lua_pushliteral(L
, "cannot close standard file");
730 static void createstdfile (lua_State
*L
, FILE *f
, const char *k
,
732 LStream
*p
= newprefile(L
);
734 p
->closef
= &io_noclose
;
736 lua_pushvalue(L
, -1);
737 lua_setfield(L
, LUA_REGISTRYINDEX
, k
); /* add file to registry */
739 lua_setfield(L
, -2, fname
); /* add file to module */
743 LUAMOD_API
int luaopen_io (lua_State
*L
) {
744 luaL_newlib(L
, iolib
); /* new module */
746 /* create (and set) default files */
747 createstdfile(L
, stdin
, IO_INPUT
, "stdin");
748 createstdfile(L
, stdout
, IO_OUTPUT
, "stdout");
749 createstdfile(L
, stderr
, NULL
, "stderr");