From Lua 5.2: Extended results from os.execute() and pipe:close().
[luajit-2.0/celess22.git] / src / lib_io.c
blob142bfae54821f6e8e6eea61b8343e15d0ec6c7cf
1 /*
2 ** I/O library.
3 ** Copyright (C) 2005-2012 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_err.h"
21 #include "lj_str.h"
22 #include "lj_ff.h"
23 #include "lj_lib.h"
25 /* Userdata payload for I/O file. */
26 typedef struct IOFileUD {
27 FILE *fp; /* File handle. */
28 uint32_t type; /* File type. */
29 } IOFileUD;
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);
54 if (iof->fp == NULL)
55 lj_err_caller(L, LJ_ERR_IOCLFL);
56 return iof;
59 static FILE *io_stdfile(lua_State *L, ptrdiff_t id)
61 IOFileUD *iof = IOSTDF_IOF(L, id);
62 if (iof->fp == NULL)
63 lj_err_caller(L, LJ_ERR_IOSTDCL);
64 return iof->fp;
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);
74 iof->fp = NULL;
75 iof->type = IOFILE_TYPE_FILE;
76 return iof;
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);
84 if (iof->fp == NULL)
85 luaL_argerror(L, 1, lj_str_pushf(L, "%s: %s", fname, strerror(errno)));
86 return iof;
89 static int io_file_close(lua_State *L, IOFileUD *iof)
91 int ok;
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) {
95 int stat = -1;
96 #if LJ_TARGET_POSIX
97 stat = pclose(iof->fp);
98 #elif LJ_TARGET_WINDOWS
99 stat = _pclose(iof->fp);
100 #else
101 lua_assert(0);
102 return 0;
103 #endif
104 #if LJ_52
105 iof->fp = NULL;
106 return luaL_execresult(L, stat);
107 #else
108 ok = (stat != -1);
109 #endif
110 } else {
111 lua_assert((iof->type & IOFILE_TYPE_MASK) == IOFILE_TYPE_STDF);
112 setnilV(L->top++);
113 lua_pushliteral(L, "cannot close standard file");
114 return 2;
116 iof->fp = NULL;
117 return luaL_fileresult(L, ok, NULL);
120 /* -- Read/write helpers -------------------------------------------------- */
122 static int io_file_readnum(lua_State *L, FILE *fp)
124 lua_Number d;
125 if (fscanf(fp, LUA_NUMBER_SCAN, &d) == 1) {
126 if (LJ_DUALNUM) {
127 int32_t i = lj_num2int(d);
128 if (d == (lua_Number)i && !tvismzero((cTValue *)&d)) {
129 setintV(L->top++, i);
130 return 1;
133 setnumV(L->top++, d);
134 return 1;
135 } else {
136 setnilV(L->top++);
137 return 0;
141 static int io_file_testeof(lua_State *L, FILE *fp)
143 int c = getc(fp);
144 ungetc(c, fp);
145 lua_pushlstring(L, NULL, 0);
146 return (c != EOF);
149 static int io_file_readline(lua_State *L, FILE *fp, size_t chop)
151 luaL_Buffer b;
152 luaL_buffinit(L, &b);
153 for (;;) {
154 size_t len;
155 char *p = luaL_prepbuffer(&b);
156 if (fgets(p, LUAL_BUFFERSIZE, fp) == NULL) { /* EOF? */
157 luaL_pushresult(&b);
158 return (strV(L->top-1)->len > 0); /* Anything read? */
160 len = strlen(p);
161 if (len == 0 || p[len-1] != '\n') { /* Partial line? */
162 luaL_addsize(&b, len);
163 } else {
164 luaL_addsize(&b, len - chop); /* Keep or remove EOL. */
165 luaL_pushresult(&b);
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 */
175 luaL_Buffer b;
176 luaL_buffinit(L, &b);
177 rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
178 do {
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;
192 clearerr(fp);
193 if (nargs == 0) {
194 ok = io_file_readline(L, fp, 1);
195 n = start+1; /* Return 1 result. */
196 } else {
197 /* The results plus the buffers go on top of the args. */
198 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
199 ok = 1;
200 for (n = start; nargs-- && ok; n++) {
201 if (tvisstr(L->base+n)) {
202 const char *p = strVdata(L->base+n);
203 if (p[0] != '*')
204 lj_err_arg(L, n+1, LJ_ERR_INVOPT);
205 if (p[1] == 'n')
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));
211 else
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);
216 } else {
217 lj_err_arg(L, n+1, LJ_ERR_INVOPT);
221 if (ferror(fp))
222 return luaL_fileresult(L, 0, NULL);
223 if (!ok)
224 setnilV(L->top-1); /* Replace last result with nil. */
225 return n - start;
228 static int io_file_write(lua_State *L, FILE *fp, int start)
230 cTValue *tv;
231 int status = 1;
232 for (tv = L->base+start; tv < L->top; tv++) {
233 if (tvisstr(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);
243 } else {
244 lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING);
247 return luaL_fileresult(L, status, NULL);
250 /* -- I/O file methods ---------------------------------------------------- */
252 #define LJLIB_MODULE_io_method
254 LJLIB_CF(io_method_close)
256 IOFileUD *iof = L->base < L->top ? io_tofile(L) :
257 IOSTDF_IOF(L, GCROOT_IO_OUTPUT);
258 return io_file_close(L, iof);
261 LJLIB_CF(io_method_read)
263 return io_file_read(L, io_tofile(L)->fp, 1);
266 LJLIB_CF(io_method_write) LJLIB_REC(io_write 0)
268 return io_file_write(L, io_tofile(L)->fp, 1);
271 LJLIB_CF(io_method_flush) LJLIB_REC(io_flush 0)
273 return luaL_fileresult(L, fflush(io_tofile(L)->fp) == 0, NULL);
276 LJLIB_CF(io_method_seek)
278 FILE *fp = io_tofile(L)->fp;
279 int opt = lj_lib_checkopt(L, 2, 1, "\3set\3cur\3end");
280 int64_t ofs = 0;
281 cTValue *o;
282 int res;
283 if (opt == 0) opt = SEEK_SET;
284 else if (opt == 1) opt = SEEK_CUR;
285 else if (opt == 2) opt = SEEK_END;
286 o = L->base+2;
287 if (o < L->top) {
288 if (tvisint(o))
289 ofs = (int64_t)intV(o);
290 else if (tvisnum(o))
291 ofs = (int64_t)numV(o);
292 else if (!tvisnil(o))
293 lj_err_argt(L, 3, LUA_TNUMBER);
295 #if LJ_TARGET_POSIX
296 res = fseeko(fp, ofs, opt);
297 #elif _MSC_VER >= 1400
298 res = _fseeki64(fp, ofs, opt);
299 #elif defined(__MINGW32__)
300 res = fseeko64(fp, ofs, opt);
301 #else
302 res = fseek(fp, (long)ofs, opt);
303 #endif
304 if (res)
305 return luaL_fileresult(L, 0, NULL);
306 #if LJ_TARGET_POSIX
307 ofs = ftello(fp);
308 #elif _MSC_VER >= 1400
309 ofs = _ftelli64(fp);
310 #elif defined(__MINGW32__)
311 ofs = ftello64(fp);
312 #else
313 ofs = (int64_t)ftell(fp);
314 #endif
315 setint64V(L->top-1, ofs);
316 return 1;
319 LJLIB_CF(io_method_setvbuf)
321 FILE *fp = io_tofile(L)->fp;
322 int opt = lj_lib_checkopt(L, 2, -1, "\4full\4line\2no");
323 size_t sz = (size_t)lj_lib_optint(L, 3, LUAL_BUFFERSIZE);
324 if (opt == 0) opt = _IOFBF;
325 else if (opt == 1) opt = _IOLBF;
326 else if (opt == 2) opt = _IONBF;
327 return luaL_fileresult(L, setvbuf(fp, NULL, opt, sz) == 0, NULL);
330 LJLIB_PUSH(top-2) /* io_lines_iter */
331 LJLIB_CF(io_method_lines)
333 io_tofile(L);
334 setfuncV(L, L->top, funcV(lj_lib_upvalue(L, 1)));
335 setudataV(L, L->top+1, udataV(L->base));
336 L->top += 2;
337 return 2;
340 LJLIB_CF(io_method___gc)
342 IOFileUD *iof = io_tofilep(L);
343 if (iof->fp != NULL && (iof->type & IOFILE_TYPE_MASK) != IOFILE_TYPE_STDF)
344 io_file_close(L, iof);
345 return 0;
348 LJLIB_CF(io_method___tostring)
350 IOFileUD *iof = io_tofilep(L);
351 if (iof->fp != NULL)
352 lua_pushfstring(L, "file (%p)", iof->fp);
353 else
354 lua_pushliteral(L, "file (closed)");
355 return 1;
358 LJLIB_PUSH(top-1) LJLIB_SET(__index)
360 #include "lj_libdef.h"
362 /* -- I/O library functions ----------------------------------------------- */
364 #define LJLIB_MODULE_io
366 LJLIB_PUSH(top-2) LJLIB_SET(!) /* Set environment. */
368 LJLIB_CF(io_open)
370 const char *fname = strdata(lj_lib_checkstr(L, 1));
371 GCstr *s = lj_lib_optstr(L, 2);
372 const char *mode = s ? strdata(s) : "r";
373 IOFileUD *iof = io_file_new(L);
374 iof->fp = fopen(fname, mode);
375 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
378 LJLIB_CF(io_popen)
380 #if LJ_TARGET_POSIX || LJ_TARGET_WINDOWS
381 const char *fname = strdata(lj_lib_checkstr(L, 1));
382 GCstr *s = lj_lib_optstr(L, 2);
383 const char *mode = s ? strdata(s) : "r";
384 IOFileUD *iof = io_file_new(L);
385 iof->type = IOFILE_TYPE_PIPE;
386 #if LJ_TARGET_POSIX
387 fflush(NULL);
388 iof->fp = popen(fname, mode);
389 #else
390 iof->fp = _popen(fname, mode);
391 #endif
392 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, fname);
393 #else
394 return luaL_error(L, LUA_QL("popen") " not supported");
395 #endif
398 LJLIB_CF(io_tmpfile)
400 IOFileUD *iof = io_file_new(L);
401 #if LJ_TARGET_PS3
402 iof->fp = NULL; errno = ENOSYS;
403 #else
404 iof->fp = tmpfile();
405 #endif
406 return iof->fp != NULL ? 1 : luaL_fileresult(L, 0, NULL);
409 LJLIB_CF(io_close)
411 return lj_cf_io_method_close(L);
414 LJLIB_CF(io_read)
416 return io_file_read(L, io_stdfile(L, GCROOT_IO_INPUT), 0);
419 LJLIB_CF(io_write) LJLIB_REC(io_write GCROOT_IO_OUTPUT)
421 return io_file_write(L, io_stdfile(L, GCROOT_IO_OUTPUT), 0);
424 LJLIB_CF(io_flush) LJLIB_REC(io_flush GCROOT_IO_OUTPUT)
426 return luaL_fileresult(L, fflush(io_stdfile(L, GCROOT_IO_OUTPUT)) == 0, NULL);
429 static int io_std_getset(lua_State *L, ptrdiff_t id, const char *mode)
431 if (L->base < L->top && !tvisnil(L->base)) {
432 if (tvisudata(L->base)) {
433 io_tofile(L);
434 L->top = L->base+1;
435 } else {
436 io_file_open(L, mode);
438 /* NOBARRIER: The standard I/O handles are GC roots. */
439 setgcref(G(L)->gcroot[id], gcV(L->top-1));
440 } else {
441 setudataV(L, L->top++, IOSTDF_UD(L, id));
443 return 1;
446 LJLIB_CF(io_input)
448 return io_std_getset(L, GCROOT_IO_INPUT, "r");
451 LJLIB_CF(io_output)
453 return io_std_getset(L, GCROOT_IO_OUTPUT, "w");
456 LJLIB_NOREG LJLIB_CF(io_lines_iter)
458 IOFileUD *iof = io_tofile(L);
459 int ok = io_file_readline(L, iof->fp, 1);
460 if (ferror(iof->fp))
461 lj_err_callermsg(L, strerror(errno));
462 if (!ok && (iof->type & IOFILE_FLAG_CLOSE))
463 io_file_close(L, iof); /* Return values are ignored (ok is 0). */
464 return ok;
467 LJLIB_PUSH(top-3) /* io_lines_iter */
468 LJLIB_CF(io_lines)
470 if (L->base < L->top && !tvisnil(L->base)) { /* io.lines(fname) */
471 IOFileUD *iof = io_file_open(L, "r");
472 iof->type = IOFILE_TYPE_FILE|IOFILE_FLAG_CLOSE;
473 setfuncV(L, L->top-2, funcV(lj_lib_upvalue(L, 1)));
474 } else { /* io.lines() iterates over stdin. */
475 setfuncV(L, L->top, funcV(lj_lib_upvalue(L, 1)));
476 setudataV(L, L->top+1, IOSTDF_UD(L, GCROOT_IO_INPUT));
477 L->top += 2;
479 return 2;
482 LJLIB_CF(io_type)
484 cTValue *o = lj_lib_checkany(L, 1);
485 if (!(tvisudata(o) && udataV(o)->udtype == UDTYPE_IO_FILE))
486 setnilV(L->top++);
487 else if (((IOFileUD *)uddata(udataV(o)))->fp != NULL)
488 lua_pushliteral(L, "file");
489 else
490 lua_pushliteral(L, "closed file");
491 return 1;
494 #include "lj_libdef.h"
496 /* ------------------------------------------------------------------------ */
498 static GCobj *io_std_new(lua_State *L, FILE *fp, const char *name)
500 IOFileUD *iof = (IOFileUD *)lua_newuserdata(L, sizeof(IOFileUD));
501 GCudata *ud = udataV(L->top-1);
502 ud->udtype = UDTYPE_IO_FILE;
503 /* NOBARRIER: The GCudata is new (marked white). */
504 setgcref(ud->metatable, gcV(L->top-3));
505 iof->fp = fp;
506 iof->type = IOFILE_TYPE_STDF;
507 lua_setfield(L, -2, name);
508 return obj2gco(ud);
511 LUALIB_API int luaopen_io(lua_State *L)
513 lj_lib_pushcf(L, lj_cf_io_lines_iter, FF_io_lines_iter);
514 LJ_LIB_REG(L, NULL, io_method);
515 copyTV(L, L->top, L->top-1); L->top++;
516 lua_setfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
517 LJ_LIB_REG(L, LUA_IOLIBNAME, io);
518 setgcref(G(L)->gcroot[GCROOT_IO_INPUT], io_std_new(L, stdin, "stdin"));
519 setgcref(G(L)->gcroot[GCROOT_IO_OUTPUT], io_std_new(L, stdout, "stdout"));
520 io_std_new(L, stderr, "stderr");
521 return 1;