liolib.c 15 KB

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