2
0

liolib.c 16 KB

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