liolib.c 15 KB

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