liolib.c 17 KB

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