2
0

liolib.c 13 KB

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