You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

661 lines
17 KiB

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