liolib.c 16 KB

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