liolib.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /*
  2. ** $Id: liolib.c,v 2.4 2002/05/02 17:12:27 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. luaL_verror(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. return luaL_verror(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. return luaL_verror(L, "obsolete option `*w'");
  224. break;
  225. default:
  226. return luaL_argerror(L, n, "invalid format");
  227. }
  228. }
  229. }
  230. }
  231. if (!success) {
  232. lua_pop(L, 1); /* remove last result */
  233. lua_pushnil(L); /* push nil instead */
  234. }
  235. return n - first;
  236. }
  237. static int io_read (lua_State *L) {
  238. return g_read(L, getiofile(L, IO_INPUT), 1);
  239. }
  240. static int f_read (lua_State *L) {
  241. return g_read(L, tofile(L, 1), 2);
  242. }
  243. /* }====================================================== */
  244. static int g_write (lua_State *L, FILE *f, int arg) {
  245. int nargs = lua_gettop(L) - 1;
  246. int status = 1;
  247. for (; nargs--; arg++) {
  248. if (lua_type(L, arg) == LUA_TNUMBER) {
  249. /* optimization: could be done exactly as for strings */
  250. status = status &&
  251. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  252. }
  253. else {
  254. size_t l;
  255. const char *s = luaL_check_lstr(L, arg, &l);
  256. status = status && (fwrite(s, sizeof(char), l, f) == l);
  257. }
  258. }
  259. pushresult(L, status);
  260. return 1;
  261. }
  262. static int io_write (lua_State *L) {
  263. return g_write(L, getiofile(L, IO_OUTPUT), 1);
  264. }
  265. static int f_write (lua_State *L) {
  266. return g_write(L, tofile(L, 1), 2);
  267. }
  268. static int f_seek (lua_State *L) {
  269. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  270. static const char *const modenames[] = {"set", "cur", "end", NULL};
  271. FILE *f = tofile(L, 1);
  272. int op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
  273. long offset = luaL_opt_long(L, 3, 0);
  274. luaL_arg_check(L, op != -1, 2, "invalid mode");
  275. op = fseek(f, offset, mode[op]);
  276. if (op)
  277. return pushresult(L, 0); /* error */
  278. else {
  279. lua_pushnumber(L, ftell(f));
  280. return 1;
  281. }
  282. }
  283. static int io_flush (lua_State *L) {
  284. return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0);
  285. }
  286. static int f_flush (lua_State *L) {
  287. return pushresult(L, fflush(tofile(L, 1)) == 0);
  288. }
  289. static const luaL_reg iolib[] = {
  290. {"input", io_input},
  291. {"output", io_output},
  292. {"close", io_close},
  293. {"flush", io_flush},
  294. {"open", io_open},
  295. {"popen", io_popen},
  296. {"read", io_read},
  297. {"tmpfile", io_tmpfile},
  298. {"write", io_write},
  299. {NULL, NULL}
  300. };
  301. static const luaL_reg flib[] = {
  302. {"flush", f_flush},
  303. {"read", f_read},
  304. {"seek", f_seek},
  305. {"write", f_write},
  306. {NULL, NULL}
  307. };
  308. static void createmeta (lua_State *L) {
  309. lua_pushliteral(L, FILEHANDLE); /* S: FH */
  310. lua_newtable(L); /* S: mt FH */
  311. /* close files when collected */
  312. lua_pushliteral(L, "__gc"); /* S: `gc' mt FH */
  313. lua_pushvalue(L, -2); /* S: mt `gc' mt FH */
  314. lua_pushcclosure(L, io_close, 1); /* S: close `gc' mt FH */
  315. lua_rawset(L, -3); /* S: mt FH */
  316. /* file methods */
  317. lua_pushliteral(L, "__gettable"); /* S: `gettable' mt FH */
  318. lua_pushvalue(L, -2); /* S: mt `gettable' mt FH */
  319. lua_rawset(L, -3); /* S: mt FH */
  320. lua_pushvalue(L, -1); /* S: mt mt FH */
  321. luaL_openlib(L, flib, 1); /* S: mt FH */
  322. /* put new metatable into registry */
  323. lua_rawset(L, LUA_REGISTRYINDEX); /* S: empty */
  324. /* meta table for CLOSEDFILEHANDLE */
  325. lua_pushliteral(L, CLOSEDFILEHANDLE);
  326. lua_newtable(L);
  327. lua_rawset(L, LUA_REGISTRYINDEX);
  328. }
  329. /* }====================================================== */
  330. /*
  331. ** {======================================================
  332. ** Other O.S. Operations
  333. ** =======================================================
  334. */
  335. static int io_execute (lua_State *L) {
  336. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  337. return 1;
  338. }
  339. static int io_remove (lua_State *L) {
  340. return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  341. }
  342. static int io_rename (lua_State *L) {
  343. return pushresult(L, rename(luaL_check_string(L, 1),
  344. luaL_check_string(L, 2)) == 0);
  345. }
  346. static int io_tmpname (lua_State *L) {
  347. char buff[L_tmpnam];
  348. if (tmpnam(buff) != buff)
  349. return luaL_verror(L, "unable to generate a unique filename");
  350. lua_pushstring(L, buff);
  351. return 1;
  352. }
  353. static int io_getenv (lua_State *L) {
  354. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  355. return 1;
  356. }
  357. static int io_clock (lua_State *L) {
  358. lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
  359. return 1;
  360. }
  361. /*
  362. ** {======================================================
  363. ** Time/Date operations
  364. ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
  365. ** wday=%w+1, yday=%j, isdst=? }
  366. ** =======================================================
  367. */
  368. static void setfield (lua_State *L, const char *key, int value) {
  369. lua_pushstring(L, key);
  370. lua_pushnumber(L, value);
  371. lua_rawset(L, -3);
  372. }
  373. static int getfield (lua_State *L, const char *key, int d) {
  374. int res;
  375. lua_pushstring(L, key);
  376. lua_gettable(L, -2);
  377. if (lua_isnumber(L, -1))
  378. res = (int)(lua_tonumber(L, -1));
  379. else {
  380. if (d == -2)
  381. return luaL_verror(L, "field `%s' missing in date table", key);
  382. res = d;
  383. }
  384. lua_pop(L, 1);
  385. return res;
  386. }
  387. static int io_date (lua_State *L) {
  388. const char *s = luaL_opt_string(L, 1, "%c");
  389. time_t t = (time_t)(luaL_opt_number(L, 2, -1));
  390. struct tm *stm;
  391. if (t == (time_t)(-1)) /* no time given? */
  392. t = time(NULL); /* use current time */
  393. if (*s == '!') { /* UTC? */
  394. stm = gmtime(&t);
  395. s++; /* skip `!' */
  396. }
  397. else
  398. stm = localtime(&t);
  399. if (stm == NULL) /* invalid date? */
  400. lua_pushnil(L);
  401. else if (strcmp(s, "*t") == 0) {
  402. lua_newtable(L);
  403. setfield(L, "sec", stm->tm_sec);
  404. setfield(L, "min", stm->tm_min);
  405. setfield(L, "hour", stm->tm_hour);
  406. setfield(L, "day", stm->tm_mday);
  407. setfield(L, "month", stm->tm_mon+1);
  408. setfield(L, "year", stm->tm_year+1900);
  409. setfield(L, "wday", stm->tm_wday+1);
  410. setfield(L, "yday", stm->tm_yday+1);
  411. setfield(L, "isdst", stm->tm_isdst);
  412. }
  413. else {
  414. char b[256];
  415. if (strftime(b, sizeof(b), s, stm))
  416. lua_pushstring(L, b);
  417. else
  418. return luaL_verror(L, "invalid `date' format");
  419. }
  420. return 1;
  421. }
  422. static int io_time (lua_State *L) {
  423. if (lua_isnoneornil(L, 1)) /* called without args? */
  424. lua_pushnumber(L, time(NULL)); /* return current time */
  425. else {
  426. time_t t;
  427. struct tm ts;
  428. luaL_check_type(L, 1, LUA_TTABLE);
  429. lua_settop(L, 1); /* make sure table is at the top */
  430. ts.tm_sec = getfield(L, "sec", 0);
  431. ts.tm_min = getfield(L, "min", 0);
  432. ts.tm_hour = getfield(L, "hour", 12);
  433. ts.tm_mday = getfield(L, "day", -2);
  434. ts.tm_mon = getfield(L, "month", -2)-1;
  435. ts.tm_year = getfield(L, "year", -2)-1900;
  436. ts.tm_isdst = getfield(L, "isdst", -1);
  437. t = mktime(&ts);
  438. if (t == (time_t)(-1))
  439. lua_pushnil(L);
  440. else
  441. lua_pushnumber(L, t);
  442. }
  443. return 1;
  444. }
  445. static int io_difftime (lua_State *L) {
  446. lua_pushnumber(L, difftime((time_t)(luaL_check_number(L, 1)),
  447. (time_t)(luaL_opt_number(L, 2, 0))));
  448. return 1;
  449. }
  450. /* }====================================================== */
  451. static int io_setloc (lua_State *L) {
  452. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  453. LC_NUMERIC, LC_TIME};
  454. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  455. "numeric", "time", NULL};
  456. const char *l = lua_tostring(L, 1);
  457. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  458. luaL_arg_check(L, l || lua_isnoneornil(L, 1), 1, "string expected");
  459. luaL_arg_check(L, op != -1, 2, "invalid option");
  460. lua_pushstring(L, setlocale(cat[op], l));
  461. return 1;
  462. }
  463. static int io_exit (lua_State *L) {
  464. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  465. return 0; /* to avoid warnings */
  466. }
  467. static const luaL_reg syslib[] = {
  468. {"clock", io_clock},
  469. {"date", io_date},
  470. {"difftime", io_difftime},
  471. {"execute", io_execute},
  472. {"exit", io_exit},
  473. {"getenv", io_getenv},
  474. {"remove", io_remove},
  475. {"rename", io_rename},
  476. {"setlocale", io_setloc},
  477. {"time", io_time},
  478. {"tmpname", io_tmpname},
  479. {NULL, NULL}
  480. };
  481. /* }====================================================== */
  482. LUALIB_API int lua_iolibopen (lua_State *L) {
  483. createmeta(L);
  484. luaL_opennamedlib(L, "os", syslib, 0);
  485. lua_pushliteral(L, FILEHANDLE); /* S: FH */
  486. lua_rawget(L, LUA_REGISTRYINDEX); /* S: mt */
  487. lua_pushvalue(L, -1); /* S: mt mt */
  488. luaL_opennamedlib(L, "io", iolib, 1); /* S: mt */
  489. lua_pushliteral(L, "io"); /* S: `io' mt */
  490. lua_gettable(L, LUA_GLOBALSINDEX); /* S: io mt */
  491. /* put predefined file handles into `io' table */
  492. registerfile(L, stdin, "stdin", IO_INPUT);
  493. registerfile(L, stdout, "stdout", IO_OUTPUT);
  494. registerfile(L, stderr, "stderr", NULL);
  495. lua_pop(L, 2); /* S: empty */
  496. return 0;
  497. }