liolib.c 16 KB

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