liolib.c 16 KB

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