liolib.c 13 KB

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