liolib.c 16 KB

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