liolib.c 17 KB

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