liolib.c 13 KB

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