liolib.c 15 KB

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