liolib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. ** $Id: liolib.c,v 2.79 2008/02/12 17:05:36 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 = newfile(L);
  130. *pf = fopen(filename, mode);
  131. return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
  132. }
  133. /*
  134. ** this function has a separated environment, which defines the
  135. ** correct __close for 'popen' files
  136. */
  137. static int io_popen (lua_State *L) {
  138. const char *filename = luaL_checkstring(L, 1);
  139. const char *mode = luaL_optstring(L, 2, "r");
  140. FILE **pf = newfile(L);
  141. *pf = lua_popen(L, filename, mode);
  142. return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
  143. }
  144. static int io_tmpfile (lua_State *L) {
  145. FILE **pf = newfile(L);
  146. *pf = tmpfile();
  147. return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
  148. }
  149. static FILE *getiofile (lua_State *L, int findex) {
  150. FILE *f;
  151. lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
  152. f = *(FILE **)lua_touserdata(L, -1);
  153. if (f == NULL)
  154. luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
  155. return f;
  156. }
  157. static int g_iofile (lua_State *L, int f, const char *mode) {
  158. if (!lua_isnoneornil(L, 1)) {
  159. const char *filename = lua_tostring(L, 1);
  160. if (filename) {
  161. FILE **pf = newfile(L);
  162. *pf = fopen(filename, mode);
  163. if (*pf == NULL)
  164. fileerror(L, 1, filename);
  165. }
  166. else {
  167. tofile(L); /* check that it's a valid file handle */
  168. lua_pushvalue(L, 1);
  169. }
  170. lua_rawseti(L, LUA_ENVIRONINDEX, f);
  171. }
  172. /* return current value */
  173. lua_rawgeti(L, LUA_ENVIRONINDEX, f);
  174. return 1;
  175. }
  176. static int io_input (lua_State *L) {
  177. return g_iofile(L, IO_INPUT, "r");
  178. }
  179. static int io_output (lua_State *L) {
  180. return g_iofile(L, IO_OUTPUT, "w");
  181. }
  182. static int io_readline (lua_State *L);
  183. static void aux_lines (lua_State *L, int idx, int toclose) {
  184. lua_pushvalue(L, idx);
  185. lua_pushboolean(L, toclose); /* close/not close file when finished */
  186. lua_pushcclosure(L, io_readline, 2);
  187. }
  188. static int f_lines (lua_State *L) {
  189. tofile(L); /* check that it's a valid file handle */
  190. aux_lines(L, 1, 0);
  191. return 1;
  192. }
  193. static int io_lines (lua_State *L) {
  194. if (lua_isnoneornil(L, 1)) { /* no arguments? */
  195. /* will iterate over default input */
  196. lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
  197. return f_lines(L);
  198. }
  199. else {
  200. const char *filename = luaL_checkstring(L, 1);
  201. FILE **pf = newfile(L);
  202. *pf = fopen(filename, "r");
  203. if (*pf == NULL)
  204. fileerror(L, 1, filename);
  205. aux_lines(L, lua_gettop(L), 1);
  206. return 1;
  207. }
  208. }
  209. /*
  210. ** {======================================================
  211. ** READ
  212. ** =======================================================
  213. */
  214. static int read_number (lua_State *L, FILE *f) {
  215. lua_Number d;
  216. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  217. lua_pushnumber(L, d);
  218. return 1;
  219. }
  220. else return 0; /* read fails */
  221. }
  222. static int test_eof (lua_State *L, FILE *f) {
  223. int c = getc(f);
  224. ungetc(c, f);
  225. lua_pushlstring(L, NULL, 0);
  226. return (c != EOF);
  227. }
  228. static int read_line (lua_State *L, FILE *f) {
  229. luaL_Buffer b;
  230. luaL_buffinit(L, &b);
  231. for (;;) {
  232. size_t l;
  233. char *p = luaL_prepbuffer(&b);
  234. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  235. luaL_pushresult(&b); /* close buffer */
  236. return (lua_objlen(L, -1) > 0); /* check whether read something */
  237. }
  238. l = strlen(p);
  239. if (l == 0 || p[l-1] != '\n')
  240. luaL_addsize(&b, l);
  241. else {
  242. luaL_addsize(&b, l - 1); /* do not include `eol' */
  243. luaL_pushresult(&b); /* close buffer */
  244. return 1; /* read at least an `eol' */
  245. }
  246. }
  247. }
  248. static int read_chars (lua_State *L, FILE *f, size_t n) {
  249. size_t tbr = n; /* number of chars to be read */
  250. size_t rlen; /* how much to read in each cycle */
  251. size_t nr; /* number of chars actually read in each cycle */
  252. luaL_Buffer b;
  253. luaL_buffinit(L, &b);
  254. rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
  255. do {
  256. char *p = luaL_prepbuffer(&b);
  257. if (rlen > tbr) rlen = tbr; /* cannot read more than asked */
  258. nr = fread(p, sizeof(char), rlen, f);
  259. luaL_addsize(&b, nr);
  260. tbr -= nr; /* still have to read 'tbr' chars */
  261. } while (tbr > 0 && nr == rlen); /* until end of count or eof */
  262. luaL_pushresult(&b); /* close buffer */
  263. return (tbr < n); /* true iff read something */
  264. }
  265. static int g_read (lua_State *L, FILE *f, int first) {
  266. int nargs = lua_gettop(L) - 1;
  267. int success;
  268. int n;
  269. clearerr(f);
  270. if (nargs == 0) { /* no arguments? */
  271. success = read_line(L, f);
  272. n = first+1; /* to return 1 result */
  273. }
  274. else { /* ensure stack space for all results and for auxlib's buffer */
  275. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  276. success = 1;
  277. for (n = first; nargs-- && success; n++) {
  278. if (lua_type(L, n) == LUA_TNUMBER) {
  279. size_t l = (size_t)lua_tointeger(L, n);
  280. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  281. }
  282. else {
  283. const char *p = lua_tostring(L, n);
  284. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  285. switch (p[1]) {
  286. case 'n': /* number */
  287. success = read_number(L, f);
  288. break;
  289. case 'l': /* line */
  290. success = read_line(L, f);
  291. break;
  292. case 'a': /* file */
  293. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  294. success = 1; /* always success */
  295. break;
  296. default:
  297. return luaL_argerror(L, n, "invalid format");
  298. }
  299. }
  300. }
  301. }
  302. if (ferror(f))
  303. return pushresult(L, 0, NULL);
  304. if (!success) {
  305. lua_pop(L, 1); /* remove last result */
  306. lua_pushnil(L); /* push nil instead */
  307. }
  308. return n - first;
  309. }
  310. static int io_read (lua_State *L) {
  311. return g_read(L, getiofile(L, IO_INPUT), 1);
  312. }
  313. static int f_read (lua_State *L) {
  314. return g_read(L, tofile(L), 2);
  315. }
  316. static int io_readline (lua_State *L) {
  317. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
  318. int success;
  319. if (f == NULL) /* file is already closed? */
  320. luaL_error(L, "file is already closed");
  321. success = read_line(L, f);
  322. if (ferror(f))
  323. return luaL_error(L, "%s", strerror(errno));
  324. if (success) return 1;
  325. else { /* EOF */
  326. if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
  327. lua_settop(L, 0);
  328. lua_pushvalue(L, lua_upvalueindex(1));
  329. aux_close(L); /* close it */
  330. }
  331. return 0;
  332. }
  333. }
  334. /* }====================================================== */
  335. static int g_write (lua_State *L, FILE *f, int arg) {
  336. int nargs = lua_gettop(L) - 1;
  337. int status = 1;
  338. for (; nargs--; arg++) {
  339. if (lua_type(L, arg) == LUA_TNUMBER) {
  340. /* optimization: could be done exactly as for strings */
  341. status = status &&
  342. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  343. }
  344. else {
  345. size_t l;
  346. const char *s = luaL_checklstring(L, arg, &l);
  347. status = status && (fwrite(s, sizeof(char), l, f) == l);
  348. }
  349. }
  350. return pushresult(L, status, NULL);
  351. }
  352. static int io_write (lua_State *L) {
  353. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  354. }
  355. static int f_write (lua_State *L) {
  356. return g_write(L, tofile(L), 2);
  357. }
  358. static int f_seek (lua_State *L) {
  359. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  360. static const char *const modenames[] = {"set", "cur", "end", NULL};
  361. FILE *f = tofile(L);
  362. int op = luaL_checkoption(L, 2, "cur", modenames);
  363. long offset = luaL_optlong(L, 3, 0);
  364. op = fseek(f, offset, mode[op]);
  365. if (op)
  366. return pushresult(L, 0, NULL); /* error */
  367. else {
  368. lua_pushinteger(L, ftell(f));
  369. return 1;
  370. }
  371. }
  372. static int f_setvbuf (lua_State *L) {
  373. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  374. static const char *const modenames[] = {"no", "full", "line", NULL};
  375. FILE *f = tofile(L);
  376. int op = luaL_checkoption(L, 2, NULL, modenames);
  377. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  378. int res = setvbuf(f, NULL, mode[op], sz);
  379. return pushresult(L, res == 0, NULL);
  380. }
  381. static int io_flush (lua_State *L) {
  382. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  383. }
  384. static int f_flush (lua_State *L) {
  385. return pushresult(L, fflush(tofile(L)) == 0, NULL);
  386. }
  387. static const luaL_Reg iolib[] = {
  388. {"close", io_close},
  389. {"flush", io_flush},
  390. {"input", io_input},
  391. {"lines", io_lines},
  392. {"open", io_open},
  393. {"output", io_output},
  394. {"popen", io_popen},
  395. {"read", io_read},
  396. {"tmpfile", io_tmpfile},
  397. {"type", io_type},
  398. {"write", io_write},
  399. {NULL, NULL}
  400. };
  401. static const luaL_Reg flib[] = {
  402. {"close", io_close},
  403. {"flush", f_flush},
  404. {"lines", f_lines},
  405. {"read", f_read},
  406. {"seek", f_seek},
  407. {"setvbuf", f_setvbuf},
  408. {"write", f_write},
  409. {"__gc", io_gc},
  410. {"__tostring", io_tostring},
  411. {NULL, NULL}
  412. };
  413. static void createmeta (lua_State *L) {
  414. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  415. lua_pushvalue(L, -1); /* push metatable */
  416. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  417. luaL_register(L, NULL, flib); /* file methods */
  418. }
  419. static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
  420. *newfile(L) = f;
  421. if (k > 0) {
  422. lua_pushvalue(L, -1);
  423. lua_rawseti(L, LUA_ENVIRONINDEX, k);
  424. }
  425. lua_pushvalue(L, -2); /* copy environment */
  426. lua_setfenv(L, -2); /* set it */
  427. lua_setfield(L, -3, fname);
  428. }
  429. static void newfenv (lua_State *L, lua_CFunction cls) {
  430. lua_createtable(L, 0, 1);
  431. lua_pushcfunction(L, cls);
  432. lua_setfield(L, -2, "__close");
  433. }
  434. LUALIB_API int luaopen_io (lua_State *L) {
  435. createmeta(L);
  436. /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
  437. newfenv(L, io_fclose);
  438. lua_replace(L, LUA_ENVIRONINDEX);
  439. /* open library */
  440. luaL_register(L, LUA_IOLIBNAME, iolib);
  441. /* create (and set) default files */
  442. newfenv(L, io_noclose); /* close function for default files */
  443. createstdfile(L, stdin, IO_INPUT, "stdin");
  444. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  445. createstdfile(L, stderr, 0, "stderr");
  446. lua_pop(L, 1); /* pop environment for default files */
  447. lua_getfield(L, -1, "popen");
  448. newfenv(L, io_pclose); /* create environment for 'popen' */
  449. lua_setfenv(L, -2); /* set fenv for 'popen' */
  450. lua_pop(L, 1); /* pop 'popen' */
  451. return 1;
  452. }