liolib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /*
  2. ** $Id: liolib.c,v 2.73.1.3 2008/01/18 17:47:43 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 return 0; /* read fails */
  217. }
  218. static int test_eof (lua_State *L, FILE *f) {
  219. int c = getc(f);
  220. ungetc(c, f);
  221. lua_pushlstring(L, NULL, 0);
  222. return (c != EOF);
  223. }
  224. static int read_line (lua_State *L, FILE *f) {
  225. luaL_Buffer b;
  226. luaL_buffinit(L, &b);
  227. for (;;) {
  228. size_t l;
  229. char *p = luaL_prepbuffer(&b);
  230. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  231. luaL_pushresult(&b); /* close buffer */
  232. return (lua_objlen(L, -1) > 0); /* check whether read something */
  233. }
  234. l = strlen(p);
  235. if (l == 0 || p[l-1] != '\n')
  236. luaL_addsize(&b, l);
  237. else {
  238. luaL_addsize(&b, l - 1); /* do not include `eol' */
  239. luaL_pushresult(&b); /* close buffer */
  240. return 1; /* read at least an `eol' */
  241. }
  242. }
  243. }
  244. static int read_chars (lua_State *L, FILE *f, size_t n) {
  245. size_t rlen; /* how much to read */
  246. size_t nr; /* number of chars actually read */
  247. luaL_Buffer b;
  248. luaL_buffinit(L, &b);
  249. rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
  250. do {
  251. char *p = luaL_prepbuffer(&b);
  252. if (rlen > n) rlen = n; /* cannot read more than asked */
  253. nr = fread(p, sizeof(char), rlen, f);
  254. luaL_addsize(&b, nr);
  255. n -= nr; /* still have to read `n' chars */
  256. } while (n > 0 && nr == rlen); /* until end of count or eof */
  257. luaL_pushresult(&b); /* close buffer */
  258. return (n == 0 || lua_objlen(L, -1) > 0);
  259. }
  260. static int g_read (lua_State *L, FILE *f, int first) {
  261. int nargs = lua_gettop(L) - 1;
  262. int success;
  263. int n;
  264. clearerr(f);
  265. if (nargs == 0) { /* no arguments? */
  266. success = read_line(L, f);
  267. n = first+1; /* to return 1 result */
  268. }
  269. else { /* ensure stack space for all results and for auxlib's buffer */
  270. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  271. success = 1;
  272. for (n = first; nargs-- && success; n++) {
  273. if (lua_type(L, n) == LUA_TNUMBER) {
  274. size_t l = (size_t)lua_tointeger(L, n);
  275. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  276. }
  277. else {
  278. const char *p = lua_tostring(L, n);
  279. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  280. switch (p[1]) {
  281. case 'n': /* number */
  282. success = read_number(L, f);
  283. break;
  284. case 'l': /* line */
  285. success = read_line(L, f);
  286. break;
  287. case 'a': /* file */
  288. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  289. success = 1; /* always success */
  290. break;
  291. default:
  292. return luaL_argerror(L, n, "invalid format");
  293. }
  294. }
  295. }
  296. }
  297. if (ferror(f))
  298. return pushresult(L, 0, NULL);
  299. if (!success) {
  300. lua_pop(L, 1); /* remove last result */
  301. lua_pushnil(L); /* push nil instead */
  302. }
  303. return n - first;
  304. }
  305. static int io_read (lua_State *L) {
  306. return g_read(L, getiofile(L, IO_INPUT), 1);
  307. }
  308. static int f_read (lua_State *L) {
  309. return g_read(L, tofile(L), 2);
  310. }
  311. static int io_readline (lua_State *L) {
  312. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
  313. int sucess;
  314. if (f == NULL) /* file is already closed? */
  315. luaL_error(L, "file is already closed");
  316. sucess = read_line(L, f);
  317. if (ferror(f))
  318. return luaL_error(L, "%s", strerror(errno));
  319. if (sucess) return 1;
  320. else { /* EOF */
  321. if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
  322. lua_settop(L, 0);
  323. lua_pushvalue(L, lua_upvalueindex(1));
  324. aux_close(L); /* close it */
  325. }
  326. return 0;
  327. }
  328. }
  329. /* }====================================================== */
  330. static int g_write (lua_State *L, FILE *f, int arg) {
  331. int nargs = lua_gettop(L) - 1;
  332. int status = 1;
  333. for (; nargs--; arg++) {
  334. if (lua_type(L, arg) == LUA_TNUMBER) {
  335. /* optimization: could be done exactly as for strings */
  336. status = status &&
  337. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  338. }
  339. else {
  340. size_t l;
  341. const char *s = luaL_checklstring(L, arg, &l);
  342. status = status && (fwrite(s, sizeof(char), l, f) == l);
  343. }
  344. }
  345. return pushresult(L, status, NULL);
  346. }
  347. static int io_write (lua_State *L) {
  348. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  349. }
  350. static int f_write (lua_State *L) {
  351. return g_write(L, tofile(L), 2);
  352. }
  353. static int f_seek (lua_State *L) {
  354. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  355. static const char *const modenames[] = {"set", "cur", "end", NULL};
  356. FILE *f = tofile(L);
  357. int op = luaL_checkoption(L, 2, "cur", modenames);
  358. long offset = luaL_optlong(L, 3, 0);
  359. op = fseek(f, offset, mode[op]);
  360. if (op)
  361. return pushresult(L, 0, NULL); /* error */
  362. else {
  363. lua_pushinteger(L, ftell(f));
  364. return 1;
  365. }
  366. }
  367. static int f_setvbuf (lua_State *L) {
  368. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  369. static const char *const modenames[] = {"no", "full", "line", NULL};
  370. FILE *f = tofile(L);
  371. int op = luaL_checkoption(L, 2, NULL, modenames);
  372. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  373. int res = setvbuf(f, NULL, mode[op], sz);
  374. return pushresult(L, res == 0, NULL);
  375. }
  376. static int io_flush (lua_State *L) {
  377. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  378. }
  379. static int f_flush (lua_State *L) {
  380. return pushresult(L, fflush(tofile(L)) == 0, NULL);
  381. }
  382. static const luaL_Reg iolib[] = {
  383. {"close", io_close},
  384. {"flush", io_flush},
  385. {"input", io_input},
  386. {"lines", io_lines},
  387. {"open", io_open},
  388. {"output", io_output},
  389. {"popen", io_popen},
  390. {"read", io_read},
  391. {"tmpfile", io_tmpfile},
  392. {"type", io_type},
  393. {"write", io_write},
  394. {NULL, NULL}
  395. };
  396. static const luaL_Reg flib[] = {
  397. {"close", io_close},
  398. {"flush", f_flush},
  399. {"lines", f_lines},
  400. {"read", f_read},
  401. {"seek", f_seek},
  402. {"setvbuf", f_setvbuf},
  403. {"write", f_write},
  404. {"__gc", io_gc},
  405. {"__tostring", io_tostring},
  406. {NULL, NULL}
  407. };
  408. static void createmeta (lua_State *L) {
  409. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  410. lua_pushvalue(L, -1); /* push metatable */
  411. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  412. luaL_register(L, NULL, flib); /* file methods */
  413. }
  414. static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
  415. *newfile(L) = f;
  416. if (k > 0) {
  417. lua_pushvalue(L, -1);
  418. lua_rawseti(L, LUA_ENVIRONINDEX, k);
  419. }
  420. lua_pushvalue(L, -2); /* copy environment */
  421. lua_setfenv(L, -2); /* set it */
  422. lua_setfield(L, -3, fname);
  423. }
  424. static void newfenv (lua_State *L, lua_CFunction cls) {
  425. lua_createtable(L, 0, 1);
  426. lua_pushcfunction(L, cls);
  427. lua_setfield(L, -2, "__close");
  428. }
  429. LUALIB_API int luaopen_io (lua_State *L) {
  430. createmeta(L);
  431. /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
  432. newfenv(L, io_fclose);
  433. lua_replace(L, LUA_ENVIRONINDEX);
  434. /* open library */
  435. luaL_register(L, LUA_IOLIBNAME, iolib);
  436. /* create (and set) default files */
  437. newfenv(L, io_noclose); /* close function for default files */
  438. createstdfile(L, stdin, IO_INPUT, "stdin");
  439. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  440. createstdfile(L, stderr, 0, "stderr");
  441. lua_pop(L, 1); /* pop environment for default files */
  442. lua_getfield(L, -1, "popen");
  443. newfenv(L, io_pclose); /* create environment for 'popen' */
  444. lua_setfenv(L, -2); /* set fenv for 'popen' */
  445. lua_pop(L, 1); /* pop 'popen' */
  446. return 1;
  447. }