beta-0.89.2
[luatex.git] / source / libs / luajit / LuaJIT-src / src / lib_io.c
blob2aa834746e1f2f4771db0d0a528b426680fd35af
1 /*
2 ** I/O library.
3 ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
4 **
5 ** Major portions taken verbatim or adapted from the Lua interpreter.
6 ** Copyright (C) 1994-2011 Lua.org, PUC-Rio. See Copyright Notice in lua.h
7 */
9 #include <errno.h>
10 #include <stdio.h>
12 #define lib_io_c
13 #define LUA_LIB
15 #include "lua.h"
16 #include "lauxlib.h"
17 #include "lualib.h"
19 #include "lj_obj.h"
20 #include "lj_gc.h"
21 #include "lj_err.h"
22 #include "lj_buf.h"
23 #include "lj_str.h"
24 #include "lj_state.h"
25 #include "lj_strfmt.h"
26 #include "lj_ff.h"
27 #include "lj_lib.h"
29 /* Userdata payload for I/O file. */
30 typedef struct IOFileUD {
31 FILE *fp; /* File handle. */
32 uint32_t type; /* File type. */
33 } IOFileUD;
35 #define IOFILE_TYPE_FILE 0 /* Regular file. */
36 #define IOFILE_TYPE_PIPE 1 /* Pipe. */
37 #define IOFILE_TYPE_STDF 2 /* Standard file handle. */
38 #define IOFILE_TYPE_MASK 3
40 #define IOFILE_FLAG_CLOSE 4 /* Close after io.lines() iterator. */
42 #define IOSTDF_UD(L, id) (&gcref(G(L)->gcroot[(id)])->ud)
43 #define IOSTDF_IOF(L, id) ((IOFileUD *)uddata(IOSTDF_UD(L, (id))))
45 /* -- Open/close helpers -------------------------------------------------- */
47 static IOFileUD *io_tofilep(lua_State *L)
49 if (!(L->base < L->top && tvisudata(L->base) &&
50 udataV(L->base)->udtype == UDTYPE_IO_FILE))
51 lj_err_argtype(L, 1, "FILE*");
52 return (IOFileUD *)uddata(udataV(L->base));
55 static IOFileUD *io_tofile(lua_State *L)
57 IOFileUD *iof = io_tofilep(L);
58 if (iof->fp == NULL)
59 lj_err_caller(L, LJ_ERR_IOCLFL);
60 return iof;
63 static FILE *io_stdfile(lua_State *L, ptrdiff_t id)
65 IOFileUD *iof = IOSTDF_IOF(L, id);
66 if (iof->fp == NULL)
67 lj_err_caller(L, LJ_ERR_IOSTDCL);
68 return iof->fp;
71 static IOFileUD *io_file_new(lua_State *L)
73 IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
74 GCudata *ud = udataV(L->top-1);
75 ud->udtype = UDTYPE_IO_FILE;
76 /* NOBARRIER: The GCudata is new (marked white). */
77 setgcrefr(ud->metatable, curr_func(L)->c.env);
78 iof->fp = NULL;
79 iof->type = IOFILE_TYPE_FILE;
80 return iof;
83 static IOFileUD *io_file_open(lua_State *L, const char *mode)
85 const char *fname = strdata(lj_lib_checkstr(L, 1));
86 IOFileUD *iof = io_file_new(L);
87 iof->fp = fopen(fname, mode);
88 if (iof->fp == NULL)
89 luaL_argerror(L, 1, lj_strfmt_pushf(L, "%s: %s", fname, strerror(errno)));
90 return iof;
93 static int io_file_close(lua_State *L, IOFileUD *iof)
95 int ok;
96 if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_FILE) {
97 ok = (fclose(iof->fp) == 0);
98 } else if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_PIPE) {
99 int stat = -1;
100 #if LJ_TARGET_POSIX
101 stat = pclose(iof->fp);
102 #elif LJ_TARGET_WINDOWS && !LJ_TARGET_XBOXONE
103 stat = _pclose(iof->fp);
104 #else
105 lua_assert(0);
106 return 0;
107 #endif
108 #if LJ_52
109 iof->fp = NULL;
110 return luaL_execresult(L, stat);
111 #else
112 ok = (stat != -1);
113 #endif
114 } else {
115 lua_assert((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_STDF);
116 setnilV(L->top++);
117 lua_pushliteral(L, "cannot close standard file");
118 return 2;
120 iof->fp = NULL;
121 return luaL_fileresult(L, ok, NULL);
124 /* -- Read/write helpers -------------------------------------------------- */
126 static int io_file_readnum(lua_State *L, FILE *fp)
128 lua_Number d;
129 if (fscanf(fp, LUA_NUMBER_SCAN, &d) == 1) {
130 if (LJ_DUALNUM) {
131 int32_t i = lj_num2int(d);
132 if (d == (lua_Number)i && !tvismzero((cTValue *)&d)) {
133 setintV(L->top++, i);
134 return 1;
137 setnumV(L->top++, d);
138 return 1;
139 } else {
140 setnilV(L->top++);
141 return 0;
145 static int io_file_readline(lua_State *L, FILE *fp, MSize chop)
147 MSize m = LUAL_BUFFERSIZE, n = 0, ok = 0;
148 char *buf;
149 for (;;) {
150 buf = lj_buf_tmp(L, m);
151 if (fgets(buf+n, m-n, fp) == NULL) break;
152 n += (MSize)strlen(buf+n);
153 ok |= n;
154 if (n && buf[n-1] == '\n') { n -= chop; break; }
155 if (n >= m - 64) m += m;
157 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
158 lj_gc_check(L);
159 return (int)ok;
162 static void io_file_readall(lua_State *L, FILE *fp)
164 MSize m, n;
165 for (m = LUAL_BUFFERSIZE, n = 0; ; m += m) {
166 char *buf = lj_buf_tmp(L, m);
167 n += (MSize)fread(buf+n, 1, m-n, fp);
168 if (n != m) {
169 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
170 lj_gc_check(L);
171 return;
176 static int io_file_readlen(lua_State *L, FILE *fp, MSize m)
178 if (m) {
179 char *buf = lj_buf_tmp(L, m);
180 MSize n = (MSize)fread(buf, 1, m, fp);
181 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
182 lj_gc_check(L);
183 return (n > 0 || m == 0);
184 } else {
185 int c = getc(fp);
186 ungetc(c, fp);
187 setstrV(L, L->top++, &G(L)->strempty);
188 return (c != EOF);
192 static int io_file_read(lua_State *L, FILE *fp, int start)
194 int ok, n, nargs = (int)(L->top - L->base) - start;
195 clearerr(fp);
196 if (nargs == 0) {
197 ok = io_file_readline(L, fp, 1);
198 n = start+1; /* Return 1 result. */
199 } else {
200 /* The results plus the buffers go on top of the args. */
201 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
202 ok = 1;
203 for (n = start; nargs-- && ok; n++) {
204 if (tvisstr(L->base+n)) {
205 const char *p = strVdata(L->base+n);
206 if (p[0] != '*')
207 lj_err_arg(L, n+1, LJ_ERR_INVOPT);
208 if (p[1] == 'n')
209 ok = io_file_readnum(L, fp);
210 else if ((p[1] & ~0x20) == 'L')
211 ok = io_file_readline(L, fp, (p[1] == 'l'));
212 else if (p[1] == 'a')
213 io_file_readall(L, fp);
214 else
215 lj_err_arg(L, n+1, LJ_ERR_INVFMT);
216 } else if (tvisnumber(L->base+n)) {
217 ok = io_file_readlen(L, fp, (MSize)lj_lib_checkint(L, n+1));
218 } else {
219 lj_err_arg(L, n+1, LJ_ERR_INVOPT);
223 if (ferror(fp))
224 return luaL_fileresult(L, 0, NULL);
225 if (!ok)
226 setnilV(L->top-1); /* Replace last result with nil. */
227 return n - start;
230 static int io_file_write(lua_State *L, FILE *fp, int start)
232 cTValue *tv;
233 int status = 1;
234 for (tv = L->base+start; tv < L->top; tv++) {
235 char buf[STRFMT_MAXBUF_NUM];
236 MSize len;
237 const char *p = lj_strfmt_wstrnum(buf, tv, &len);
238 if (!p)
239 lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING);
240 status = status && (fwrite(p, 1, len, fp) == len);
242 if (LJ_52 && status) {
243 L->top = L->base+1;
244 if (start == 0)
245 setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_OUTPUT));
246 return 1;
248 return luaL_fileresult(L, status, NULL);
251 static int io_file_iter(lua_State *L)
253 GCfunc *fn = curr_func(L);
254 IOFileUD *iof = uddata(udataV(&fn->c.upvalue[0]));
255 int n = fn->c.nupvalues - 1;
256 if (iof->fp == NULL)
257 lj_err_caller(L, LJ_ERR_IOCLFL);
258 L->top = L->base;
259 if (n) { /* Copy upvalues with options to stack. */
260 if (n > LUAI_MAXCSTACK)
261 lj_err_caller(L, LJ_ERR_STKOV);
262 lj_state_checkstack(L, (MSize)n);
263 memcpy(L->top, &fn->c.upvalue[1], n*sizeof(TValue));
264 L->top += n;
266 n = io_file_read(L, iof->fp, 0);
267 if (ferror(iof->fp))
268 lj_err_callermsg(L, strVdata(L->top-2));
269 if (tvisnil(L->base) && (iof->type & IOFILE_FLAG_CLOSE)) {
270 io_file_close(L, iof); /* Return values are ignored. */
271 return 0;
273 return n;
276 static int io_file_lines(lua_State *L)
278 int n = (int)(L->top - L->base);
279 if (n > LJ_MAX_UPVAL)
280 lj_err_caller(L, LJ_ERR_UNPACK);
281 lua_pushcclosure(L, io_file_iter, n);
282 return 1;
285 /* -- I/O file methods ---------------------------------------------------- */
287 #define LJLIB_MODULE_io_method
289 LJLIB_CF(io_method_close)
291 IOFileUD *iof = L->base < L->top ? io_tofile(L) :
292 IOSTDF_IOF(L, GCROOT_IO_OUTPUT);
293 return io_file_close(L, iof);
296 LJLIB_CF(io_method_read)
298 return io_file_read(L, io_tofile(L)->fp, 1);
301 LJLIB_CF(io_method_write) LJLIB_REC(io_write 0)
303 return io_file_write(L, io_tofile(L)->fp, 1);
306 LJLIB_CF(io_method_flush) LJLIB_REC(io_flush 0)
308 return luaL_fileresult(L, fflush(io_tofile(L)->fp) == 0, NULL);
311 LJLIB_CF(io_method_seek)
313 FILE *fp = io_tofile(L)->fp;
314 int opt = lj_lib_checkopt(L, 2, 1, "\3set\3cur\3end");
315 int64_t ofs = 0;
316 cTValue *o;
317 int res;
318 if (opt == 0) opt = SEEK_SET;
319 else if (opt == 1) opt = SEEK_CUR;
320 else if (opt == 2) opt = SEEK_END;
321 o = L->base+2;
322 if (o < L->top) {
323 if (tvisint(o))
324 ofs = (int64_t)intV(o);
325 else if (tvisnum(o))
326 ofs = (int64_t)numV(o);
327 else if (!tvisnil(o))
328 lj_err_argt(L, 3, LUA_TNUMBER);
330 #if LJ_TARGET_POSIX
331 res = fseeko(fp, ofs, opt);
332 #elif _MSC_VER >= 1400
333 res = _fseeki64(fp, ofs, opt);
334 #elif defined(__MINGW32__)
335 res = fseeko64(fp, ofs, opt);
336 #else
337 res = fseek(fp, (long)ofs, opt);
338 #endif
339 if (res)
340 return luaL_fileresult(L, 0, NULL);
341 #if LJ_TARGET_POSIX
342 ofs = ftello(fp);
343 #elif _MSC_VER >= 1400
344 ofs = _ftelli64(fp);
345 #elif defined(__MINGW32__)
346 ofs = ftello64(fp);
347 #else
348 ofs = (int64_t)ftell(fp);
349 #endif
350 setint64V(L->top-1, ofs);
351 return 1;
354 LJLIB_CF(io_method_setvbuf)
356 FILE *fp = io_tofile(L)->fp;
357 int opt = lj_lib_checkopt(L, 2, -1, "\4full\4line\2no");
358 size_t sz = (size_t)lj_lib_optint(L, 3, LUAL_BUFFERSIZE);
359 if (opt == 0) opt = _IOFBF;
360 else if (opt == 1) opt = _IOLBF;
361 else if (opt == 2) opt = _IONBF;
362 return luaL_fileresult(L, setvbuf(fp, NULL, opt, sz) == 0, NULL);
365 LJLIB_CF(io_method_lines)
367 io_tofile(L);
368 return io_file_lines(L);
371 LJLIB_CF(io_method___gc)
373 IOFileUD *iof = io_tofilep(L);
374 if (iof->fp != NULL && (iof->type & IOFILE_TYPE_MASK) != IOFILE_TYPE_STDF)
375 io_file_close(L, iof);
376 return 0;
379 LJLIB_CF(io_method___tostring)
381 IOFileUD *iof = io_tofilep(L);
382 if (iof->fp != NULL)
383 lua_pushfstring(L, "file (%p)", iof->fp);
384 else
385 lua_pushliteral(L, "file (closed)");
386 return 1;
389 LJLIB_PUSH(top-1) LJLIB_SET(__index)
391 #include "lj_libdef.h"
393 /* -- I/O library functions ----------------------------------------------- */
395 #define LJLIB_MODULE_io
397 LJLIB_PUSH(top-2) LJLIB_SET(!) /* Set environment. */
399 LJLIB_CF(io_open)
401 const char *fname = strdata(lj_lib_checkstr(L, 1));
402 GCstr *s = lj_lib_optstr(L, 2);
403 const char *mode = s ? strdata(s) : "r";
404 IOFileUD *iof = io_file_new(L);
405 iof->fp = fopen(fname, mode);
406 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
409 LJLIB_CF(io_popen)
411 #if LJ_TARGET_POSIX || (LJ_TARGET_WINDOWS && !LJ_TARGET_XBOXONE)
412 const char *fname = strdata(lj_lib_checkstr(L, 1));
413 GCstr *s = lj_lib_optstr(L, 2);
414 const char *mode = s ? strdata(s) : "r";
415 IOFileUD *iof = io_file_new(L);
416 iof->type = IOFILE_TYPE_PIPE;
417 #if LJ_TARGET_POSIX
418 fflush(NULL);
419 iof->fp = popen(fname, mode);
420 #else
421 iof->fp = _popen(fname, mode);
422 #endif
423 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
424 #else
425 return luaL_error(L, LUA_QL("popen") " not supported");
426 #endif
429 LJLIB_CF(io_tmpfile)
431 IOFileUD *iof = io_file_new(L);
432 #if LJ_TARGET_PS3 || LJ_TARGET_PS4 || LJ_TARGET_PSVITA
433 iof->fp = NULL; errno = ENOSYS;
434 #else
435 iof->fp = tmpfile();
436 #endif
437 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, NULL);
440 LJLIB_CF(io_close)
442 return lj_cf_io_method_close(L);
445 LJLIB_CF(io_read)
447 return io_file_read(L, io_stdfile(L, GCROOT_IO_INPUT), 0);
450 LJLIB_CF(io_write) LJLIB_REC(io_write GCROOT_IO_OUTPUT)
452 return io_file_write(L, io_stdfile(L, GCROOT_IO_OUTPUT), 0);
455 LJLIB_CF(io_flush) LJLIB_REC(io_flush GCROOT_IO_OUTPUT)
457 return luaL_fileresult(L, fflush(io_stdfile(L, GCROOT_IO_OUTPUT)) == 0, NULL);
460 static int io_std_getset(lua_State *L, ptrdiff_t id, const char *mode)
462 if (L->base < L->top && !tvisnil(L->base)) {
463 if (tvisudata(L->base)) {
464 io_tofile(L);
465 L->top = L->base+1;
466 } else {
467 io_file_open(L, mode);
469 /* NOBARRIER: The standard I/O handles are GC roots. */
470 setgcref(G(L)->gcroot[id], gcV(L->top-1));
471 } else {
472 setudataV(L, L->top++, IOSTDF_UD(L, id));
474 return 1;
477 LJLIB_CF(io_input)
479 return io_std_getset(L, GCROOT_IO_INPUT, "r");
482 LJLIB_CF(io_output)
484 return io_std_getset(L, GCROOT_IO_OUTPUT, "w");
487 LJLIB_CF(io_lines)
489 if (L->base == L->top) setnilV(L->top++);
490 if (!tvisnil(L->base)) { /* io.lines(fname) */
491 IOFileUD *iof = io_file_open(L, "r");
492 iof->type = IOFILE_TYPE_FILE|IOFILE_FLAG_CLOSE;
493 L->top--;
494 setudataV(L, L->base, udataV(L->top));
495 } else { /* io.lines() iterates over stdin. */
496 setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_INPUT));
498 return io_file_lines(L);
501 LJLIB_CF(io_type)
503 cTValue *o = lj_lib_checkany(L, 1);
504 if (!(tvisudata(o) && udataV(o)->udtype == UDTYPE_IO_FILE))
505 setnilV(L->top++);
506 else if (((IOFileUD *)uddata(udataV(o)))->fp != NULL)
507 lua_pushliteral(L, "file");
508 else
509 lua_pushliteral(L, "closed file");
510 return 1;
513 #include "lj_libdef.h"
515 /* ------------------------------------------------------------------------ */
517 static GCobj *io_std_new(lua_State *L, FILE *fp, const char *name)
519 IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
520 GCudata *ud = udataV(L->top-1);
521 ud->udtype = UDTYPE_IO_FILE;
522 /* NOBARRIER: The GCudata is new (marked white). */
523 setgcref(ud->metatable, gcV(L->top-3));
524 iof->fp = fp;
525 iof->type = IOFILE_TYPE_STDF;
526 lua_setfield(L, -2, name);
527 return obj2gco(ud);
530 LUALIB_API int luaopen_io(lua_State *L)
532 LJ_LIB_REG(L, NULL, io_method);
533 copyTV(L, L->top, L->top-1); L->top++;
534 lua_setfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
535 LJ_LIB_REG(L, LUA_IOLIBNAME, io);
536 setgcref(G(L)->gcroot[GCROOT_IO_INPUT], io_std_new(L, stdin, "stdin"));
537 setgcref(G(L)->gcroot[GCROOT_IO_OUTPUT], io_std_new(L, stdout, "stdout"));
538 io_std_new(L, stderr, "stderr");
539 return 1;