liolib.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. /*
  2. ** $Id: liolib.c,v 2.19 2002/09/19 20:12:47 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <errno.h>
  7. #include <locale.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. /*
  16. ** {======================================================
  17. ** FILE Operations
  18. ** =======================================================
  19. */
  20. #ifndef USE_POPEN
  21. #define pclose(f) (-1)
  22. #endif
  23. #define FILEHANDLE "FileHandle"
  24. #define IO_INPUT "_input"
  25. #define IO_OUTPUT "_output"
  26. static int pushresult (lua_State *L, int i) {
  27. if (i) {
  28. lua_pushboolean(L, 1);
  29. return 1;
  30. }
  31. else {
  32. lua_pushnil(L);
  33. lua_pushstring(L, strerror(errno));
  34. lua_pushnumber(L, errno);
  35. return 3;
  36. }
  37. }
  38. static FILE *tofile (lua_State *L, int findex) {
  39. FILE **f = (FILE **)lua_touserdata(L, findex);
  40. if (f && *f && lua_getmetatable(L, findex) &&
  41. lua_rawequal(L, -1, lua_upvalueindex(1))) {
  42. lua_pop(L, 1);
  43. return *f;
  44. }
  45. if (findex > 0) {
  46. if (f && *f == NULL)
  47. luaL_error(L, "attempt to use a closed file");
  48. else
  49. luaL_argerror(L, findex, "bad file");
  50. }
  51. return NULL;
  52. }
  53. static void newfile (lua_State *L, FILE *f) {
  54. lua_boxpointer(L, f);
  55. lua_pushliteral(L, FILEHANDLE);
  56. lua_rawget(L, LUA_REGISTRYINDEX);
  57. lua_setmetatable(L, -2);
  58. }
  59. static void registerfile (lua_State *L, FILE *f, const char *name,
  60. const char *impname) {
  61. lua_pushstring(L, name);
  62. newfile(L, f);
  63. if (impname) {
  64. lua_pushstring(L, impname);
  65. lua_pushvalue(L, -2);
  66. lua_settable(L, -6);
  67. }
  68. lua_settable(L, -3);
  69. }
  70. static int setnewfile (lua_State *L, FILE *f) {
  71. if (f == NULL)
  72. return pushresult(L, 0);
  73. else {
  74. newfile(L, f);
  75. return 1;
  76. }
  77. }
  78. static int aux_close (lua_State *L) {
  79. FILE *f = tofile(L, 1);
  80. if (f == stdin || f == stdout || f == stderr)
  81. return 0; /* file cannot be closed */
  82. *(FILE **)lua_touserdata(L, 1) = NULL; /* mark file as closed */
  83. return (pclose(f) != -1) || (fclose(f) == 0);
  84. }
  85. static int io_close (lua_State *L) {
  86. if (lua_isnone(L, 1)) {
  87. lua_pushstring(L, IO_OUTPUT);
  88. lua_rawget(L, lua_upvalueindex(1));
  89. }
  90. return pushresult(L, aux_close(L));
  91. }
  92. static int io_gc (lua_State *L) {
  93. FILE **f = (FILE **)lua_touserdata(L, 1);
  94. if (!(f && *f == NULL)) /* ignore closed files */
  95. aux_close(L);
  96. return 0;
  97. }
  98. static int io_open (lua_State *L) {
  99. FILE *f = fopen(luaL_check_string(L, 1), luaL_opt_string(L, 2, "r"));
  100. return setnewfile(L, f);
  101. }
  102. static int io_popen (lua_State *L) {
  103. #ifndef USE_POPEN
  104. luaL_error(L, "`popen' not supported");
  105. return 0;
  106. #else
  107. FILE *f = popen(luaL_check_string(L, 1), luaL_opt_string(L, 2, "r"));
  108. return setnewfile(L, f);
  109. #endif
  110. }
  111. static int io_tmpfile (lua_State *L) {
  112. return setnewfile(L, tmpfile());
  113. }
  114. static FILE *getiofile (lua_State *L, const char *name) {
  115. FILE *f;
  116. lua_pushstring(L, name);
  117. lua_rawget(L, lua_upvalueindex(1));
  118. f = tofile(L, -1);
  119. if (f == NULL)
  120. luaL_error(L, "%s is closed", name);
  121. return f;
  122. }
  123. static int g_iofile (lua_State *L, const char *name, const char *mode) {
  124. if (lua_isnoneornil(L, 1)) {
  125. lua_pushstring(L, name);
  126. lua_rawget(L, lua_upvalueindex(1));
  127. return 1;
  128. }
  129. else {
  130. const char *filename = lua_tostring(L, 1);
  131. lua_pushstring(L, name);
  132. if (filename) {
  133. FILE *f = fopen(filename, mode);
  134. luaL_arg_check(L, f, 1, strerror(errno));
  135. newfile(L, f);
  136. }
  137. else {
  138. tofile(L, 1); /* check that it's a valid file handle */
  139. lua_pushvalue(L, 1);
  140. }
  141. lua_rawset(L, lua_upvalueindex(1));
  142. return 0;
  143. }
  144. }
  145. static int io_input (lua_State *L) {
  146. return g_iofile(L, IO_INPUT, "r");
  147. }
  148. static int io_output (lua_State *L) {
  149. return g_iofile(L, IO_OUTPUT, "w");
  150. }
  151. static int io_readline (lua_State *L);
  152. static void aux_lines (lua_State *L, int index, int close) {
  153. lua_pushliteral(L, FILEHANDLE);
  154. lua_rawget(L, LUA_REGISTRYINDEX);
  155. lua_pushvalue(L, index);
  156. lua_pushboolean(L, close); /* close/not close file when finished */
  157. lua_pushcclosure(L, io_readline, 3);
  158. }
  159. static int f_lines (lua_State *L) {
  160. tofile(L, 1); /* check that it's a valid file handle */
  161. aux_lines(L, 1, 0);
  162. return 1;
  163. }
  164. static int io_lines (lua_State *L) {
  165. if (lua_isnoneornil(L, 1)) { /* no arguments? */
  166. lua_pushstring(L, IO_INPUT);
  167. lua_rawget(L, lua_upvalueindex(1)); /* will iterate over default input */
  168. return f_lines(L);
  169. }
  170. else {
  171. FILE *f = fopen(luaL_check_string(L, 1), "r");
  172. luaL_arg_check(L, f, 1, strerror(errno));
  173. newfile(L, f);
  174. aux_lines(L, lua_gettop(L), 1);
  175. return 1;
  176. }
  177. }
  178. /*
  179. ** {======================================================
  180. ** READ
  181. ** =======================================================
  182. */
  183. static int read_number (lua_State *L, FILE *f) {
  184. lua_Number d;
  185. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  186. lua_pushnumber(L, d);
  187. return 1;
  188. }
  189. else return 0; /* read fails */
  190. }
  191. static int test_eof (lua_State *L, FILE *f) {
  192. int c = getc(f);
  193. ungetc(c, f);
  194. lua_pushlstring(L, NULL, 0);
  195. return (c != EOF);
  196. }
  197. static int read_line (lua_State *L, FILE *f) {
  198. luaL_Buffer b;
  199. luaL_buffinit(L, &b);
  200. for (;;) {
  201. size_t l;
  202. char *p = luaL_prepbuffer(&b);
  203. if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
  204. luaL_pushresult(&b); /* close buffer */
  205. return (lua_strlen(L, -1) > 0); /* check whether read something */
  206. }
  207. l = strlen(p);
  208. if (p[l-1] != '\n')
  209. luaL_addsize(&b, l);
  210. else {
  211. luaL_addsize(&b, l - 1); /* do not include `eol' */
  212. luaL_pushresult(&b); /* close buffer */
  213. return 1; /* read at least an `eol' */
  214. }
  215. }
  216. }
  217. static int read_chars (lua_State *L, FILE *f, size_t n) {
  218. size_t rlen; /* how much to read */
  219. size_t nr; /* number of chars actually read */
  220. luaL_Buffer b;
  221. luaL_buffinit(L, &b);
  222. rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
  223. do {
  224. char *p = luaL_prepbuffer(&b);
  225. if (rlen > n) rlen = n; /* cannot read more than asked */
  226. nr = fread(p, sizeof(char), rlen, f);
  227. luaL_addsize(&b, nr);
  228. n -= nr; /* still have to read `n' chars */
  229. } while (n > 0 && nr == rlen); /* until end of count or eof */
  230. luaL_pushresult(&b); /* close buffer */
  231. return (n == 0 || lua_strlen(L, -1) > 0);
  232. }
  233. static int g_read (lua_State *L, FILE *f, int first) {
  234. int nargs = lua_gettop(L) - 1;
  235. int success;
  236. int n;
  237. if (nargs == 0) { /* no arguments? */
  238. success = read_line(L, f);
  239. n = first+1; /* to return 1 result */
  240. }
  241. else { /* ensure stack space for all results and for auxlib's buffer */
  242. luaL_check_stack(L, nargs+LUA_MINSTACK, "too many arguments");
  243. success = 1;
  244. for (n = first; nargs-- && success; n++) {
  245. if (lua_type(L, n) == LUA_TNUMBER) {
  246. size_t l = (size_t)lua_tonumber(L, n);
  247. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  248. }
  249. else {
  250. const char *p = lua_tostring(L, n);
  251. if (!p || p[0] != '*')
  252. return luaL_error(L, "invalid `read' option");
  253. switch (p[1]) {
  254. case 'n': /* number */
  255. success = read_number(L, f);
  256. break;
  257. case 'l': /* line */
  258. success = read_line(L, f);
  259. break;
  260. case 'a': /* file */
  261. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  262. success = 1; /* always success */
  263. break;
  264. case 'w': /* word */
  265. return luaL_error(L, "obsolete option `*w'");
  266. default:
  267. return luaL_argerror(L, n, "invalid format");
  268. }
  269. }
  270. }
  271. }
  272. if (!success) {
  273. lua_pop(L, 1); /* remove last result */
  274. lua_pushnil(L); /* push nil instead */
  275. }
  276. return n - first;
  277. }
  278. static int io_read (lua_State *L) {
  279. return g_read(L, getiofile(L, IO_INPUT), 1);
  280. }
  281. static int f_read (lua_State *L) {
  282. return g_read(L, tofile(L, 1), 2);
  283. }
  284. static int io_readline (lua_State *L) {
  285. FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(2));
  286. if (f == NULL) /* file is already closed? */
  287. luaL_error(L, "file is already closed");
  288. if (read_line(L, f)) return 1;
  289. else { /* EOF */
  290. if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
  291. lua_settop(L, 0);
  292. lua_pushvalue(L, lua_upvalueindex(2));
  293. aux_close(L); /* close it */
  294. }
  295. return 0;
  296. }
  297. }
  298. /* }====================================================== */
  299. static int g_write (lua_State *L, FILE *f, int arg) {
  300. int nargs = lua_gettop(L) - 1;
  301. int status = 1;
  302. for (; nargs--; arg++) {
  303. if (lua_type(L, arg) == LUA_TNUMBER) {
  304. /* optimization: could be done exactly as for strings */
  305. status = status &&
  306. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  307. }
  308. else {
  309. size_t l;
  310. const char *s = luaL_check_lstr(L, arg, &l);
  311. status = status && (fwrite(s, sizeof(char), l, f) == l);
  312. }
  313. }
  314. pushresult(L, status);
  315. return 1;
  316. }
  317. static int io_write (lua_State *L) {
  318. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  319. }
  320. static int f_write (lua_State *L) {
  321. return g_write(L, tofile(L, 1), 2);
  322. }
  323. static int f_seek (lua_State *L) {
  324. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  325. static const char *const modenames[] = {"set", "cur", "end", NULL};
  326. FILE *f = tofile(L, 1);
  327. int op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
  328. long offset = luaL_opt_long(L, 3, 0);
  329. luaL_arg_check(L, op != -1, 2, "invalid mode");
  330. op = fseek(f, offset, mode[op]);
  331. if (op)
  332. return pushresult(L, 0); /* error */
  333. else {
  334. lua_pushnumber(L, ftell(f));
  335. return 1;
  336. }
  337. }
  338. static int io_flush (lua_State *L) {
  339. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0);
  340. }
  341. static int f_flush (lua_State *L) {
  342. return pushresult(L, fflush(tofile(L, 1)) == 0);
  343. }
  344. static const luaL_reg iolib[] = {
  345. {"input", io_input},
  346. {"output", io_output},
  347. {"lines", io_lines},
  348. {"close", io_close},
  349. {"flush", io_flush},
  350. {"open", io_open},
  351. {"popen", io_popen},
  352. {"read", io_read},
  353. {"tmpfile", io_tmpfile},
  354. {"write", io_write},
  355. {NULL, NULL}
  356. };
  357. static const luaL_reg flib[] = {
  358. {"flush", f_flush},
  359. {"read", f_read},
  360. {"lines", f_lines},
  361. {"seek", f_seek},
  362. {"write", f_write},
  363. {"close", io_close},
  364. {NULL, NULL}
  365. };
  366. static void createmeta (lua_State *L) {
  367. lua_pushliteral(L, FILEHANDLE);
  368. lua_newtable(L); /* push new metatable for file handles */
  369. /* close files when collected */
  370. lua_pushliteral(L, "__gc");
  371. lua_pushvalue(L, -2); /* push metatable (will be upvalue for `gc' method) */
  372. lua_pushcclosure(L, io_gc, 1);
  373. lua_rawset(L, -3); /* metatable.__gc = io_gc */
  374. /* file methods */
  375. lua_pushliteral(L, "__index");
  376. lua_pushvalue(L, -2); /* push metatable */
  377. lua_rawset(L, -3); /* metatable.__index = metatable */
  378. lua_pushvalue(L, -1); /* push metatable (will be upvalue for library) */
  379. luaL_openlib(L, flib, 1);
  380. lua_rawset(L, LUA_REGISTRYINDEX); /* registry.FILEHANDLE = metatable */
  381. }
  382. /* }====================================================== */
  383. /*
  384. ** {======================================================
  385. ** Other O.S. Operations
  386. ** =======================================================
  387. */
  388. static int io_execute (lua_State *L) {
  389. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  390. return 1;
  391. }
  392. static int io_remove (lua_State *L) {
  393. return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  394. }
  395. static int io_rename (lua_State *L) {
  396. return pushresult(L, rename(luaL_check_string(L, 1),
  397. luaL_check_string(L, 2)) == 0);
  398. }
  399. static int io_tmpname (lua_State *L) {
  400. char buff[L_tmpnam];
  401. if (tmpnam(buff) != buff)
  402. return luaL_error(L, "unable to generate a unique filename");
  403. lua_pushstring(L, buff);
  404. return 1;
  405. }
  406. static int io_getenv (lua_State *L) {
  407. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  408. return 1;
  409. }
  410. static int io_clock (lua_State *L) {
  411. lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
  412. return 1;
  413. }
  414. /*
  415. ** {======================================================
  416. ** Time/Date operations
  417. ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
  418. ** wday=%w+1, yday=%j, isdst=? }
  419. ** =======================================================
  420. */
  421. static void setfield (lua_State *L, const char *key, int value) {
  422. lua_pushstring(L, key);
  423. lua_pushnumber(L, value);
  424. lua_rawset(L, -3);
  425. }
  426. static void setboolfield (lua_State *L, const char *key, int value) {
  427. lua_pushstring(L, key);
  428. lua_pushboolean(L, value);
  429. lua_rawset(L, -3);
  430. }
  431. static int getboolfield (lua_State *L, const char *key) {
  432. int res;
  433. lua_pushstring(L, key);
  434. lua_gettable(L, -2);
  435. res = lua_toboolean(L, -1);
  436. lua_pop(L, 1);
  437. return res;
  438. }
  439. static int getfield (lua_State *L, const char *key, int d) {
  440. int res;
  441. lua_pushstring(L, key);
  442. lua_gettable(L, -2);
  443. if (lua_isnumber(L, -1))
  444. res = (int)(lua_tonumber(L, -1));
  445. else {
  446. if (d == -2)
  447. return luaL_error(L, "field `%s' missing in date table", key);
  448. res = d;
  449. }
  450. lua_pop(L, 1);
  451. return res;
  452. }
  453. static int io_date (lua_State *L) {
  454. const char *s = luaL_opt_string(L, 1, "%c");
  455. time_t t = (time_t)(luaL_opt_number(L, 2, -1));
  456. struct tm *stm;
  457. if (t == (time_t)(-1)) /* no time given? */
  458. t = time(NULL); /* use current time */
  459. if (*s == '!') { /* UTC? */
  460. stm = gmtime(&t);
  461. s++; /* skip `!' */
  462. }
  463. else
  464. stm = localtime(&t);
  465. if (stm == NULL) /* invalid date? */
  466. lua_pushnil(L);
  467. else if (strcmp(s, "*t") == 0) {
  468. lua_newtable(L);
  469. setfield(L, "sec", stm->tm_sec);
  470. setfield(L, "min", stm->tm_min);
  471. setfield(L, "hour", stm->tm_hour);
  472. setfield(L, "day", stm->tm_mday);
  473. setfield(L, "month", stm->tm_mon+1);
  474. setfield(L, "year", stm->tm_year+1900);
  475. setfield(L, "wday", stm->tm_wday+1);
  476. setfield(L, "yday", stm->tm_yday+1);
  477. setboolfield(L, "isdst", stm->tm_isdst);
  478. }
  479. else {
  480. char b[256];
  481. if (strftime(b, sizeof(b), s, stm))
  482. lua_pushstring(L, b);
  483. else
  484. return luaL_error(L, "`date' format too long");
  485. }
  486. return 1;
  487. }
  488. static int io_time (lua_State *L) {
  489. if (lua_isnoneornil(L, 1)) /* called without args? */
  490. lua_pushnumber(L, time(NULL)); /* return current time */
  491. else {
  492. time_t t;
  493. struct tm ts;
  494. luaL_check_type(L, 1, LUA_TTABLE);
  495. lua_settop(L, 1); /* make sure table is at the top */
  496. ts.tm_sec = getfield(L, "sec", 0);
  497. ts.tm_min = getfield(L, "min", 0);
  498. ts.tm_hour = getfield(L, "hour", 12);
  499. ts.tm_mday = getfield(L, "day", -2);
  500. ts.tm_mon = getfield(L, "month", -2) - 1;
  501. ts.tm_year = getfield(L, "year", -2) - 1900;
  502. ts.tm_isdst = getboolfield(L, "isdst");
  503. t = mktime(&ts);
  504. if (t == (time_t)(-1))
  505. lua_pushnil(L);
  506. else
  507. lua_pushnumber(L, t);
  508. }
  509. return 1;
  510. }
  511. static int io_difftime (lua_State *L) {
  512. lua_pushnumber(L, difftime((time_t)(luaL_check_number(L, 1)),
  513. (time_t)(luaL_opt_number(L, 2, 0))));
  514. return 1;
  515. }
  516. /* }====================================================== */
  517. static int io_setloc (lua_State *L) {
  518. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  519. LC_NUMERIC, LC_TIME};
  520. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  521. "numeric", "time", NULL};
  522. const char *l = lua_tostring(L, 1);
  523. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  524. luaL_arg_check(L, l || lua_isnoneornil(L, 1), 1, "string expected");
  525. luaL_arg_check(L, op != -1, 2, "invalid option");
  526. lua_pushstring(L, setlocale(cat[op], l));
  527. return 1;
  528. }
  529. static int io_exit (lua_State *L) {
  530. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  531. return 0; /* to avoid warnings */
  532. }
  533. static const luaL_reg syslib[] = {
  534. {"clock", io_clock},
  535. {"date", io_date},
  536. {"difftime", io_difftime},
  537. {"execute", io_execute},
  538. {"exit", io_exit},
  539. {"getenv", io_getenv},
  540. {"remove", io_remove},
  541. {"rename", io_rename},
  542. {"setlocale", io_setloc},
  543. {"time", io_time},
  544. {"tmpname", io_tmpname},
  545. {NULL, NULL}
  546. };
  547. /* }====================================================== */
  548. LUALIB_API int lua_iolibopen (lua_State *L) {
  549. createmeta(L);
  550. luaL_opennamedlib(L, LUA_OSLIBNAME, syslib, 0);
  551. lua_pushliteral(L, FILEHANDLE); /* S: FH */
  552. lua_rawget(L, LUA_REGISTRYINDEX); /* S: mt */
  553. lua_pushvalue(L, -1); /* S: mt mt */
  554. luaL_opennamedlib(L, LUA_IOLIBNAME, iolib, 1); /* S: mt */
  555. lua_pushliteral(L, LUA_IOLIBNAME); /* S: `io' mt */
  556. lua_gettable(L, LUA_GLOBALSINDEX); /* S: io mt */
  557. /* put predefined file handles into `io' table */
  558. registerfile(L, stdin, "stdin", IO_INPUT);
  559. registerfile(L, stdout, "stdout", IO_OUTPUT);
  560. registerfile(L, stderr, "stderr", NULL);
  561. lua_pop(L, 2); /* S: empty */
  562. return 0;
  563. }