3 ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
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
27 /* Userdata payload for I/O file. */
28 typedef struct IOFileUD
{
29 FILE *fp
; /* File handle. */
30 uint32_t type
; /* File type. */
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
);
57 lj_err_caller(L
, LJ_ERR_IOCLFL
);
61 static IOFileUD
*io_stdfile(lua_State
*L
, ptrdiff_t id
)
63 IOFileUD
*iof
= IOSTDF_IOF(L
, id
);
65 lj_err_caller(L
, LJ_ERR_IOSTDCL
);
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
);
77 iof
->type
= IOFILE_TYPE_FILE
;
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
);
87 luaL_argerror(L
, 1, lj_str_pushf(L
, "%s: %s", fname
, strerror(errno
)));
91 static int io_file_close(lua_State
*L
, IOFileUD
*iof
)
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
) {
99 stat
= pclose(iof
->fp
);
100 #elif LJ_TARGET_WINDOWS
101 stat
= _pclose(iof
->fp
);
108 return luaL_execresult(L
, stat
);
113 lua_assert((iof
->type
& IOFILE_TYPE_MASK
) == IOFILE_TYPE_STDF
);
115 lua_pushliteral(L
, "cannot close standard file");
119 return luaL_fileresult(L
, ok
, NULL
);
122 /* -- Read/write helpers -------------------------------------------------- */
124 static int io_file_readnum(lua_State
*L
, FILE *fp
)
127 if (fscanf(fp
, LUA_NUMBER_SCAN
, &d
) == 1) {
129 int32_t i
= lj_num2int(d
);
130 if (d
== (lua_Number
)i
&& !tvismzero((cTValue
*)&d
)) {
131 setintV(L
->top
++, i
);
135 setnumV(L
->top
++, d
);
143 static int io_file_readline(lua_State
*L
, FILE *fp
, MSize chop
)
145 MSize m
= LUAL_BUFFERSIZE
, n
= 0, ok
= 0;
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
);
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
));
160 static void io_file_readall(lua_State
*L
, FILE *fp
)
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
);
167 setstrV(L
, L
->top
++, lj_str_new(L
, buf
, (size_t)n
));
174 static int io_file_readlen(lua_State
*L
, FILE *fp
, MSize 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
));
185 setstrV(L
, L
->top
++, &G(L
)->strempty
);
190 static int io_file_read(lua_State
*L
, IOFileUD
*iof
, int start
)
193 int ok
, n
, nargs
= (int)(L
->top
- L
->base
) - start
;
196 ok
= io_file_readline(L
, fp
, 1);
197 n
= start
+1; /* Return 1 result. */
199 /* The results plus the buffers go on top of the args. */
200 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
202 for (n
= start
; nargs
-- && ok
; n
++) {
203 if (tvisstr(L
->base
+n
)) {
204 const char *p
= strVdata(L
->base
+n
);
206 lj_err_arg(L
, n
+1, LJ_ERR_INVOPT
);
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
);
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));
218 lj_err_arg(L
, n
+1, LJ_ERR_INVOPT
);
223 return luaL_fileresult(L
, 0, NULL
);
225 setnilV(L
->top
-1); /* Replace last result with nil. */
229 static int io_file_write(lua_State
*L
, IOFileUD
*iof
, int start
)
234 for (tv
= L
->base
+start
; tv
< L
->top
; 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);
246 lj_err_argt(L
, (int)(tv
- L
->base
) + 1, LUA_TSTRING
);
249 if (LJ_52
&& status
) {
252 setudataV(L
, L
->base
, IOSTDF_UD(L
, GCROOT_IO_OUTPUT
));
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;
264 lj_err_caller(L
, LJ_ERR_IOCLFL
);
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
));
271 n
= io_file_read(L
, iof
, 0);
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. */
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
);
290 /* -- I/O file methods ---------------------------------------------------- */
292 #define LJLIB_MODULE_io_method
294 LJLIB_CF(io_method_close
)
297 if (L
->base
< L
->top
) {
300 iof
= IOSTDF_IOF(L
, GCROOT_IO_OUTPUT
);
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");
329 if (opt
== 0) opt
= SEEK_SET
;
330 else if (opt
== 1) opt
= SEEK_CUR
;
331 else if (opt
== 2) opt
= SEEK_END
;
335 ofs
= (int64_t)intV(o
);
337 ofs
= (int64_t)numV(o
);
338 else if (!tvisnil(o
))
339 lj_err_argt(L
, 3, LUA_TNUMBER
);
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
);
348 res
= fseek(fp
, (long)ofs
, opt
);
351 return luaL_fileresult(L
, 0, NULL
);
354 #elif _MSC_VER >= 1400
356 #elif defined(__MINGW32__)
359 ofs
= (int64_t)ftell(fp
);
361 setint64V(L
->top
-1, ofs
);
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
)
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
);
390 LJLIB_CF(io_method___tostring
)
392 IOFileUD
*iof
= io_tofilep(L
);
394 lua_pushfstring(L
, "file (%p)", iof
->fp
);
396 lua_pushliteral(L
, "file (closed)");
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. */
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
);
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
;
430 iof
->fp
= popen(fname
, mode
);
432 iof
->fp
= _popen(fname
, mode
);
434 return iof
->fp
!= NULL
? 1 : luaL_fileresult(L
, 0, fname
);
436 return luaL_error(L
, LUA_QL("popen") " not supported");
442 IOFileUD
*iof
= io_file_new(L
);
443 #if LJ_TARGET_PS3 || LJ_TARGET_PS4 || LJ_TARGET_PSVITA
444 iof
->fp
= NULL
; errno
= ENOSYS
;
448 return iof
->fp
!= NULL
? 1 : luaL_fileresult(L
, 0, NULL
);
453 return lj_cf_io_method_close(L
);
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
)) {
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));
483 setudataV(L
, L
->top
++, IOSTDF_UD(L
, id
));
490 return io_std_getset(L
, GCROOT_IO_INPUT
, "r");
495 return io_std_getset(L
, GCROOT_IO_OUTPUT
, "w");
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
;
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
);
514 cTValue
*o
= lj_lib_checkany(L
, 1);
515 if (!(tvisudata(o
) && udataV(o
)->udtype
== UDTYPE_IO_FILE
))
517 else if (((IOFileUD
*)uddata(udataV(o
)))->fp
!= NULL
)
518 lua_pushliteral(L
, "file");
520 lua_pushliteral(L
, "closed file");
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));
536 iof
->type
= IOFILE_TYPE_STDF
;
537 lua_setfield(L
, -2, name
);
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");