liolib.c 13 KB

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