liolib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /*
  2. ** $Id: liolib.c,v 2.100 2011/06/21 13:43:48 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. /*
  16. ** lua_popen spawns a new process connected to the current one through
  17. ** the file streams.
  18. */
  19. #if !defined(lua_popen) /* { */
  20. #if defined(LUA_USE_POPEN) /* { */
  21. #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
  22. #define lua_pclose(L,file) ((void)L, pclose(file))
  23. #elif defined(LUA_WIN) /* }{ */
  24. #define lua_popen(L,c,m) ((void)L, _popen(c,m))
  25. #define lua_pclose(L,file) ((void)L, _pclose(file))
  26. #else /* }{ */
  27. #define lua_popen(L,c,m) ((void)((void)c, m), \
  28. luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
  29. #define lua_pclose(L,file) ((void)((void)L, file), -1)
  30. #endif /* } */
  31. #endif /* } */
  32. #define IO_PREFIX "_IO_"
  33. #define IO_INPUT (IO_PREFIX "input")
  34. #define IO_OUTPUT (IO_PREFIX "output")
  35. typedef struct LStream {
  36. FILE *f; /* stream */
  37. lua_CFunction closef; /* to close stream (NULL for closed streams) */
  38. } LStream;
  39. static void fileerror (lua_State *L, int arg, const char *filename) {
  40. lua_pushfstring(L, "%s: %s", filename, strerror(errno));
  41. luaL_argerror(L, arg, lua_tostring(L, -1));
  42. }
  43. #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
  44. #define isclosed(p) ((p)->closef == NULL)
  45. static int io_type (lua_State *L) {
  46. LStream *p;
  47. luaL_checkany(L, 1);
  48. p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
  49. if (p == NULL)
  50. lua_pushnil(L); /* not a file */
  51. else if (isclosed(p))
  52. lua_pushliteral(L, "closed file");
  53. else
  54. lua_pushliteral(L, "file");
  55. return 1;
  56. }
  57. static int f_tostring (lua_State *L) {
  58. LStream *p = tolstream(L);
  59. if (isclosed(p))
  60. lua_pushliteral(L, "file (closed)");
  61. else
  62. lua_pushfstring(L, "file (%p)", p->f);
  63. return 1;
  64. }
  65. static FILE *tofile (lua_State *L) {
  66. LStream *p = tolstream(L);
  67. if (isclosed(p))
  68. luaL_error(L, "attempt to use a closed file");
  69. lua_assert(p->f);
  70. return p->f;
  71. }
  72. /*
  73. ** When creating file handles, always creates a `closed' file handle
  74. ** before opening the actual file; so, if there is a memory error, the
  75. ** file is not left opened.
  76. */
  77. static LStream *newprefile (lua_State *L) {
  78. LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
  79. p->closef = NULL; /* mark file handle as 'closed' */
  80. luaL_setmetatable(L, LUA_FILEHANDLE);
  81. return p;
  82. }
  83. static int aux_close (lua_State *L) {
  84. LStream *p = tolstream(L);
  85. lua_CFunction cf = p->closef;
  86. p->closef = NULL; /* mark stream as closed */
  87. return (*cf)(L); /* close it */
  88. }
  89. static int io_close (lua_State *L) {
  90. if (lua_isnone(L, 1)) /* no argument? */
  91. lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
  92. tofile(L); /* make sure argument is an open stream */
  93. return aux_close(L);
  94. }
  95. static int f_gc (lua_State *L) {
  96. LStream *p = tolstream(L);
  97. if (!isclosed(p) && p->f != NULL)
  98. aux_close(L); /* ignore closed and incompletely open files */
  99. return 0;
  100. }
  101. /*
  102. ** function to close regular files
  103. */
  104. static int io_fclose (lua_State *L) {
  105. LStream *p = tolstream(L);
  106. int res = fclose(p->f);
  107. return luaL_fileresult(L, (res == 0), NULL);
  108. }
  109. static LStream *newfile (lua_State *L) {
  110. LStream *p = newprefile(L);
  111. p->f = NULL;
  112. p->closef = &io_fclose;
  113. return p;
  114. }
  115. static int io_open (lua_State *L) {
  116. const char *filename = luaL_checkstring(L, 1);
  117. const char *mode = luaL_optstring(L, 2, "r");
  118. LStream *p = newfile(L);
  119. int i = 0;
  120. /* check whether 'mode' matches '[rwa]%+?b?' */
  121. if (!(mode[i] != '\0' && strchr("rwa", mode[i++]) != NULL &&
  122. (mode[i] != '+' || ++i) && /* skip if char is '+' */
  123. (mode[i] != 'b' || ++i) && /* skip if char is 'b' */
  124. (mode[i] == '\0')))
  125. return luaL_error(L, "invalid mode " LUA_QL("%s")
  126. " (should match " LUA_QL("[rwa]%%+?b?") ")", mode);
  127. p->f = fopen(filename, mode);
  128. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  129. }
  130. /*
  131. ** function to close 'popen' files
  132. */
  133. static int io_pclose (lua_State *L) {
  134. LStream *p = tolstream(L);
  135. return luaL_execresult(L, lua_pclose(L, p->f));
  136. }
  137. static int io_popen (lua_State *L) {
  138. const char *filename = luaL_checkstring(L, 1);
  139. const char *mode = luaL_optstring(L, 2, "r");
  140. LStream *p = newprefile(L);
  141. p->f = lua_popen(L, filename, mode);
  142. p->closef = &io_pclose;
  143. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  144. }
  145. static int io_tmpfile (lua_State *L) {
  146. LStream *p = newfile(L);
  147. p->f = tmpfile();
  148. return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
  149. }
  150. static FILE *getiofile (lua_State *L, const char *findex) {
  151. LStream *p;
  152. lua_getfield(L, LUA_REGISTRYINDEX, findex);
  153. p = (LStream *)lua_touserdata(L, -1);
  154. if (isclosed(p))
  155. luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
  156. return p->f;
  157. }
  158. static int g_iofile (lua_State *L, const char *f, const char *mode) {
  159. if (!lua_isnoneornil(L, 1)) {
  160. const char *filename = lua_tostring(L, 1);
  161. if (filename) {
  162. LStream *p = newfile(L);
  163. p->f = fopen(filename, mode);
  164. if (p->f == NULL)
  165. fileerror(L, 1, filename);
  166. }
  167. else {
  168. tofile(L); /* check that it's a valid file handle */
  169. lua_pushvalue(L, 1);
  170. }
  171. lua_setfield(L, LUA_REGISTRYINDEX, f);
  172. }
  173. /* return current value */
  174. lua_getfield(L, LUA_REGISTRYINDEX, f);
  175. return 1;
  176. }
  177. static int io_input (lua_State *L) {
  178. return g_iofile(L, IO_INPUT, "r");
  179. }
  180. static int io_output (lua_State *L) {
  181. return g_iofile(L, IO_OUTPUT, "w");
  182. }
  183. static int io_readline (lua_State *L);
  184. static void aux_lines (lua_State *L, int toclose) {
  185. int i;
  186. int n = lua_gettop(L) - 1; /* number of arguments to read */
  187. /* ensure that arguments will fit here and into 'io_readline' stack */
  188. luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
  189. lua_pushvalue(L, 1); /* file handle */
  190. lua_pushinteger(L, n); /* number of arguments to read */
  191. lua_pushboolean(L, toclose); /* close/not close file when finished */
  192. for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */
  193. lua_pushcclosure(L, io_readline, 3 + n);
  194. }
  195. static int f_lines (lua_State *L) {
  196. tofile(L); /* check that it's a valid file handle */
  197. aux_lines(L, 0);
  198. return 1;
  199. }
  200. static int io_lines (lua_State *L) {
  201. int toclose;
  202. if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
  203. if (lua_isnil(L, 1)) { /* no file name? */
  204. lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
  205. lua_replace(L, 1); /* put it at index 1 */
  206. tofile(L); /* check that it's a valid file handle */
  207. toclose = 0; /* do not close it after iteration */
  208. }
  209. else { /* open a new file */
  210. const char *filename = luaL_checkstring(L, 1);
  211. LStream *p = newfile(L);
  212. p->f = fopen(filename, "r");
  213. if (p->f == NULL)
  214. fileerror(L, 1, filename);
  215. lua_replace(L, 1); /* put file at index 1 */
  216. toclose = 1; /* close it after iteration */
  217. }
  218. aux_lines(L, toclose);
  219. return 1;
  220. }
  221. /*
  222. ** {======================================================
  223. ** READ
  224. ** =======================================================
  225. */
  226. static int read_number (lua_State *L, FILE *f) {
  227. lua_Number d;
  228. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  229. lua_pushnumber(L, d);
  230. return 1;
  231. }
  232. else {
  233. lua_pushnil(L); /* "result" to be removed */
  234. return 0; /* read fails */
  235. }
  236. }
  237. static int test_eof (lua_State *L, FILE *f) {
  238. int c = getc(f);
  239. ungetc(c, f);
  240. lua_pushlstring(L, NULL, 0);
  241. return (c != EOF);
  242. }
  243. static int read_line (lua_State *L, FILE *f, int chop) {
  244. luaL_Buffer b;
  245. luaL_buffinit(L, &b);
  246. for (;;) {
  247. size_t l;
  248. char *p = luaL_prepbuffer(&b);
  249. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  250. luaL_pushresult(&b); /* close buffer */
  251. return (lua_rawlen(L, -1) > 0); /* check whether read something */
  252. }
  253. l = strlen(p);
  254. if (l == 0 || p[l-1] != '\n')
  255. luaL_addsize(&b, l);
  256. else {
  257. luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
  258. luaL_pushresult(&b); /* close buffer */
  259. return 1; /* read at least an `eol' */
  260. }
  261. }
  262. }
  263. #define MAX_SIZE_T (~(size_t)0)
  264. static void read_all (lua_State *L, FILE *f) {
  265. size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */
  266. luaL_Buffer b;
  267. luaL_buffinit(L, &b);
  268. for (;;) {
  269. char *p = luaL_prepbuffsize(&b, rlen);
  270. size_t nr = fread(p, sizeof(char), rlen, f);
  271. luaL_addsize(&b, nr);
  272. if (nr < rlen) break; /* eof? */
  273. else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */
  274. rlen *= 2; /* double buffer size at each iteration */
  275. }
  276. luaL_pushresult(&b); /* close buffer */
  277. }
  278. static int read_chars (lua_State *L, FILE *f, size_t n) {
  279. size_t nr; /* number of chars actually read */
  280. char *p;
  281. luaL_Buffer b;
  282. luaL_buffinit(L, &b);
  283. p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
  284. nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
  285. luaL_addsize(&b, nr);
  286. luaL_pushresult(&b); /* close buffer */
  287. return (nr > 0); /* true iff read something */
  288. }
  289. static int g_read (lua_State *L, FILE *f, int first) {
  290. int nargs = lua_gettop(L) - 1;
  291. int success;
  292. int n;
  293. clearerr(f);
  294. if (nargs == 0) { /* no arguments? */
  295. success = read_line(L, f, 1);
  296. n = first+1; /* to return 1 result */
  297. }
  298. else { /* ensure stack space for all results and for auxlib's buffer */
  299. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  300. success = 1;
  301. for (n = first; nargs-- && success; n++) {
  302. if (lua_type(L, n) == LUA_TNUMBER) {
  303. size_t l = (size_t)lua_tointeger(L, n);
  304. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  305. }
  306. else {
  307. const char *p = lua_tostring(L, n);
  308. luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
  309. switch (p[1]) {
  310. case 'n': /* number */
  311. success = read_number(L, f);
  312. break;
  313. case 'l': /* line */
  314. success = read_line(L, f, 1);
  315. break;
  316. case 'L': /* line with end-of-line */
  317. success = read_line(L, f, 0);
  318. break;
  319. case 'a': /* file */
  320. read_all(L, f); /* read entire file */
  321. success = 1; /* always success */
  322. break;
  323. default:
  324. return luaL_argerror(L, n, "invalid format");
  325. }
  326. }
  327. }
  328. }
  329. if (ferror(f))
  330. return luaL_fileresult(L, 0, NULL);
  331. if (!success) {
  332. lua_pop(L, 1); /* remove last result */
  333. lua_pushnil(L); /* push nil instead */
  334. }
  335. return n - first;
  336. }
  337. static int io_read (lua_State *L) {
  338. return g_read(L, getiofile(L, IO_INPUT), 1);
  339. }
  340. static int f_read (lua_State *L) {
  341. return g_read(L, tofile(L), 2);
  342. }
  343. static int io_readline (lua_State *L) {
  344. LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
  345. int i;
  346. int n = (int)lua_tointeger(L, lua_upvalueindex(2));
  347. if (isclosed(p)) /* file is already closed? */
  348. return luaL_error(L, "file is already closed");
  349. lua_settop(L , 1);
  350. for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
  351. lua_pushvalue(L, lua_upvalueindex(3 + i));
  352. n = g_read(L, p->f, 2); /* 'n' is number of results */
  353. lua_assert(n > 0); /* should return at least a nil */
  354. if (!lua_isnil(L, -n)) /* read at least one value? */
  355. return n; /* return them */
  356. else { /* first result is nil: EOF or error */
  357. if (!lua_isnil(L, -1)) /* is there error information? */
  358. return luaL_error(L, "%s", lua_tostring(L, -1)); /* error */
  359. /* else EOF */
  360. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  361. lua_settop(L, 0);
  362. lua_pushvalue(L, lua_upvalueindex(1));
  363. aux_close(L); /* close it */
  364. }
  365. return 0;
  366. }
  367. }
  368. /* }====================================================== */
  369. static int g_write (lua_State *L, FILE *f, int arg) {
  370. int nargs = lua_gettop(L) - arg;
  371. int status = 1;
  372. for (; nargs--; arg++) {
  373. if (lua_type(L, arg) == LUA_TNUMBER) {
  374. /* optimization: could be done exactly as for strings */
  375. status = status &&
  376. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  377. }
  378. else {
  379. size_t l;
  380. const char *s = luaL_checklstring(L, arg, &l);
  381. status = status && (fwrite(s, sizeof(char), l, f) == l);
  382. }
  383. }
  384. if (status) return 1; /* file handle already on stack top */
  385. else return luaL_fileresult(L, status, NULL);
  386. }
  387. static int io_write (lua_State *L) {
  388. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  389. }
  390. static int f_write (lua_State *L) {
  391. FILE *f = tofile(L);
  392. lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
  393. return g_write(L, f, 2);
  394. }
  395. static int f_seek (lua_State *L) {
  396. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  397. static const char *const modenames[] = {"set", "cur", "end", NULL};
  398. FILE *f = tofile(L);
  399. int op = luaL_checkoption(L, 2, "cur", modenames);
  400. long offset = luaL_optlong(L, 3, 0);
  401. op = fseek(f, offset, mode[op]);
  402. if (op)
  403. return luaL_fileresult(L, 0, NULL); /* error */
  404. else {
  405. lua_pushinteger(L, ftell(f));
  406. return 1;
  407. }
  408. }
  409. static int f_setvbuf (lua_State *L) {
  410. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  411. static const char *const modenames[] = {"no", "full", "line", NULL};
  412. FILE *f = tofile(L);
  413. int op = luaL_checkoption(L, 2, NULL, modenames);
  414. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  415. int res = setvbuf(f, NULL, mode[op], sz);
  416. return luaL_fileresult(L, res == 0, NULL);
  417. }
  418. static int io_flush (lua_State *L) {
  419. return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
  420. }
  421. static int f_flush (lua_State *L) {
  422. return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
  423. }
  424. /*
  425. ** functions for 'io' library
  426. */
  427. static const luaL_Reg iolib[] = {
  428. {"close", io_close},
  429. {"flush", io_flush},
  430. {"input", io_input},
  431. {"lines", io_lines},
  432. {"open", io_open},
  433. {"output", io_output},
  434. {"popen", io_popen},
  435. {"read", io_read},
  436. {"tmpfile", io_tmpfile},
  437. {"type", io_type},
  438. {"write", io_write},
  439. {NULL, NULL}
  440. };
  441. /*
  442. ** methods for file handles
  443. */
  444. static const luaL_Reg flib[] = {
  445. {"close", io_close},
  446. {"flush", f_flush},
  447. {"lines", f_lines},
  448. {"read", f_read},
  449. {"seek", f_seek},
  450. {"setvbuf", f_setvbuf},
  451. {"write", f_write},
  452. {"__gc", f_gc},
  453. {"__tostring", f_tostring},
  454. {NULL, NULL}
  455. };
  456. static void createmeta (lua_State *L) {
  457. luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
  458. lua_pushvalue(L, -1); /* push metatable */
  459. lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
  460. luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
  461. lua_pop(L, 1); /* pop new metatable */
  462. }
  463. /*
  464. ** function to (not) close the standard files stdin, stdout, and stderr
  465. */
  466. static int io_noclose (lua_State *L) {
  467. LStream *p = tolstream(L);
  468. p->closef = &io_noclose; /* keep file opened */
  469. lua_pushnil(L);
  470. lua_pushliteral(L, "cannot close standard file");
  471. return 2;
  472. }
  473. static void createstdfile (lua_State *L, FILE *f, const char *k,
  474. const char *fname) {
  475. LStream *p = newprefile(L);
  476. p->f = f;
  477. p->closef = &io_noclose;
  478. if (k != NULL) {
  479. lua_pushvalue(L, -1);
  480. lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
  481. }
  482. lua_setfield(L, -2, fname); /* add file to module */
  483. }
  484. LUAMOD_API int luaopen_io (lua_State *L) {
  485. luaL_newlib(L, iolib); /* new module */
  486. createmeta(L);
  487. /* create (and set) default files */
  488. createstdfile(L, stdin, IO_INPUT, "stdin");
  489. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  490. createstdfile(L, stderr, NULL, "stderr");
  491. return 1;
  492. }