liolib.c 15 KB

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