liolib.c 15 KB

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