liolib.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. ** $Id: liolib.c $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define liolib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <ctype.h>
  10. #include <errno.h>
  11. #include <locale.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include "lua.h"
  16. #include "lauxlib.h"
  17. #include "lualib.h"
  18. #include "llimits.h"
  19. /*
  20. ** Change this macro to accept other modes for 'fopen' besides
  21. ** the standard ones.
  22. */
  23. #if !defined(l_checkmode)
  24. /* accepted extensions to 'mode' in 'fopen' */
  25. #if !defined(L_MODEEXT)
  26. #define L_MODEEXT "b"
  27. #endif
  28. /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
  29. static int l_checkmode (const char *mode) {
  30. return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
  31. (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */
  32. (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */
  33. }
  34. #endif
  35. /*
  36. ** {======================================================
  37. ** l_popen spawns a new process connected to the current
  38. ** one through the file streams.
  39. ** =======================================================
  40. */
  41. #if !defined(l_popen) /* { */
  42. #if defined(LUA_USE_POSIX) /* { */
  43. #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
  44. #define l_pclose(L,file) (pclose(file))
  45. #elif defined(LUA_USE_WINDOWS) /* }{ */
  46. #define l_popen(L,c,m) (_popen(c,m))
  47. #define l_pclose(L,file) (_pclose(file))
  48. #if !defined(l_checkmodep)
  49. /* Windows accepts "[rw][bt]?" as valid modes */
  50. #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
  51. (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
  52. #endif
  53. #else /* }{ */
  54. /* ISO C definitions */
  55. #define l_popen(L,c,m) \
  56. ((void)c, (void)m, \
  57. luaL_error(L, "'popen' not supported"), \
  58. (FILE*)0)
  59. #define l_pclose(L,file) ((void)L, (void)file, -1)
  60. #endif /* } */
  61. #endif /* } */
  62. #if !defined(l_checkmodep)
  63. /* By default, Lua accepts only "r" or "w" as valid modes */
  64. #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
  65. #endif
  66. /* }====================================================== */
  67. #if !defined(l_getc) /* { */
  68. #if defined(LUA_USE_POSIX)
  69. #define l_getc(f) getc_unlocked(f)
  70. #define l_lockfile(f) flockfile(f)
  71. #define l_unlockfile(f) funlockfile(f)
  72. #else
  73. #define l_getc(f) getc(f)
  74. #define l_lockfile(f) ((void)0)
  75. #define l_unlockfile(f) ((void)0)
  76. #endif
  77. #endif /* } */
  78. /*
  79. ** {======================================================
  80. ** l_fseek: configuration for longer offsets
  81. ** =======================================================
  82. */
  83. #if !defined(l_fseek) /* { */
  84. #if defined(LUA_USE_POSIX) /* { */
  85. #include <sys/types.h>
  86. #define l_fseek(f,o,w) fseeko(f,o,w)
  87. #define l_ftell(f) ftello(f)
  88. #define l_seeknum off_t
  89. #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
  90. && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
  91. /* Windows (but not DDK) and Visual C++ 2005 or higher */
  92. #define l_fseek(f,o,w) _fseeki64(f,o,w)
  93. #define l_ftell(f) _ftelli64(f)
  94. #define l_seeknum __int64
  95. #else /* }{ */
  96. /* ISO C definitions */
  97. #define l_fseek(f,o,w) fseek(f,o,w)
  98. #define l_ftell(f) ftell(f)
  99. #define l_seeknum long
  100. #endif /* } */
  101. #endif /* } */
  102. /* }====================================================== */
  103. #define IO_PREFIX "_IO_"
  104. #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
  105. #define IO_INPUT (IO_PREFIX "input")
  106. #define IO_OUTPUT (IO_PREFIX "output")
  107. typedef luaL_Stream LStream;
  108. #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
  109. #define isclosed(p) ((p)->closef == NULL)
  110. static int io_type (lua_State *L) {
  111. LStream *p;
  112. luaL_checkany(L, 1);
  113. p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
  114. if (p == NULL)
  115. luaL_pushfail(L); /* not a file */
  116. else if (isclosed(p))
  117. lua_pushliteral(L, "closed file");
  118. else
  119. lua_pushliteral(L, "file");
  120. return 1;
  121. }
  122. static int f_tostring (lua_State *L) {
  123. LStream *p = tolstream(L);
  124. if (isclosed(p))
  125. lua_pushliteral(L, "file (closed)");
  126. else
  127. lua_pushfstring(L, "file (%p)", p->f);
  128. return 1;
  129. }
  130. static FILE *tofile (lua_State *L) {
  131. LStream *p = tolstream(L);
  132. if (l_unlikely(isclosed(p)))
  133. luaL_error(L, "attempt to use a closed file");
  134. lua_assert(p->f);
  135. return p->f;
  136. }
  137. /*
  138. ** When creating file handles, always creates a 'closed' file handle
  139. ** before opening the actual file; so, if there is a memory error, the
  140. ** handle is in a consistent state.
  141. */
  142. static LStream *newprefile (lua_State *L) {
  143. LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
  144. p->closef = NULL; /* mark file handle as 'closed' */
  145. luaL_setmetatable(L, LUA_FILEHANDLE);
  146. return p;
  147. }
  148. /*
  149. ** Calls the 'close' function from a file handle. The 'volatile' avoids
  150. ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
  151. ** 32 bits).
  152. */
  153. static int aux_close (lua_State *L) {
  154. LStream *p = tolstream(L);
  155. volatile lua_CFunction cf = p->closef;
  156. p->closef = NULL; /* mark stream as closed */
  157. return (*cf)(L); /* close it */
  158. }
  159. static int f_close (lua_State *L) {
  160. tofile(L); /* make sure argument is an open stream */
  161. return aux_close(L);
  162. }
  163. static int io_close (lua_State *L) {
  164. if (lua_isnone(L, 1)) /* no argument? */
  165. lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */
  166. return f_close(L);
  167. }
  168. static int f_gc (lua_State *L) {
  169. LStream *p = tolstream(L);
  170. if (!isclosed(p) && p->f != NULL)
  171. aux_close(L); /* ignore closed and incompletely open files */
  172. return 0;
  173. }
  174. /*
  175. ** function to close regular files
  176. */
  177. static int io_fclose (lua_State *L) {
  178. LStream *p = tolstream(L);
  179. errno = 0;
  180. return luaL_fileresult(L, (fclose(p->f) == 0), NULL);
  181. }
  182. static LStream *newfile (lua_State *L) {
  183. LStream *p = newprefile(L);
  184. p->f = NULL;
  185. p->closef = &io_fclose;
  186. return p;
  187. }
  188. static void opencheck (lua_State *L, const char *fname, const char *mode) {
  189. LStream *p = newfile(L);
  190. p->f = fopen(fname, mode);
  191. if (l_unlikely(p->f == NULL))
  192. luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
  193. }
  194. static int io_open (lua_State *L) {
  195. const char *filename = luaL_checkstring(L, 1);
  196. const char *mode = luaL_optstring(L, 2, "r");
  197. LStream *p = newfile(L);
  198. const char *md = mode; /* to traverse/check mode */
  199. luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
  200. errno = 0;
  201. p->f = fopen(filename, mode);
  202. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  203. }
  204. /*
  205. ** function to close 'popen' files
  206. */
  207. static int io_pclose (lua_State *L) {
  208. LStream *p = tolstream(L);
  209. errno = 0;
  210. return luaL_execresult(L, l_pclose(L, p->f));
  211. }
  212. static int io_popen (lua_State *L) {
  213. const char *filename = luaL_checkstring(L, 1);
  214. const char *mode = luaL_optstring(L, 2, "r");
  215. LStream *p = newprefile(L);
  216. luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
  217. errno = 0;
  218. p->f = l_popen(L, filename, mode);
  219. p->closef = &io_pclose;
  220. return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
  221. }
  222. static int io_tmpfile (lua_State *L) {
  223. LStream *p = newfile(L);
  224. errno = 0;
  225. p->f = tmpfile();
  226. return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
  227. }
  228. static FILE *getiofile (lua_State *L, const char *findex) {
  229. LStream *p;
  230. lua_getfield(L, LUA_REGISTRYINDEX, findex);
  231. p = (LStream *)lua_touserdata(L, -1);
  232. if (l_unlikely(isclosed(p)))
  233. luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
  234. return p->f;
  235. }
  236. static int g_iofile (lua_State *L, const char *f, const char *mode) {
  237. if (!lua_isnoneornil(L, 1)) {
  238. const char *filename = lua_tostring(L, 1);
  239. if (filename)
  240. opencheck(L, filename, mode);
  241. else {
  242. tofile(L); /* check that it's a valid file handle */
  243. lua_pushvalue(L, 1);
  244. }
  245. lua_setfield(L, LUA_REGISTRYINDEX, f);
  246. }
  247. /* return current value */
  248. lua_getfield(L, LUA_REGISTRYINDEX, f);
  249. return 1;
  250. }
  251. static int io_input (lua_State *L) {
  252. return g_iofile(L, IO_INPUT, "r");
  253. }
  254. static int io_output (lua_State *L) {
  255. return g_iofile(L, IO_OUTPUT, "w");
  256. }
  257. static int io_readline (lua_State *L);
  258. /*
  259. ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
  260. ** in the limit for upvalues of a closure)
  261. */
  262. #define MAXARGLINE 250
  263. /*
  264. ** Auxiliary function to create the iteration function for 'lines'.
  265. ** The iteration function is a closure over 'io_readline', with
  266. ** the following upvalues:
  267. ** 1) The file being read (first value in the stack)
  268. ** 2) the number of arguments to read
  269. ** 3) a boolean, true iff file has to be closed when finished ('toclose')
  270. ** *) a variable number of format arguments (rest of the stack)
  271. */
  272. static void aux_lines (lua_State *L, int toclose) {
  273. int n = lua_gettop(L) - 1; /* number of arguments to read */
  274. luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
  275. lua_pushvalue(L, 1); /* file */
  276. lua_pushinteger(L, n); /* number of arguments to read */
  277. lua_pushboolean(L, toclose); /* close/not close file when finished */
  278. lua_rotate(L, 2, 3); /* move the three values to their positions */
  279. lua_pushcclosure(L, io_readline, 3 + n);
  280. }
  281. static int f_lines (lua_State *L) {
  282. tofile(L); /* check that it's a valid file handle */
  283. aux_lines(L, 0);
  284. return 1;
  285. }
  286. /*
  287. ** Return an iteration function for 'io.lines'. If file has to be
  288. ** closed, also returns the file itself as a second result (to be
  289. ** closed as the state at the exit of a generic for).
  290. */
  291. static int io_lines (lua_State *L) {
  292. int toclose;
  293. if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
  294. if (lua_isnil(L, 1)) { /* no file name? */
  295. lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
  296. lua_replace(L, 1); /* put it at index 1 */
  297. tofile(L); /* check that it's a valid file handle */
  298. toclose = 0; /* do not close it after iteration */
  299. }
  300. else { /* open a new file */
  301. const char *filename = luaL_checkstring(L, 1);
  302. opencheck(L, filename, "r");
  303. lua_replace(L, 1); /* put file at index 1 */
  304. toclose = 1; /* close it after iteration */
  305. }
  306. aux_lines(L, toclose); /* push iteration function */
  307. if (toclose) {
  308. lua_pushnil(L); /* state */
  309. lua_pushnil(L); /* control */
  310. lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */
  311. return 4;
  312. }
  313. else
  314. return 1;
  315. }
  316. /*
  317. ** {======================================================
  318. ** READ
  319. ** =======================================================
  320. */
  321. /* maximum length of a numeral */
  322. #if !defined (L_MAXLENNUM)
  323. #define L_MAXLENNUM 200
  324. #endif
  325. /* auxiliary structure used by 'read_number' */
  326. typedef struct {
  327. FILE *f; /* file being read */
  328. int c; /* current character (look ahead) */
  329. int n; /* number of elements in buffer 'buff' */
  330. char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
  331. } RN;
  332. /*
  333. ** Add current char to buffer (if not out of space) and read next one
  334. */
  335. static int nextc (RN *rn) {
  336. if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
  337. rn->buff[0] = '\0'; /* invalidate result */
  338. return 0; /* fail */
  339. }
  340. else {
  341. rn->buff[rn->n++] = cast_char(rn->c); /* save current char */
  342. rn->c = l_getc(rn->f); /* read next one */
  343. return 1;
  344. }
  345. }
  346. /*
  347. ** Accept current char if it is in 'set' (of size 2)
  348. */
  349. static int test2 (RN *rn, const char *set) {
  350. if (rn->c == set[0] || rn->c == set[1])
  351. return nextc(rn);
  352. else return 0;
  353. }
  354. /*
  355. ** Read a sequence of (hex)digits
  356. */
  357. static int readdigits (RN *rn, int hex) {
  358. int count = 0;
  359. while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
  360. count++;
  361. return count;
  362. }
  363. /*
  364. ** Read a number: first reads a valid prefix of a numeral into a buffer.
  365. ** Then it calls 'lua_stringtonumber' to check whether the format is
  366. ** correct and to convert it to a Lua number.
  367. */
  368. static int read_number (lua_State *L, FILE *f) {
  369. RN rn;
  370. int count = 0;
  371. int hex = 0;
  372. char decp[2];
  373. rn.f = f; rn.n = 0;
  374. decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
  375. decp[1] = '.'; /* always accept a dot */
  376. l_lockfile(rn.f);
  377. do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
  378. test2(&rn, "-+"); /* optional sign */
  379. if (test2(&rn, "00")) {
  380. if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
  381. else count = 1; /* count initial '0' as a valid digit */
  382. }
  383. count += readdigits(&rn, hex); /* integral part */
  384. if (test2(&rn, decp)) /* decimal point? */
  385. count += readdigits(&rn, hex); /* fractional part */
  386. if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
  387. test2(&rn, "-+"); /* exponent sign */
  388. readdigits(&rn, 0); /* exponent digits */
  389. }
  390. ungetc(rn.c, rn.f); /* unread look-ahead char */
  391. l_unlockfile(rn.f);
  392. rn.buff[rn.n] = '\0'; /* finish string */
  393. if (l_likely(lua_stringtonumber(L, rn.buff)))
  394. return 1; /* ok, it is a valid number */
  395. else { /* invalid format */
  396. lua_pushnil(L); /* "result" to be removed */
  397. return 0; /* read fails */
  398. }
  399. }
  400. static int test_eof (lua_State *L, FILE *f) {
  401. int c = getc(f);
  402. ungetc(c, f); /* no-op when c == EOF */
  403. lua_pushliteral(L, "");
  404. return (c != EOF);
  405. }
  406. static int read_line (lua_State *L, FILE *f, int chop) {
  407. luaL_Buffer b;
  408. int c;
  409. luaL_buffinit(L, &b);
  410. do { /* may need to read several chunks to get whole line */
  411. char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */
  412. unsigned i = 0;
  413. l_lockfile(f); /* no memory errors can happen inside the lock */
  414. while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
  415. buff[i++] = cast_char(c); /* read up to end of line or buffer limit */
  416. l_unlockfile(f);
  417. luaL_addsize(&b, i);
  418. } while (c != EOF && c != '\n'); /* repeat until end of line */
  419. if (!chop && c == '\n') /* want a newline and have one? */
  420. luaL_addchar(&b, '\n'); /* add ending newline to result */
  421. luaL_pushresult(&b); /* close buffer */
  422. /* return ok if read something (either a newline or something else) */
  423. return (c == '\n' || lua_rawlen(L, -1) > 0);
  424. }
  425. static void read_all (lua_State *L, FILE *f) {
  426. size_t nr;
  427. luaL_Buffer b;
  428. luaL_buffinit(L, &b);
  429. do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
  430. char *p = luaL_prepbuffer(&b);
  431. nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
  432. luaL_addsize(&b, nr);
  433. } while (nr == LUAL_BUFFERSIZE);
  434. luaL_pushresult(&b); /* close buffer */
  435. }
  436. static int read_chars (lua_State *L, FILE *f, size_t n) {
  437. size_t nr; /* number of chars actually read */
  438. char *p;
  439. luaL_Buffer b;
  440. luaL_buffinit(L, &b);
  441. p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
  442. nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
  443. luaL_addsize(&b, nr);
  444. luaL_pushresult(&b); /* close buffer */
  445. return (nr > 0); /* true iff read something */
  446. }
  447. static int g_read (lua_State *L, FILE *f, int first) {
  448. int nargs = lua_gettop(L) - 1;
  449. int n, success;
  450. clearerr(f);
  451. errno = 0;
  452. if (nargs == 0) { /* no arguments? */
  453. success = read_line(L, f, 1);
  454. n = first + 1; /* to return 1 result */
  455. }
  456. else {
  457. /* ensure stack space for all results and for auxlib's buffer */
  458. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  459. success = 1;
  460. for (n = first; nargs-- && success; n++) {
  461. if (lua_type(L, n) == LUA_TNUMBER) {
  462. size_t l = (size_t)luaL_checkinteger(L, n);
  463. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  464. }
  465. else {
  466. const char *p = luaL_checkstring(L, n);
  467. if (*p == '*') p++; /* skip optional '*' (for compatibility) */
  468. switch (*p) {
  469. case 'n': /* number */
  470. success = read_number(L, f);
  471. break;
  472. case 'l': /* line */
  473. success = read_line(L, f, 1);
  474. break;
  475. case 'L': /* line with end-of-line */
  476. success = read_line(L, f, 0);
  477. break;
  478. case 'a': /* file */
  479. read_all(L, f); /* read entire file */
  480. success = 1; /* always success */
  481. break;
  482. default:
  483. return luaL_argerror(L, n, "invalid format");
  484. }
  485. }
  486. }
  487. }
  488. if (ferror(f))
  489. return luaL_fileresult(L, 0, NULL);
  490. if (!success) {
  491. lua_pop(L, 1); /* remove last result */
  492. luaL_pushfail(L); /* push nil instead */
  493. }
  494. return n - first;
  495. }
  496. static int io_read (lua_State *L) {
  497. return g_read(L, getiofile(L, IO_INPUT), 1);
  498. }
  499. static int f_read (lua_State *L) {
  500. return g_read(L, tofile(L), 2);
  501. }
  502. /*
  503. ** Iteration function for 'lines'.
  504. */
  505. static int io_readline (lua_State *L) {
  506. LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
  507. int i;
  508. int n = (int)lua_tointeger(L, lua_upvalueindex(2));
  509. if (isclosed(p)) /* file is already closed? */
  510. return luaL_error(L, "file is already closed");
  511. lua_settop(L , 1);
  512. luaL_checkstack(L, n, "too many arguments");
  513. for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
  514. lua_pushvalue(L, lua_upvalueindex(3 + i));
  515. n = g_read(L, p->f, 2); /* 'n' is number of results */
  516. lua_assert(n > 0); /* should return at least a nil */
  517. if (lua_toboolean(L, -n)) /* read at least one value? */
  518. return n; /* return them */
  519. else { /* first result is false: EOF or error */
  520. if (n > 1) { /* is there error information? */
  521. /* 2nd result is error message */
  522. return luaL_error(L, "%s", lua_tostring(L, -n + 1));
  523. }
  524. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  525. lua_settop(L, 0); /* clear stack */
  526. lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */
  527. aux_close(L); /* close it */
  528. }
  529. return 0;
  530. }
  531. }
  532. /* }====================================================== */
  533. static int g_write (lua_State *L, FILE *f, int arg) {
  534. int nargs = lua_gettop(L) - arg;
  535. size_t totalbytes = 0; /* total number of bytes written */
  536. errno = 0;
  537. for (; nargs--; arg++) { /* for each argument */
  538. char buff[LUA_N2SBUFFSZ];
  539. const char *s;
  540. size_t numbytes; /* bytes written in one call to 'fwrite' */
  541. size_t len = lua_numbertocstring(L, arg, buff); /* try as a number */
  542. if (len > 0) { /* did conversion work (value was a number)? */
  543. s = buff;
  544. len--;
  545. }
  546. else /* must be a string */
  547. s = luaL_checklstring(L, arg, &len);
  548. numbytes = fwrite(s, sizeof(char), len, f);
  549. totalbytes += numbytes;
  550. if (numbytes < len) { /* write error? */
  551. int n = luaL_fileresult(L, 0, NULL);
  552. lua_pushinteger(L, cast_st2S(totalbytes));
  553. return n + 1; /* return fail, error msg., error code, and counter */
  554. }
  555. }
  556. return 1; /* no errors; file handle already on stack top */
  557. }
  558. static int io_write (lua_State *L) {
  559. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  560. }
  561. static int f_write (lua_State *L) {
  562. FILE *f = tofile(L);
  563. lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
  564. return g_write(L, f, 2);
  565. }
  566. static int f_seek (lua_State *L) {
  567. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  568. static const char *const modenames[] = {"set", "cur", "end", NULL};
  569. FILE *f = tofile(L);
  570. int op = luaL_checkoption(L, 2, "cur", modenames);
  571. lua_Integer p3 = luaL_optinteger(L, 3, 0);
  572. l_seeknum offset = (l_seeknum)p3;
  573. luaL_argcheck(L, (lua_Integer)offset == p3, 3,
  574. "not an integer in proper range");
  575. errno = 0;
  576. op = l_fseek(f, offset, mode[op]);
  577. if (l_unlikely(op))
  578. return luaL_fileresult(L, 0, NULL); /* error */
  579. else {
  580. lua_pushinteger(L, (lua_Integer)l_ftell(f));
  581. return 1;
  582. }
  583. }
  584. static int f_setvbuf (lua_State *L) {
  585. static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  586. static const char *const modenames[] = {"no", "full", "line", NULL};
  587. FILE *f = tofile(L);
  588. int op = luaL_checkoption(L, 2, NULL, modenames);
  589. lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  590. int res;
  591. errno = 0;
  592. res = setvbuf(f, NULL, mode[op], (size_t)sz);
  593. return luaL_fileresult(L, res == 0, NULL);
  594. }
  595. static int aux_flush (lua_State *L, FILE *f) {
  596. errno = 0;
  597. return luaL_fileresult(L, fflush(f) == 0, NULL);
  598. }
  599. static int f_flush (lua_State *L) {
  600. return aux_flush(L, tofile(L));
  601. }
  602. static int io_flush (lua_State *L) {
  603. return aux_flush(L, getiofile(L, IO_OUTPUT));
  604. }
  605. /*
  606. ** functions for 'io' library
  607. */
  608. static const luaL_Reg iolib[] = {
  609. {"close", io_close},
  610. {"flush", io_flush},
  611. {"input", io_input},
  612. {"lines", io_lines},
  613. {"open", io_open},
  614. {"output", io_output},
  615. {"popen", io_popen},
  616. {"read", io_read},
  617. {"tmpfile", io_tmpfile},
  618. {"type", io_type},
  619. {"write", io_write},
  620. {NULL, NULL}
  621. };
  622. /*
  623. ** methods for file handles
  624. */
  625. static const luaL_Reg meth[] = {
  626. {"read", f_read},
  627. {"write", f_write},
  628. {"lines", f_lines},
  629. {"flush", f_flush},
  630. {"seek", f_seek},
  631. {"close", f_close},
  632. {"setvbuf", f_setvbuf},
  633. {NULL, NULL}
  634. };
  635. /*
  636. ** metamethods for file handles
  637. */
  638. static const luaL_Reg metameth[] = {
  639. {"__index", NULL}, /* placeholder */
  640. {"__gc", f_gc},
  641. {"__close", f_gc},
  642. {"__tostring", f_tostring},
  643. {NULL, NULL}
  644. };
  645. static void createmeta (lua_State *L) {
  646. luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
  647. luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
  648. luaL_newlibtable(L, meth); /* create method table */
  649. luaL_setfuncs(L, meth, 0); /* add file methods to method table */
  650. lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
  651. lua_pop(L, 1); /* pop metatable */
  652. }
  653. /*
  654. ** function to (not) close the standard files stdin, stdout, and stderr
  655. */
  656. static int io_noclose (lua_State *L) {
  657. LStream *p = tolstream(L);
  658. p->closef = &io_noclose; /* keep file opened */
  659. luaL_pushfail(L);
  660. lua_pushliteral(L, "cannot close standard file");
  661. return 2;
  662. }
  663. static void createstdfile (lua_State *L, FILE *f, const char *k,
  664. const char *fname) {
  665. LStream *p = newprefile(L);
  666. p->f = f;
  667. p->closef = &io_noclose;
  668. if (k != NULL) {
  669. lua_pushvalue(L, -1);
  670. lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
  671. }
  672. lua_setfield(L, -2, fname); /* add file to module */
  673. }
  674. LUAMOD_API int luaopen_io (lua_State *L) {
  675. luaL_newlib(L, iolib); /* new module */
  676. createmeta(L);
  677. /* create (and set) default files */
  678. createstdfile(L, stdin, IO_INPUT, "stdin");
  679. createstdfile(L, stdout, IO_OUTPUT, "stdout");
  680. createstdfile(L, stderr, NULL, "stderr");
  681. return 1;
  682. }