liolib.c 15 KB

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