/lua/liolib.c

https://bitbucket.org/cesbo/astra · C · 666 lines · 470 code · 137 blank · 59 comment · 91 complexity · ce131ca289d111022f816486a34671f2 MD5 · raw file

  1. /*
  2. ** $Id: liolib.c,v 2.112.1.1 2013/04/12 18:48:47 roberto Exp $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. /*
  7. ** This definition must come before the inclusion of 'stdio.h'; it
  8. ** should not affect non-POSIX systems
  9. */
  10. #if !defined(_FILE_OFFSET_BITS)
  11. #define _LARGEFILE_SOURCE 1
  12. #define _FILE_OFFSET_BITS 64
  13. #endif
  14. #include <errno.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #define liolib_c
  19. #define LUA_LIB
  20. #include "lua.h"
  21. #include "lauxlib.h"
  22. #include "lualib.h"
  23. #if !defined(lua_checkmode)
  24. /*
  25. ** Check whether 'mode' matches '[rwa]%+?b?'.
  26. ** Change this macro to accept other modes for 'fopen' besides
  27. ** the standard ones.
  28. */
  29. #define lua_checkmode(mode) \
  30. (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
  31. (*mode != '+' || ++mode) && /* skip if char is '+' */ \
  32. (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
  33. (*mode == '\0'))
  34. #endif
  35. /*
  36. ** {======================================================
  37. ** lua_popen spawns a new process connected to the current
  38. ** one through the file streams.
  39. ** =======================================================
  40. */
  41. #if !defined(lua_popen) /* { */
  42. #if defined(LUA_USE_POPEN) /* { */
  43. #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
  44. #define lua_pclose(L,file) ((void)L, pclose(file))
  45. #elif defined(LUA_WIN) /* }{ */
  46. #define lua_popen(L,c,m) ((void)L, _popen(c,m))
  47. #define lua_pclose(L,file) ((void)L, _pclose(file))
  48. #else /* }{ */
  49. #define lua_popen(L,c,m) ((void)((void)c, m), \
  50. luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
  51. #define lua_pclose(L,file) ((void)((void)L, file), -1)
  52. #endif /* } */
  53. #endif /* } */
  54. /* }====================================================== */
  55. /*
  56. ** {======================================================
  57. ** lua_fseek: configuration for longer offsets
  58. ** =======================================================
  59. */
  60. #if !defined(lua_fseek) && !defined(LUA_ANSI) /* { */
  61. #if defined(LUA_USE_POSIX) /* { */
  62. #define l_fseek(f,o,w) fseeko(f,o,w)
  63. #define l_ftell(f) ftello(f)
  64. #define l_seeknum off_t
  65. #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
  66. && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
  67. /* Windows (but not DDK) and Visual C++ 2005 or higher */
  68. #define l_fseek(f,o,w) _fseeki64(f,o,w)
  69. #define l_ftell(f) _ftelli64(f)
  70. #define l_seeknum __int64
  71. #endif /* } */
  72. #endif /* } */
  73. #if !defined(l_fseek) /* default definitions */
  74. #define l_fseek(f,o,w) fseek(f,o,w)
  75. #define l_ftell(f) ftell(f)
  76. #define l_seeknum long
  77. #endif
  78. /* }====================================================== */
  79. #define IO_PREFIX "_IO_"
  80. #define IO_INPUT (IO_PREFIX "input")
  81. #define IO_OUTPUT (IO_PREFIX "output")
  82. typedef luaL_Stream LStream;
  83. #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
  84. #define isclosed(p) ((p)->closef == NULL)
  85. static int io_type (lua_State *L) {
  86. LStream *p;
  87. luaL_checkany(L, 1);
  88. p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
  89. if (p == NULL)
  90. lua_pushnil(L); /* not a file */
  91. else if (isclosed(p))
  92. lua_pushliteral(L, "closed file");
  93. else
  94. lua_pushliteral(L, "file");
  95. return 1;
  96. }
  97. static int f_tostring (lua_State *L) {
  98. LStream *p = tolstream(L);
  99. if (isclosed(p))
  100. lua_pushliteral(L, "file (closed)");
  101. else
  102. lua_pushfstring(L, "file (%p)", p->f);
  103. return 1;
  104. }
  105. static FILE *tofile (lua_State *L) {
  106. LStream *p = tolstream(L);
  107. if (isclosed(p))
  108. luaL_error(L, "attempt to use a closed file");
  109. lua_assert(p->f);
  110. return p->f;
  111. }
  112. /*
  113. ** When creating file handles, always creates a `closed' file handle
  114. ** before opening the actual file; so, if there is a memory error, the
  115. ** file is not left opened.
  116. */
  117. static LStream *newprefile (lua_State *L) {
  118. LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
  119. p->closef = NULL; /* mark file handle as 'closed' */
  120. luaL_setmetatable(L, LUA_FILEHANDLE);
  121. return p;
  122. }
  123. static int aux_close (lua_State *L) {
  124. LStream *p = tolstream(L);
  125. lua_CFunction cf = p->closef;
  126. p->closef = NULL; /* mark stream as closed */
  127. return (*cf)(L); /* close it */
  128. }
  129. static int io_close (lua_State *L) {
  130. if (lua_isnone(L, 1)) /* no argument? */
  131. lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
  132. tofile(L); /* make sure argument is an open stream */
  133. return aux_close(L);
  134. }
  135. static int f_gc (lua_State *L) {
  136. LStream *p = tolstream(L);
  137. if (!isclosed(p) && p->f != NULL)
  138. aux_close(L); /* ignore closed and incompletely open files */
  139. return 0;
  140. }
  141. /*
  142. ** function to close regular files
  143. */
  144. static int io_fclose (lua_State *L) {
  145. LStream *p = tolstream(L);
  146. int res = fclose(p->f);
  147. return luaL_fileresult(L, (res == 0), NULL);
  148. }
  149. static LStream *newfile (lua_State *L) {
  150. LStream *p = newprefile(L);
  151. p->f = NULL;
  152. p->closef = &io_fclose;
  153. return p;
  154. }
  155. static void opencheck (lua_State *L, const char *fname, const char *mode) {
  156. LStream *p = newfile(L);
  157. p->f = fopen(fname, mode);
  158. if (p->f == NULL)
  159. luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
  160. }
  161. static int io_open (lua_State *L) {
  162. const char *filename = luaL_checkstring(L, 1);
  163. const char *mode = luaL_optstring(L, 2, "r");
  164. LStream *p = newfile(L);
  165. const char *md = mode; /* to traverse/check mode */
  166. luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
  167. p->f = fopen(filename, mode);
  168. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  169. }
  170. /*
  171. ** function to close 'popen' files
  172. */
  173. static int io_pclose (lua_State *L) {
  174. LStream *p = tolstream(L);
  175. return luaL_execresult(L, lua_pclose(L, p->f));
  176. }
  177. static int io_popen (lua_State *L) {
  178. const char *filename = luaL_checkstring(L, 1);
  179. const char *mode = luaL_optstring(L, 2, "r");
  180. LStream *p = newprefile(L);
  181. p->f = lua_popen(L, filename, mode);
  182. p->closef = &io_pclose;
  183. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  184. }
  185. static int io_tmpfile (lua_State *L) {
  186. LStream *p = newfile(L);
  187. p->f = tmpfile();
  188. return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
  189. }
  190. static FILE *getiofile (lua_State *L, const char *findex) {
  191. LStream *p;
  192. lua_getfield(L, LUA_REGISTRYINDEX, findex);
  193. p = (LStream *)lua_touserdata(L, -1);
  194. if (isclosed(p))
  195. luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
  196. return p->f;
  197. }
  198. static int g_iofile (lua_State *L, const char *f, const char *mode) {
  199. if (!lua_isnoneornil(L, 1)) {
  200. const char *filename = lua_tostring(L, 1);
  201. if (filename)
  202. opencheck(L, filename, mode);
  203. else {
  204. tofile(L); /* check that it's a valid file handle */
  205. lua_pushvalue(L, 1);
  206. }
  207. lua_setfield(L, LUA_REGISTRYINDEX, f);
  208. }
  209. /* return current value */
  210. lua_getfield(L, LUA_REGISTRYINDEX, f);
  211. return 1;
  212. }
  213. static int io_input (lua_State *L) {
  214. return g_iofile(L, IO_INPUT, "r");
  215. }
  216. static int io_output (lua_State *L) {
  217. return g_iofile(L, IO_OUTPUT, "w");
  218. }
  219. static int io_readline (lua_State *L);
  220. static void aux_lines (lua_State *L, int toclose) {
  221. int i;
  222. int n = lua_gettop(L) - 1; /* number of arguments to read */
  223. /* ensure that arguments will fit here and into 'io_readline' stack */
  224. luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
  225. lua_pushvalue(L, 1); /* file handle */
  226. lua_pushinteger(L, n); /* number of arguments to read */
  227. lua_pushboolean(L, toclose); /* close/not close file when finished */
  228. for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */
  229. lua_pushcclosure(L, io_readline, 3 + n);
  230. }
  231. static int f_lines (lua_State *L) {
  232. tofile(L); /* check that it's a valid file handle */
  233. aux_lines(L, 0);
  234. return 1;
  235. }
  236. static int io_lines (lua_State *L) {
  237. int toclose;
  238. if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
  239. if (lua_isnil(L, 1)) { /* no file name? */
  240. lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
  241. lua_replace(L, 1); /* put it at index 1 */
  242. tofile(L); /* check that it's a valid file handle */
  243. toclose = 0; /* do not close it after iteration */
  244. }
  245. else { /* open a new file */
  246. const char *filename = luaL_checkstring(L, 1);
  247. opencheck(L, filename, "r");
  248. lua_replace(L, 1); /* put file at index 1 */
  249. toclose = 1; /* close it after iteration */
  250. }
  251. aux_lines(L, toclose);
  252. return 1;
  253. }
  254. /*
  255. ** {======================================================
  256. ** READ
  257. ** =======================================================
  258. */
  259. static int read_number (lua_State *L, FILE *f) {
  260. lua_Number d;
  261. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  262. lua_pushnumber(L, d);
  263. return 1;
  264. }
  265. else {
  266. lua_pushnil(L); /* "result" to be removed */
  267. return 0; /* read fails */
  268. }
  269. }
  270. static int test_eof (lua_State *L, FILE *f) {
  271. int c = getc(f);
  272. ungetc(c, f);
  273. lua_pushlstring(L, NULL, 0);
  274. return (c != EOF);
  275. }
  276. static int read_line (lua_State *L, FILE *f, int chop) {
  277. luaL_Buffer b;
  278. luaL_buffinit(L, &b);
  279. for (;;) {
  280. size_t l;
  281. char *p = luaL_prepbuffer(&b);
  282. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  283. luaL_pushresult(&b); /* close buffer */
  284. return (lua_rawlen(L, -1) > 0); /* check whether read something */
  285. }
  286. l = strlen(p);
  287. if (l == 0 || p[l-1] != '\n')
  288. luaL_addsize(&b, l);
  289. else {
  290. luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
  291. luaL_pushresult(&b); /* close buffer */
  292. return 1; /* read at least an `eol' */
  293. }
  294. }
  295. }
  296. #define MAX_SIZE_T (~(size_t)0)
  297. static void read_all (lua_State *L, FILE *f) {
  298. size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */
  299. luaL_Buffer b;
  300. luaL_buffinit(L, &b);
  301. for (;;) {
  302. char *p = luaL_prepbuffsize(&b, rlen);
  303. size_t nr = fread(p, sizeof(char), rlen, f);
  304. luaL_addsize(&b, nr);
  305. if (nr < rlen) break; /* eof? */
  306. else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */
  307. rlen *= 2; /* double buffer size at each iteration */
  308. }
  309. luaL_pushresult(&b); /* close buffer */
  310. }
  311. static int read_chars (lua_State *L, FILE *f, size_t n) {
  312. size_t nr; /* number of chars actually read */
  313. char *p;
  314. luaL_Buffer b;
  315. luaL_buffinit(L, &b);
  316. p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
  317. nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
  318. luaL_addsize(&b, nr);
  319. luaL_pushresult(&b); /* close buffer */
  320. return (nr > 0); /* true iff read something */
  321. }
  322. static int g_read (lua_State *L, FILE *f, int first) {
  323. int nargs = lua_gettop(L) - 1;
  324. int success;
  325. int n;
  326. clearerr(f);
  327. if (nargs == 0) { /* no arguments? */
  328. success = read_line(L, f, 1);
  329. n = first+1; /* to return 1 result */
  330. }
  331. else { /* ensure stack space for all results and for auxlib's buffer */
  332. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  333. success = 1;
  334. for (n = first; nargs-- && success; n++) {
  335. if (lua_type(L, n) == LUA_TNUMBER) {
  336. size_t l = (size_t)lua_tointeger(L, n);
  337. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  338. }
  339. else {
  340. const char *p = lua_tostring(L, n);
  341. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  342. switch (p[1]) {
  343. case 'n': /* number */
  344. success = read_number(L, f);
  345. break;
  346. case 'l': /* line */
  347. success = read_line(L, f, 1);
  348. break;
  349. case 'L': /* line with end-of-line */
  350. success = read_line(L, f, 0);
  351. break;
  352. case 'a': /* file */
  353. read_all(L, f); /* read entire file */
  354. success = 1; /* always success */
  355. break;
  356. default:
  357. return luaL_argerror(L, n, "invalid format");
  358. }
  359. }
  360. }
  361. }
  362. if (ferror(f))
  363. return luaL_fileresult(L, 0, NULL);
  364. if (!success) {
  365. lua_pop(L, 1); /* remove last result */
  366. lua_pushnil(L); /* push nil instead */
  367. }
  368. return n - first;
  369. }
  370. static int io_read (lua_State *L) {
  371. return g_read(L, getiofile(L, IO_INPUT), 1);
  372. }
  373. static int f_read (lua_State *L) {
  374. return g_read(L, tofile(L), 2);
  375. }
  376. static int io_readline (lua_State *L) {
  377. LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
  378. int i;
  379. int n = (int)lua_tointeger(L, lua_upvalueindex(2));
  380. if (isclosed(p)) /* file is already closed? */
  381. return luaL_error(L, "file is already closed");
  382. lua_settop(L , 1);
  383. for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
  384. lua_pushvalue(L, lua_upvalueindex(3 + i));
  385. n = g_read(L, p->f, 2); /* 'n' is number of results */
  386. lua_assert(n > 0); /* should return at least a nil */
  387. if (!lua_isnil(L, -n)) /* read at least one value? */
  388. return n; /* return them */
  389. else { /* first result is nil: EOF or error */
  390. if (n > 1) { /* is there error information? */
  391. /* 2nd result is error message */
  392. return luaL_error(L, "%s", lua_tostring(L, -n + 1));
  393. }
  394. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  395. lua_settop(L, 0);
  396. lua_pushvalue(L, lua_upvalueindex(1));
  397. aux_close(L); /* close it */
  398. }
  399. return 0;
  400. }
  401. }
  402. /* }====================================================== */
  403. static int g_write (lua_State *L, FILE *f, int arg) {
  404. int nargs = lua_gettop(L) - arg;
  405. int status = 1;
  406. for (; nargs--; arg++) {
  407. if (lua_type(L, arg) == LUA_TNUMBER) {
  408. /* optimization: could be done exactly as for strings */
  409. status = status &&
  410. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  411. }
  412. else {
  413. size_t l;
  414. const char *s = luaL_checklstring(L, arg, &l);
  415. status = status && (fwrite(s, sizeof(char), l, f) == l);
  416. }
  417. }
  418. if (status) return 1; /* file handle already on stack top */
  419. else return luaL_fileresult(L, status, NULL);
  420. }
  421. static int io_write (lua_State *L) {
  422. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  423. }
  424. static int f_write (lua_State *L) {
  425. FILE *f = tofile(L);
  426. lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
  427. return g_write(L, f, 2);
  428. }
  429. static int f_seek (lua_State *L) {
  430. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  431. static const char *const modenames[] = {"set", "cur", "end", NULL};
  432. FILE *f = tofile(L);
  433. int op = luaL_checkoption(L, 2, "cur", modenames);
  434. lua_Number p3 = luaL_optnumber(L, 3, 0);
  435. l_seeknum offset = (l_seeknum)p3;
  436. luaL_argcheck(L, (lua_Number)offset == p3, 3,
  437. "not an integer in proper range");
  438. op = l_fseek(f, offset, mode[op]);
  439. if (op)
  440. return luaL_fileresult(L, 0, NULL); /* error */
  441. else {
  442. lua_pushnumber(L, (lua_Number)l_ftell(f));
  443. return 1;
  444. }
  445. }
  446. static int f_setvbuf (lua_State *L) {
  447. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  448. static const char *const modenames[] = {"no", "full", "line", NULL};
  449. FILE *f = tofile(L);
  450. int op = luaL_checkoption(L, 2, NULL, modenames);
  451. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  452. int res = setvbuf(f, NULL, mode[op], sz);
  453. return luaL_fileresult(L, res == 0, NULL);
  454. }
  455. static int io_flush (lua_State *L) {
  456. return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  457. }
  458. static int f_flush (lua_State *L) {
  459. return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
  460. }
  461. /*
  462. ** functions for 'io' library
  463. */
  464. static const luaL_Reg iolib[] = {
  465. {"close", io_close},
  466. {"flush", io_flush},
  467. {"input", io_input},
  468. {"lines", io_lines},
  469. {"open", io_open},
  470. {"output", io_output},
  471. {"popen", io_popen},
  472. {"read", io_read},
  473. {"tmpfile", io_tmpfile},
  474. {"type", io_type},
  475. {"write", io_write},
  476. {NULL, NULL}
  477. };
  478. /*
  479. ** methods for file handles
  480. */
  481. static const luaL_Reg flib[] = {
  482. {"close", io_close},
  483. {"flush", f_flush},
  484. {"lines", f_lines},
  485. {"read", f_read},
  486. {"seek", f_seek},
  487. {"setvbuf", f_setvbuf},
  488. {"write", f_write},
  489. {"__gc", f_gc},
  490. {"__tostring", f_tostring},
  491. {NULL, NULL}
  492. };
  493. static void createmeta (lua_State *L) {
  494. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  495. lua_pushvalue(L, -1); /* push metatable */
  496. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  497. luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
  498. lua_pop(L, 1); /* pop new metatable */
  499. }
  500. /*
  501. ** function to (not) close the standard files stdin, stdout, and stderr
  502. */
  503. static int io_noclose (lua_State *L) {
  504. LStream *p = tolstream(L);
  505. p->closef = &io_noclose; /* keep file opened */
  506. lua_pushnil(L);
  507. lua_pushliteral(L, "cannot close standard file");
  508. return 2;
  509. }
  510. static void createstdfile (lua_State *L, FILE *f, const char *k,
  511. const char *fname) {
  512. LStream *p = newprefile(L);
  513. p->f = f;
  514. p->closef = &io_noclose;
  515. if (k != NULL) {
  516. lua_pushvalue(L, -1);
  517. lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
  518. }
  519. lua_setfield(L, -2, fname); /* add file to module */
  520. }
  521. LUAMOD_API int luaopen_io (lua_State *L) {
  522. luaL_newlib(L, iolib); /* new module */
  523. createmeta(L);
  524. /* create (and set) default files */
  525. createstdfile(L, stdin, IO_INPUT, "stdin");
  526. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  527. createstdfile(L, stderr, NULL, "stderr");
  528. return 1;
  529. }