liolib.c 14 KB

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