FFI: Fix pragma push stack limit check and throw on overflow.
[luajit-2.0.git] / src / lib_io.c
blobf7db083e3c6e06144a6f943b3fadc9959c9c69ea
1 /*
2 ** I/O library.
3 ** Copyright (C) 2005-2023 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_str.h"
23 #include "lj_state.h"
24 #include "lj_ff.h"
25 #include "lj_lib.h"
27 /* Userdata payload for I/O file. */
28 typedef struct IOFileUD {
29 FILE *fp; /* File handle. */
30 uint32_t type; /* File type. */
31 } IOFileUD;
33 #define IOFILE_TYPE_FILE 0 /* Regular file. */
34 #define IOFILE_TYPE_PIPE 1 /* Pipe. */
35 #define IOFILE_TYPE_STDF 2 /* Standard file handle. */
36 #define IOFILE_TYPE_MASK 3
38 #define IOFILE_FLAG_CLOSE 4 /* Close after io.lines() iterator. */
40 #define IOSTDF_UD(L, id) (&gcref(G(L)->gcroot[(id)])->ud)
41 #define IOSTDF_IOF(L, id) ((IOFileUD *)uddata(IOSTDF_UD(L, (id))))
43 /* -- Open/close helpers -------------------------------------------------- */
45 static IOFileUD *io_tofilep(lua_State *L)
47 if (!(L->base < L->top && tvisudata(L->base) &&
48 udataV(L->base)->udtype == UDTYPE_IO_FILE))
49 lj_err_argtype(L, 1, "FILE*");
50 return (IOFileUD *)uddata(udataV(L->base));
53 static IOFileUD *io_tofile(lua_State *L)
55 IOFileUD *iof = io_tofilep(L);
56 if (iof->fp == NULL)
57 lj_err_caller(L, LJ_ERR_IOCLFL);
58 return iof;
61 static IOFileUD *io_stdfile(lua_State *L, ptrdiff_t id)
63 IOFileUD *iof = IOSTDF_IOF(L, id);
64 if (iof->fp == NULL)
65 lj_err_caller(L, LJ_ERR_IOSTDCL);
66 return iof;
69 static IOFileUD *io_file_new(lua_State *L)
71 IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
72 GCudata *ud = udataV(L->top-1);
73 ud->udtype = UDTYPE_IO_FILE;
74 /* NOBARRIER: The GCudata is new (marked white). */
75 setgcrefr(ud->metatable, curr_func(L)->c.env);
76 iof->fp = NULL;
77 iof->type = IOFILE_TYPE_FILE;
78 return iof;
81 static IOFileUD *io_file_open(lua_State *L, const char *mode)
83 const char *fname = strdata(lj_lib_checkstr(L, 1));
84 IOFileUD *iof = io_file_new(L);
85 iof->fp = fopen(fname, mode);
86 if (iof->fp == NULL)
87 luaL_argerror(L, 1, lj_str_pushf(L, "%s: %s", fname, strerror(errno)));
88 return iof;
91 static int io_file_close(lua_State *L, IOFileUD *iof)
93 int ok;
94 if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_FILE) {
95 ok = (fclose(iof->fp) == 0);
96 } else if ((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_PIPE) {
97 int stat = -1;
98 #if LJ_TARGET_POSIX
99 stat = pclose(iof->fp);
100 #elif LJ_TARGET_WINDOWS
101 stat = _pclose(iof->fp);
102 #else
103 lua_assert(0);
104 return 0;
105 #endif
106 #if LJ_52
107 iof->fp = NULL;
108 return luaL_execresult(L, stat);
109 #else
110 ok = (stat != -1);
111 #endif
112 } else {
113 lua_assert((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_STDF);
114 setnilV(L->top++);
115 lua_pushliteral(L, "cannot close standard file");
116 return 2;
118 iof->fp = NULL;
119 return luaL_fileresult(L, ok, NULL);
122 /* -- Read/write helpers -------------------------------------------------- */
124 static int io_file_readnum(lua_State *L, FILE *fp)
126 lua_Number d;
127 if (fscanf(fp, LUA_NUMBER_SCAN, &d) == 1) {
128 if (LJ_DUALNUM) {
129 int32_t i = lj_num2int(d);
130 if (d == (lua_Number)i && !tvismzero((cTValue *)&d)) {
131 setintV(L->top++, i);
132 return 1;
135 setnumV(L->top++, d);
136 return 1;
137 } else {
138 setnilV(L->top++);
139 return 0;
143 static int io_file_readline(lua_State *L, FILE *fp, MSize chop)
145 MSize m = LUAL_BUFFERSIZE, n = 0, ok = 0;
146 char *buf;
147 for (;;) {
148 buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
149 if (fgets(buf+n, m-n, fp) == NULL) break;
150 n += (MSize)strlen(buf+n);
151 ok |= n;
152 if (n && buf[n-1] == '\n') { n -= chop; break; }
153 if (n >= m - 64) m += m;
155 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
156 lj_gc_check(L);
157 return (int)ok;
160 static void io_file_readall(lua_State *L, FILE *fp)
162 MSize m, n;
163 for (m = LUAL_BUFFERSIZE, n = 0; ; m += m) {
164 char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
165 n += (MSize)fread(buf+n, 1, m-n, fp);
166 if (n != m) {
167 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
168 lj_gc_check(L);
169 return;
174 static int io_file_readlen(lua_State *L, FILE *fp, MSize m)
176 if (m) {
177 char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m);
178 MSize n = (MSize)fread(buf, 1, m, fp);
179 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
180 lj_gc_check(L);
181 return n > 0;
182 } else {
183 int c = getc(fp);
184 ungetc(c, fp);
185 setstrV(L, L->top++, &G(L)->strempty);
186 return (c != EOF);
190 static int io_file_read(lua_State *L, IOFileUD *iof, int start)
192 FILE *fp = iof->fp;
193 int ok, n, nargs = (int)(L->top - L->base) - start;
194 clearerr(fp);
195 if (nargs == 0) {
196 ok = io_file_readline(L, fp, 1);
197 n = start+1; /* Return 1 result. */
198 } else {
199 /* The results plus the buffers go on top of the args. */
200 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
201 ok = 1;
202 for (n = start; nargs-- && ok; n++) {
203 if (tvisstr(L->base+n)) {
204 const char *p = strVdata(L->base+n);
205 if (p[0] != '*')
206 lj_err_arg(L, n+1, LJ_ERR_INVOPT);
207 if (p[1] == 'n')
208 ok = io_file_readnum(L, fp);
209 else if ((p[1] & ~0x20) == 'L')
210 ok = io_file_readline(L, fp, (p[1] == 'l'));
211 else if (p[1] == 'a')
212 io_file_readall(L, fp);
213 else
214 lj_err_arg(L, n+1, LJ_ERR_INVFMT);
215 } else if (tvisnumber(L->base+n)) {
216 ok = io_file_readlen(L, fp, (MSize)lj_lib_checkint(L, n+1));
217 } else {
218 lj_err_arg(L, n+1, LJ_ERR_INVOPT);
222 if (ferror(fp))
223 return luaL_fileresult(L, 0, NULL);
224 if (!ok)
225 setnilV(L->top-1); /* Replace last result with nil. */
226 return n - start;
229 static int io_file_write(lua_State *L, IOFileUD *iof, int start)
231 FILE *fp = iof->fp;
232 cTValue *tv;
233 int status = 1;
234 for (tv = L->base+start; tv < L->top; tv++) {
235 if (tvisstr(tv)) {
236 MSize len = strV(tv)->len;
237 status = status && (fwrite(strVdata(tv), 1, len, fp) == len);
238 } else if (tvisint(tv)) {
239 char buf[LJ_STR_INTBUF];
240 char *p = lj_str_bufint(buf, intV(tv));
241 size_t len = (size_t)(buf+LJ_STR_INTBUF-p);
242 status = status && (fwrite(p, 1, len, fp) == len);
243 } else if (tvisnum(tv)) {
244 status = status && (fprintf(fp, LUA_NUMBER_FMT, numV(tv)) > 0);
245 } else {
246 lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING);
249 if (LJ_52 && status) {
250 L->top = L->base+1;
251 if (start == 0)
252 setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_OUTPUT));
253 return 1;
255 return luaL_fileresult(L, status, NULL);
258 static int io_file_iter(lua_State *L)
260 GCfunc *fn = curr_func(L);
261 IOFileUD *iof = uddata(udataV(&fn->c.upvalue[0]));
262 int n = fn->c.nupvalues - 1;
263 if (iof->fp == NULL)
264 lj_err_caller(L, LJ_ERR_IOCLFL);
265 L->top = L->base;
266 if (n) { /* Copy upvalues with options to stack. */
267 lj_state_checkstack(L, (MSize)n);
268 memcpy(L->top, &fn->c.upvalue[1], n*sizeof(TValue));
269 L->top += n;
271 n = io_file_read(L, iof, 0);
272 if (ferror(iof->fp))
273 lj_err_callermsg(L, strVdata(L->top-2));
274 if (tvisnil(L->base) && (iof->type & IOFILE_FLAG_CLOSE)) {
275 io_file_close(L, iof); /* Return values are ignored. */
276 return 0;
278 return n;
281 static int io_file_lines(lua_State *L)
283 int n = (int)(L->top - L->base);
284 if (n > LJ_MAX_UPVAL)
285 lj_err_caller(L, LJ_ERR_UNPACK);
286 lua_pushcclosure(L, io_file_iter, n);
287 return 1;
290 /* -- I/O file methods ---------------------------------------------------- */
292 #define LJLIB_MODULE_io_method
294 LJLIB_CF(io_method_close)
296 IOFileUD *iof;
297 if (L->base < L->top) {
298 iof = io_tofile(L);
299 } else {
300 iof = IOSTDF_IOF(L, GCROOT_IO_OUTPUT);
301 if (iof->fp == NULL)
302 lj_err_caller(L, LJ_ERR_IOCLFL);
304 return io_file_close(L, iof);
307 LJLIB_CF(io_method_read)
309 return io_file_read(L, io_tofile(L), 1);
312 LJLIB_CF(io_method_write) LJLIB_REC(io_write 0)
314 return io_file_write(L, io_tofile(L), 1);
317 LJLIB_CF(io_method_flush) LJLIB_REC(io_flush 0)
319 return luaL_fileresult(L, fflush(io_tofile(L)->fp) == 0, NULL);
322 LJLIB_CF(io_method_seek)
324 FILE *fp = io_tofile(L)->fp;
325 int opt = lj_lib_checkopt(L, 2, 1, "\3set\3cur\3end");
326 int64_t ofs = 0;
327 cTValue *o;
328 int res;
329 if (opt == 0) opt = SEEK_SET;
330 else if (opt == 1) opt = SEEK_CUR;
331 else if (opt == 2) opt = SEEK_END;
332 o = L->base+2;
333 if (o < L->top) {
334 if (tvisint(o))
335 ofs = (int64_t)intV(o);
336 else if (tvisnum(o))
337 ofs = (int64_t)numV(o);
338 else if (!tvisnil(o))
339 lj_err_argt(L, 3, LUA_TNUMBER);
341 #if LJ_TARGET_POSIX
342 res = fseeko(fp, ofs, opt);
343 #elif _MSC_VER >= 1400
344 res = _fseeki64(fp, ofs, opt);
345 #elif defined(__MINGW32__)
346 res = fseeko64(fp, ofs, opt);
347 #else
348 res = fseek(fp, (long)ofs, opt);
349 #endif
350 if (res)
351 return luaL_fileresult(L, 0, NULL);
352 #if LJ_TARGET_POSIX
353 ofs = ftello(fp);
354 #elif _MSC_VER >= 1400
355 ofs = _ftelli64(fp);
356 #elif defined(__MINGW32__)
357 ofs = ftello64(fp);
358 #else
359 ofs = (int64_t)ftell(fp);
360 #endif
361 setint64V(L->top-1, ofs);
362 return 1;
365 LJLIB_CF(io_method_setvbuf)
367 FILE *fp = io_tofile(L)->fp;
368 int opt = lj_lib_checkopt(L, 2, -1, "\4full\4line\2no");
369 size_t sz = (size_t)lj_lib_optint(L, 3, LUAL_BUFFERSIZE);
370 if (opt == 0) opt = _IOFBF;
371 else if (opt == 1) opt = _IOLBF;
372 else if (opt == 2) opt = _IONBF;
373 return luaL_fileresult(L, setvbuf(fp, NULL, opt, sz) == 0, NULL);
376 LJLIB_CF(io_method_lines)
378 io_tofile(L);
379 return io_file_lines(L);
382 LJLIB_CF(io_method___gc)
384 IOFileUD *iof = io_tofilep(L);
385 if (iof->fp != NULL && (iof->type & IOFILE_TYPE_MASK) != IOFILE_TYPE_STDF)
386 io_file_close(L, iof);
387 return 0;
390 LJLIB_CF(io_method___tostring)
392 IOFileUD *iof = io_tofilep(L);
393 if (iof->fp != NULL)
394 lua_pushfstring(L, "file (%p)", iof->fp);
395 else
396 lua_pushliteral(L, "file (closed)");
397 return 1;
400 LJLIB_PUSH(top-1) LJLIB_SET(__index)
402 #include "lj_libdef.h"
404 /* -- I/O library functions ----------------------------------------------- */
406 #define LJLIB_MODULE_io
408 LJLIB_PUSH(top-2) LJLIB_SET(!) /* Set environment. */
410 LJLIB_CF(io_open)
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->fp = fopen(fname, mode);
417 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
420 LJLIB_CF(io_popen)
422 #if LJ_TARGET_POSIX || LJ_TARGET_WINDOWS
423 const char *fname = strdata(lj_lib_checkstr(L, 1));
424 GCstr *s = lj_lib_optstr(L, 2);
425 const char *mode = s ? strdata(s) : "r";
426 IOFileUD *iof = io_file_new(L);
427 iof->type = IOFILE_TYPE_PIPE;
428 #if LJ_TARGET_POSIX
429 fflush(NULL);
430 iof->fp = popen(fname, mode);
431 #else
432 iof->fp = _popen(fname, mode);
433 #endif
434 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
435 #else
436 return luaL_error(L, LUA_QL("popen") " not supported");
437 #endif
440 LJLIB_CF(io_tmpfile)
442 IOFileUD *iof = io_file_new(L);
443 #if LJ_TARGET_PS3 || LJ_TARGET_PS4 || LJ_TARGET_PSVITA
444 iof->fp = NULL; errno = ENOSYS;
445 #else
446 iof->fp = tmpfile();
447 #endif
448 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, NULL);
451 LJLIB_CF(io_close)
453 return lj_cf_io_method_close(L);
456 LJLIB_CF(io_read)
458 return io_file_read(L, io_stdfile(L, GCROOT_IO_INPUT), 0);
461 LJLIB_CF(io_write) LJLIB_REC(io_write GCROOT_IO_OUTPUT)
463 return io_file_write(L, io_stdfile(L, GCROOT_IO_OUTPUT), 0);
466 LJLIB_CF(io_flush) LJLIB_REC(io_flush GCROOT_IO_OUTPUT)
468 return luaL_fileresult(L, fflush(io_stdfile(L, GCROOT_IO_OUTPUT)->fp) == 0, NULL);
471 static int io_std_getset(lua_State *L, ptrdiff_t id, const char *mode)
473 if (L->base < L->top && !tvisnil(L->base)) {
474 if (tvisudata(L->base)) {
475 io_tofile(L);
476 L->top = L->base+1;
477 } else {
478 io_file_open(L, mode);
480 /* NOBARRIER: The standard I/O handles are GC roots. */
481 setgcref(G(L)->gcroot[id], gcV(L->top-1));
482 } else {
483 setudataV(L, L->top++, IOSTDF_UD(L, id));
485 return 1;
488 LJLIB_CF(io_input)
490 return io_std_getset(L, GCROOT_IO_INPUT, "r");
493 LJLIB_CF(io_output)
495 return io_std_getset(L, GCROOT_IO_OUTPUT, "w");
498 LJLIB_CF(io_lines)
500 if (L->base == L->top) setnilV(L->top++);
501 if (!tvisnil(L->base)) { /* io.lines(fname) */
502 IOFileUD *iof = io_file_open(L, "r");
503 iof->type = IOFILE_TYPE_FILE|IOFILE_FLAG_CLOSE;
504 L->top--;
505 setudataV(L, L->base, udataV(L->top));
506 } else { /* io.lines() iterates over stdin. */
507 setudataV(L, L->base, IOSTDF_UD(L, GCROOT_IO_INPUT));
509 return io_file_lines(L);
512 LJLIB_CF(io_type)
514 cTValue *o = lj_lib_checkany(L, 1);
515 if (!(tvisudata(o) && udataV(o)->udtype == UDTYPE_IO_FILE))
516 setnilV(L->top++);
517 else if (((IOFileUD *)uddata(udataV(o)))->fp != NULL)
518 lua_pushliteral(L, "file");
519 else
520 lua_pushliteral(L, "closed file");
521 return 1;
524 #include "lj_libdef.h"
526 /* ------------------------------------------------------------------------ */
528 static GCobj *io_std_new(lua_State *L, FILE *fp, const char *name)
530 IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
531 GCudata *ud = udataV(L->top-1);
532 ud->udtype = UDTYPE_IO_FILE;
533 /* NOBARRIER: The GCudata is new (marked white). */
534 setgcref(ud->metatable, gcV(L->top-3));
535 iof->fp = fp;
536 iof->type = IOFILE_TYPE_STDF;
537 lua_setfield(L, -2, name);
538 return obj2gco(ud);
541 LUALIB_API int luaopen_io(lua_State *L)
543 LJ_LIB_REG(L, NULL, io_method);
544 copyTV(L, L->top, L->top-1); L->top++;
545 lua_setfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
546 LJ_LIB_REG(L, LUA_IOLIBNAME, io);
547 setgcref(G(L)->gcroot[GCROOT_IO_INPUT], io_std_new(L, stdin, "stdin"));
548 setgcref(G(L)->gcroot[GCROOT_IO_OUTPUT], io_std_new(L, stdout, "stdout"));
549 io_std_new(L, stderr, "stderr");
550 return 1;