3 ** Copyright (C) 2005-2012 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
25 /* Userdata payload for I/O file. */
26 typedef struct IOFileUD
{
27 FILE *fp
; /* File handle. */
28 uint32_t type
; /* File type. */
31 #define IOFILE_TYPE_FILE 0 /* Regular file. */
32 #define IOFILE_TYPE_PIPE 1 /* Pipe. */
33 #define IOFILE_TYPE_STDF 2 /* Standard file handle. */
34 #define IOFILE_TYPE_MASK 3
36 #define IOFILE_FLAG_CLOSE 4 /* Close after io.lines() iterator. */
38 #define IOSTDF_UD(L, id) (&gcref(G(L)->gcroot[(id)])->ud)
39 #define IOSTDF_IOF(L, id) ((IOFileUD *)uddata(IOSTDF_UD(L, (id))))
41 /* -- Open/close helpers -------------------------------------------------- */
43 static IOFileUD
*io_tofilep(lua_State
*L
)
45 if (!(L
->base
< L
->top
&& tvisudata(L
->base
) &&
46 udataV(L
->base
)->udtype
== UDTYPE_IO_FILE
))
47 lj_err_argtype(L
, 1, "FILE*");
48 return (IOFileUD
*)uddata(udataV(L
->base
));
51 static IOFileUD
*io_tofile(lua_State
*L
)
53 IOFileUD
*iof
= io_tofilep(L
);
55 lj_err_caller(L
, LJ_ERR_IOCLFL
);
59 static FILE *io_stdfile(lua_State
*L
, ptrdiff_t id
)
61 IOFileUD
*iof
= IOSTDF_IOF(L
, id
);
63 lj_err_caller(L
, LJ_ERR_IOSTDCL
);
67 static IOFileUD
*io_file_new(lua_State
*L
)
69 IOFileUD
*iof
= (IOFileUD
*)lua_newuserdata(L
, sizeof(IOFileUD
));
70 GCudata
*ud
= udataV(L
->top
-1);
71 ud
->udtype
= UDTYPE_IO_FILE
;
72 /* NOBARRIER: The GCudata is new (marked white). */
73 setgcrefr(ud
->metatable
, curr_func(L
)->c
.env
);
75 iof
->type
= IOFILE_TYPE_FILE
;
79 static IOFileUD
*io_file_open(lua_State
*L
, const char *mode
)
81 const char *fname
= strdata(lj_lib_checkstr(L
, 1));
82 IOFileUD
*iof
= io_file_new(L
);
83 iof
->fp
= fopen(fname
, mode
);
85 luaL_argerror(L
, 1, lj_str_pushf(L
, "%s: %s", fname
, strerror(errno
)));
89 static int io_file_close(lua_State
*L
, IOFileUD
*iof
)
92 if ((iof
->type
& IOFILE_TYPE_MASK
) == IOFILE_TYPE_FILE
) {
93 ok
= (fclose(iof
->fp
) == 0);
94 } else if ((iof
->type
& IOFILE_TYPE_MASK
) == IOFILE_TYPE_PIPE
) {
97 stat
= pclose(iof
->fp
);
98 #elif LJ_TARGET_WINDOWS
99 stat
= _pclose(iof
->fp
);
106 return luaL_execresult(L
, stat
);
111 lua_assert((iof
->type
& IOFILE_TYPE_MASK
) == IOFILE_TYPE_STDF
);
113 lua_pushliteral(L
, "cannot close standard file");
117 return luaL_fileresult(L
, ok
, NULL
);
120 /* -- Read/write helpers -------------------------------------------------- */
122 static int io_file_readnum(lua_State
*L
, FILE *fp
)
125 if (fscanf(fp
, LUA_NUMBER_SCAN
, &d
) == 1) {
127 int32_t i
= lj_num2int(d
);
128 if (d
== (lua_Number
)i
&& !tvismzero((cTValue
*)&d
)) {
129 setintV(L
->top
++, i
);
133 setnumV(L
->top
++, d
);
141 static int io_file_testeof(lua_State
*L
, FILE *fp
)
145 lua_pushlstring(L
, NULL
, 0);
149 static int io_file_readline(lua_State
*L
, FILE *fp
, size_t chop
)
152 luaL_buffinit(L
, &b
);
155 char *p
= luaL_prepbuffer(&b
);
156 if (fgets(p
, LUAL_BUFFERSIZE
, fp
) == NULL
) { /* EOF? */
158 return (strV(L
->top
-1)->len
> 0); /* Anything read? */
161 if (len
== 0 || p
[len
-1] != '\n') { /* Partial line? */
162 luaL_addsize(&b
, len
);
164 luaL_addsize(&b
, len
- chop
); /* Keep or remove EOL. */
166 return 1; /* Got at least an EOL. */
171 static int io_file_readchars(lua_State
*L
, FILE *fp
, size_t n
)
173 size_t rlen
; /* how much to read */
174 size_t nr
; /* number of chars actually read */
176 luaL_buffinit(L
, &b
);
177 rlen
= LUAL_BUFFERSIZE
; /* try to read that much each time */
179 char *p
= luaL_prepbuffer(&b
);
180 if (rlen
> n
) rlen
= n
; /* cannot read more than asked */
181 nr
= fread(p
, 1, rlen
, fp
);
182 luaL_addsize(&b
, nr
);
183 n
-= nr
; /* still have to read `n' chars */
184 } while (n
> 0 && nr
== rlen
); /* until end of count or eof */
185 luaL_pushresult(&b
); /* close buffer */
186 return (n
== 0 || strV(L
->top
-1)->len
> 0);
189 static int io_file_read(lua_State
*L
, FILE *fp
, int start
)
191 int ok
, n
, nargs
= (int)(L
->top
- L
->base
) - start
;
194 ok
= io_file_readline(L
, fp
, 1);
195 n
= start
+1; /* Return 1 result. */
197 /* The results plus the buffers go on top of the args. */
198 luaL_checkstack(L
, nargs
+LUA_MINSTACK
, "too many arguments");
200 for (n
= start
; nargs
-- && ok
; n
++) {
201 if (tvisstr(L
->base
+n
)) {
202 const char *p
= strVdata(L
->base
+n
);
204 lj_err_arg(L
, n
+1, LJ_ERR_INVOPT
);
206 ok
= io_file_readnum(L
, fp
);
207 else if ((p
[1] & ~0x20) == 'L')
208 ok
= io_file_readline(L
, fp
, (p
[1] == 'l'));
209 else if (p
[1] == 'a')
210 io_file_readchars(L
, fp
, ~((size_t)0));
212 lj_err_arg(L
, n
+1, LJ_ERR_INVFMT
);
213 } else if (tvisnumber(L
->base
+n
)) {
214 size_t len
= (size_t)lj_lib_checkint(L
, n
+1);
215 ok
= len
? io_file_readchars(L
, fp
, len
) : io_file_testeof(L
, fp
);
217 lj_err_arg(L
, n
+1, LJ_ERR_INVOPT
);
222 return luaL_fileresult(L
, 0, NULL
);
224 setnilV(L
->top
-1); /* Replace last result with nil. */
228 static int io_file_write(lua_State
*L
, FILE *fp
, int start
)
232 for (tv
= L
->base
+start
; tv
< L
->top
; tv
++) {
234 MSize len
= strV(tv
)->len
;
235 status
= status
&& (fwrite(strVdata(tv
), 1, len
, fp
) == len
);
236 } else if (tvisint(tv
)) {
237 char buf
[LJ_STR_INTBUF
];
238 char *p
= lj_str_bufint(buf
, intV(tv
));
239 size_t len
= (size_t)(buf
+LJ_STR_INTBUF
-p
);
240 status
= status
&& (fwrite(p
, 1, len
, fp
) == len
);
241 } else if (tvisnum(tv
)) {
242 status
= status
&& (fprintf(fp
, LUA_NUMBER_FMT
, numV(tv
)) > 0);
244 lj_err_argt(L
, (int)(tv
- L
->base
) + 1, LUA_TSTRING
);
247 if (LJ_52
&& status
) {
250 setudataV(L
, L
->base
, IOSTDF_UD(L
, GCROOT_IO_OUTPUT
));
253 return luaL_fileresult(L
, status
, NULL
);
256 /* -- I/O file methods ---------------------------------------------------- */
258 #define LJLIB_MODULE_io_method
260 LJLIB_CF(io_method_close
)
262 IOFileUD
*iof
= L
->base
< L
->top
? io_tofile(L
) :
263 IOSTDF_IOF(L
, GCROOT_IO_OUTPUT
);
264 return io_file_close(L
, iof
);
267 LJLIB_CF(io_method_read
)
269 return io_file_read(L
, io_tofile(L
)->fp
, 1);
272 LJLIB_CF(io_method_write
) LJLIB_REC(io_write
0)
274 return io_file_write(L
, io_tofile(L
)->fp
, 1);
277 LJLIB_CF(io_method_flush
) LJLIB_REC(io_flush
0)
279 return luaL_fileresult(L
, fflush(io_tofile(L
)->fp
) == 0, NULL
);
282 LJLIB_CF(io_method_seek
)
284 FILE *fp
= io_tofile(L
)->fp
;
285 int opt
= lj_lib_checkopt(L
, 2, 1, "\3set\3cur\3end");
289 if (opt
== 0) opt
= SEEK_SET
;
290 else if (opt
== 1) opt
= SEEK_CUR
;
291 else if (opt
== 2) opt
= SEEK_END
;
295 ofs
= (int64_t)intV(o
);
297 ofs
= (int64_t)numV(o
);
298 else if (!tvisnil(o
))
299 lj_err_argt(L
, 3, LUA_TNUMBER
);
302 res
= fseeko(fp
, ofs
, opt
);
303 #elif _MSC_VER >= 1400
304 res
= _fseeki64(fp
, ofs
, opt
);
305 #elif defined(__MINGW32__)
306 res
= fseeko64(fp
, ofs
, opt
);
308 res
= fseek(fp
, (long)ofs
, opt
);
311 return luaL_fileresult(L
, 0, NULL
);
314 #elif _MSC_VER >= 1400
316 #elif defined(__MINGW32__)
319 ofs
= (int64_t)ftell(fp
);
321 setint64V(L
->top
-1, ofs
);
325 LJLIB_CF(io_method_setvbuf
)
327 FILE *fp
= io_tofile(L
)->fp
;
328 int opt
= lj_lib_checkopt(L
, 2, -1, "\4full\4line\2no");
329 size_t sz
= (size_t)lj_lib_optint(L
, 3, LUAL_BUFFERSIZE
);
330 if (opt
== 0) opt
= _IOFBF
;
331 else if (opt
== 1) opt
= _IOLBF
;
332 else if (opt
== 2) opt
= _IONBF
;
333 return luaL_fileresult(L
, setvbuf(fp
, NULL
, opt
, sz
) == 0, NULL
);
336 LJLIB_PUSH(top
-2) /* io_lines_iter */
337 LJLIB_CF(io_method_lines
)
340 setfuncV(L
, L
->top
, funcV(lj_lib_upvalue(L
, 1)));
341 setudataV(L
, L
->top
+1, udataV(L
->base
));
346 LJLIB_CF(io_method___gc
)
348 IOFileUD
*iof
= io_tofilep(L
);
349 if (iof
->fp
!= NULL
&& (iof
->type
& IOFILE_TYPE_MASK
) != IOFILE_TYPE_STDF
)
350 io_file_close(L
, iof
);
354 LJLIB_CF(io_method___tostring
)
356 IOFileUD
*iof
= io_tofilep(L
);
358 lua_pushfstring(L
, "file (%p)", iof
->fp
);
360 lua_pushliteral(L
, "file (closed)");
364 LJLIB_PUSH(top
-1) LJLIB_SET(__index
)
366 #include "lj_libdef.h"
368 /* -- I/O library functions ----------------------------------------------- */
370 #define LJLIB_MODULE_io
372 LJLIB_PUSH(top
-2) LJLIB_SET(!) /* Set environment. */
376 const char *fname
= strdata(lj_lib_checkstr(L
, 1));
377 GCstr
*s
= lj_lib_optstr(L
, 2);
378 const char *mode
= s
? strdata(s
) : "r";
379 IOFileUD
*iof
= io_file_new(L
);
380 iof
->fp
= fopen(fname
, mode
);
381 return iof
->fp
!= NULL
? 1 : luaL_fileresult(L
, 0, fname
);
386 #if LJ_TARGET_POSIX || LJ_TARGET_WINDOWS
387 const char *fname
= strdata(lj_lib_checkstr(L
, 1));
388 GCstr
*s
= lj_lib_optstr(L
, 2);
389 const char *mode
= s
? strdata(s
) : "r";
390 IOFileUD
*iof
= io_file_new(L
);
391 iof
->type
= IOFILE_TYPE_PIPE
;
394 iof
->fp
= popen(fname
, mode
);
396 iof
->fp
= _popen(fname
, mode
);
398 return iof
->fp
!= NULL
? 1 : luaL_fileresult(L
, 0, fname
);
400 return luaL_error(L
, LUA_QL("popen") " not supported");
406 IOFileUD
*iof
= io_file_new(L
);
408 iof
->fp
= NULL
; errno
= ENOSYS
;
412 return iof
->fp
!= NULL
? 1 : luaL_fileresult(L
, 0, NULL
);
417 return lj_cf_io_method_close(L
);
422 return io_file_read(L
, io_stdfile(L
, GCROOT_IO_INPUT
), 0);
425 LJLIB_CF(io_write
) LJLIB_REC(io_write GCROOT_IO_OUTPUT
)
427 return io_file_write(L
, io_stdfile(L
, GCROOT_IO_OUTPUT
), 0);
430 LJLIB_CF(io_flush
) LJLIB_REC(io_flush GCROOT_IO_OUTPUT
)
432 return luaL_fileresult(L
, fflush(io_stdfile(L
, GCROOT_IO_OUTPUT
)) == 0, NULL
);
435 static int io_std_getset(lua_State
*L
, ptrdiff_t id
, const char *mode
)
437 if (L
->base
< L
->top
&& !tvisnil(L
->base
)) {
438 if (tvisudata(L
->base
)) {
442 io_file_open(L
, mode
);
444 /* NOBARRIER: The standard I/O handles are GC roots. */
445 setgcref(G(L
)->gcroot
[id
], gcV(L
->top
-1));
447 setudataV(L
, L
->top
++, IOSTDF_UD(L
, id
));
454 return io_std_getset(L
, GCROOT_IO_INPUT
, "r");
459 return io_std_getset(L
, GCROOT_IO_OUTPUT
, "w");
462 LJLIB_NOREG
LJLIB_CF(io_lines_iter
)
464 IOFileUD
*iof
= io_tofile(L
);
465 int ok
= io_file_readline(L
, iof
->fp
, 1);
467 lj_err_callermsg(L
, strerror(errno
));
468 if (!ok
&& (iof
->type
& IOFILE_FLAG_CLOSE
))
469 io_file_close(L
, iof
); /* Return values are ignored (ok is 0). */
473 LJLIB_PUSH(top
-3) /* io_lines_iter */
476 if (L
->base
< L
->top
&& !tvisnil(L
->base
)) { /* io.lines(fname) */
477 IOFileUD
*iof
= io_file_open(L
, "r");
478 iof
->type
= IOFILE_TYPE_FILE
|IOFILE_FLAG_CLOSE
;
479 setfuncV(L
, L
->top
-2, funcV(lj_lib_upvalue(L
, 1)));
480 } else { /* io.lines() iterates over stdin. */
481 setfuncV(L
, L
->top
, funcV(lj_lib_upvalue(L
, 1)));
482 setudataV(L
, L
->top
+1, IOSTDF_UD(L
, GCROOT_IO_INPUT
));
490 cTValue
*o
= lj_lib_checkany(L
, 1);
491 if (!(tvisudata(o
) && udataV(o
)->udtype
== UDTYPE_IO_FILE
))
493 else if (((IOFileUD
*)uddata(udataV(o
)))->fp
!= NULL
)
494 lua_pushliteral(L
, "file");
496 lua_pushliteral(L
, "closed file");
500 #include "lj_libdef.h"
502 /* ------------------------------------------------------------------------ */
504 static GCobj
*io_std_new(lua_State
*L
, FILE *fp
, const char *name
)
506 IOFileUD
*iof
= (IOFileUD
*)lua_newuserdata(L
, sizeof(IOFileUD
));
507 GCudata
*ud
= udataV(L
->top
-1);
508 ud
->udtype
= UDTYPE_IO_FILE
;
509 /* NOBARRIER: The GCudata is new (marked white). */
510 setgcref(ud
->metatable
, gcV(L
->top
-3));
512 iof
->type
= IOFILE_TYPE_STDF
;
513 lua_setfield(L
, -2, name
);
517 LUALIB_API
int luaopen_io(lua_State
*L
)
519 lj_lib_pushcf(L
, lj_cf_io_lines_iter
, FF_io_lines_iter
);
520 LJ_LIB_REG(L
, NULL
, io_method
);
521 copyTV(L
, L
->top
, L
->top
-1); L
->top
++;
522 lua_setfield(L
, LUA_REGISTRYINDEX
, LUA_FILEHANDLE
);
523 LJ_LIB_REG(L
, LUA_IOLIBNAME
, io
);
524 setgcref(G(L
)->gcroot
[GCROOT_IO_INPUT
], io_std_new(L
, stdin
, "stdin"));
525 setgcref(G(L
)->gcroot
[GCROOT_IO_OUTPUT
], io_std_new(L
, stdout
, "stdout"));
526 io_std_new(L
, stderr
, "stderr");