liolib.c 15 KB

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