liolib.c 13 KB

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