liolib.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. ** $Id: liolib.c,v 1.103 2001/02/02 19:02:40 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include "lua.h"
  12. #include "lauxlib.h"
  13. #include "luadebug.h"
  14. #include "lualib.h"
  15. #ifndef OLD_ANSI
  16. #include <errno.h>
  17. #include <locale.h>
  18. #endif
  19. #ifndef l_realloc
  20. #define l_malloc(s) malloc(s)
  21. #define l_realloc(b,os,s) realloc(b, s)
  22. #define l_free(b, os) free(b)
  23. #endif
  24. #ifdef POPEN
  25. /* FILE *popen();
  26. int pclose(); */
  27. #define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
  28. #else
  29. /* no support for popen */
  30. #define popen(x,y) NULL /* that is, popen always fails */
  31. #define CLOSEFILE(L, f) (fclose(f))
  32. #endif
  33. #define INFILE 0
  34. #define OUTFILE 1
  35. #define NOFILE 2
  36. #define FILEHANDLE "FileHandle"
  37. static const char *const filenames[] = {"_INPUT", "_OUTPUT"};
  38. static int pushresult (lua_State *L, int i) {
  39. if (i) {
  40. lua_pushuserdata(L, NULL);
  41. return 1;
  42. }
  43. else {
  44. lua_pushnil(L);
  45. lua_pushstring(L, strerror(errno));
  46. lua_pushnumber(L, errno);
  47. return 3;
  48. }
  49. }
  50. /*
  51. ** {======================================================
  52. ** FILE Operations
  53. ** =======================================================
  54. */
  55. #define checkfile(L,f) (strcmp(lua_xtype(L,(f)), FILEHANDLE) == 0)
  56. static FILE *getopthandle (lua_State *L, int inout) {
  57. FILE *p = (FILE *)lua_touserdata(L, 1);
  58. if (p != NULL) { /* is it a userdata ? */
  59. if (!checkfile(L, 1)) {
  60. if (strcmp(lua_xtype(L, 1), "ClosedFileHandle") == 0)
  61. luaL_argerror(L, 1, "file is closed");
  62. else
  63. luaL_argerror(L, 1, "(invalid value)");
  64. }
  65. /* move it to stack top */
  66. lua_pushvalue(L, 1); lua_remove(L, 1);
  67. }
  68. else if (inout != NOFILE) { /* try global value */
  69. lua_getglobal(L, filenames[inout]);
  70. if (!checkfile(L,-1))
  71. luaL_verror(L, "global variable `%.10s' is not a valid file handle",
  72. filenames[inout]);
  73. p = (FILE *)lua_touserdata(L, -1);
  74. }
  75. return p; /* leave handle at stack top to avoid GC */
  76. }
  77. static void pushfile (lua_State *L, FILE *f) {
  78. lua_pushusertag(L, f, lua_type2tag(L, FILEHANDLE));
  79. }
  80. static void setfilebyname (lua_State *L, FILE *f, const char *name) {
  81. pushfile(L, f);
  82. lua_setglobal(L, name);
  83. }
  84. #define setfile(L,f,inout) (setfilebyname(L,f,filenames[inout]))
  85. static int setreturn (lua_State *L, FILE *f, int inout) {
  86. if (f == NULL)
  87. return pushresult(L, 0);
  88. else {
  89. if (inout != NOFILE)
  90. setfile(L, f, inout);
  91. pushfile(L, f);
  92. return 1;
  93. }
  94. }
  95. static int closefile (lua_State *L, FILE *f) {
  96. if (f == stdin || f == stdout || f == stderr)
  97. return 1;
  98. else {
  99. pushfile(L, f);
  100. lua_settag(L, lua_type2tag(L, "ClosedFileHandle"));
  101. return (CLOSEFILE(L, f) == 0);
  102. }
  103. }
  104. static int io_close (lua_State *L) {
  105. FILE *f = (FILE *)luaL_check_userdata(L, 1, FILEHANDLE);
  106. return pushresult(L, closefile(L, f));
  107. }
  108. static int file_collect (lua_State *L) {
  109. FILE *f = (FILE *)luaL_check_userdata(L, 1, FILEHANDLE);
  110. if (f != stdin && f != stdout && f != stderr)
  111. CLOSEFILE(L, f);
  112. return 0;
  113. }
  114. static int io_open (lua_State *L) {
  115. FILE *f = fopen(luaL_check_string(L, 1), luaL_check_string(L, 2));
  116. return setreturn(L, f, NOFILE);
  117. }
  118. static int io_tmpfile (lua_State *L) {
  119. return setreturn(L, tmpfile(), NOFILE);
  120. }
  121. static int io_fromto (lua_State *L, int inout, const char *mode) {
  122. FILE *current;
  123. if (lua_isnull(L, 1)) {
  124. closefile(L, getopthandle(L, inout));
  125. current = (inout == 0) ? stdin : stdout;
  126. }
  127. else if (checkfile(L, 1)) /* deprecated option */
  128. current = (FILE *)lua_touserdata(L, 1);
  129. else {
  130. const char *s = luaL_check_string(L, 1);
  131. current = (*s == '|') ? popen(s+1, mode) : fopen(s, mode);
  132. }
  133. return setreturn(L, current, inout);
  134. }
  135. static int io_readfrom (lua_State *L) {
  136. return io_fromto(L, INFILE, "r");
  137. }
  138. static int io_writeto (lua_State *L) {
  139. return io_fromto(L, OUTFILE, "w");
  140. }
  141. static int io_appendto (lua_State *L) {
  142. FILE *current = fopen(luaL_check_string(L, 1), "a");
  143. return setreturn(L, current, OUTFILE);
  144. }
  145. /*
  146. ** {======================================================
  147. ** READ
  148. ** =======================================================
  149. */
  150. static int read_number (lua_State *L, FILE *f) {
  151. double d;
  152. if (fscanf(f, "%lf", &d) == 1) {
  153. lua_pushnumber(L, d);
  154. return 1;
  155. }
  156. else return 0; /* read fails */
  157. }
  158. static int read_word (lua_State *L, FILE *f) {
  159. int c;
  160. luaL_Buffer b;
  161. luaL_buffinit(L, &b);
  162. do { c = fgetc(f); } while (isspace(c)); /* skip spaces */
  163. while (c != EOF && !isspace(c)) {
  164. luaL_putchar(&b, c);
  165. c = fgetc(f);
  166. }
  167. ungetc(c, f);
  168. luaL_pushresult(&b); /* close buffer */
  169. return (lua_strlen(L, -1) > 0);
  170. }
  171. static int read_line (lua_State *L, FILE *f) {
  172. int n = 0;
  173. luaL_Buffer b;
  174. luaL_buffinit(L, &b);
  175. for (;;) {
  176. char *p = luaL_prepbuffer(&b);
  177. if (!fgets(p, LUAL_BUFFERSIZE, f)) /* read fails? */
  178. break;
  179. n = strlen(p);
  180. if (p[n-1] != '\n')
  181. luaL_addsize(&b, n);
  182. else {
  183. luaL_addsize(&b, n-1); /* do not add the `\n' */
  184. break;
  185. }
  186. }
  187. luaL_pushresult(&b); /* close buffer */
  188. return (n > 0); /* read something? */
  189. }
  190. static void read_file (lua_State *L, FILE *f) {
  191. size_t len = 0;
  192. size_t size = LUAL_BUFFERSIZE;
  193. size_t oldsize = 0;
  194. char *buffer = NULL;
  195. for (;;) {
  196. char *newbuffer = (char *)l_realloc(buffer, oldsize, size);
  197. if (newbuffer == NULL) {
  198. l_free(buffer, oldsize);
  199. lua_error(L, "not enough memory to read a file");
  200. }
  201. buffer = newbuffer;
  202. len += fread(buffer+len, sizeof(char), size-len, f);
  203. if (len < size) break; /* did not read all it could */
  204. oldsize = size;
  205. size *= 2;
  206. }
  207. lua_pushlstring(L, buffer, len);
  208. l_free(buffer, size);
  209. }
  210. static int read_chars (lua_State *L, FILE *f, size_t n) {
  211. char *buffer;
  212. size_t n1;
  213. char statbuff[LUAL_BUFFERSIZE];
  214. if (n <= LUAL_BUFFERSIZE)
  215. buffer = statbuff;
  216. else {
  217. buffer = (char *)l_malloc(n);
  218. if (buffer == NULL)
  219. lua_error(L, "not enough memory to read a file");
  220. }
  221. n1 = fread(buffer, sizeof(char), n, f);
  222. lua_pushlstring(L, buffer, n1);
  223. if (buffer != statbuff) l_free(buffer, n);
  224. return (n1 > 0 || n == 0);
  225. }
  226. static int io_read (lua_State *L) {
  227. FILE *f = getopthandle(L, INFILE);
  228. int nargs = lua_gettop(L)-1;
  229. int success;
  230. int n;
  231. if (nargs == 0) { /* no arguments? */
  232. success = read_line(L, f);
  233. n = 2; /* will return n-1 results */
  234. }
  235. else { /* ensure stack space for all results and for auxlib's buffer */
  236. luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
  237. success = 1;
  238. for (n = 1; n<=nargs && success; n++) {
  239. if (lua_type(L, n) == LUA_TNUMBER)
  240. success = read_chars(L, f, (size_t)lua_tonumber(L, n));
  241. else {
  242. const char *p = lua_tostring(L, n);
  243. if (!p || p[0] != '*')
  244. lua_error(L, "invalid `read' option");
  245. switch (p[1]) {
  246. case 'n': /* number */
  247. success = read_number(L, f);
  248. break;
  249. case 'l': /* line */
  250. success = read_line(L, f);
  251. break;
  252. case 'a': /* file */
  253. read_file(L, f);
  254. success = 1; /* always success */
  255. break;
  256. case 'w': /* word */
  257. success = read_word(L, f);
  258. break;
  259. default:
  260. luaL_argerror(L, n, "invalid format");
  261. success = 0; /* to avoid warnings */
  262. }
  263. }
  264. }
  265. }
  266. if (!success) {
  267. lua_pop(L, 1); /* remove last result */
  268. lua_pushnil(L); /* push nil instead */
  269. }
  270. return n - 1;
  271. }
  272. /* }====================================================== */
  273. static int io_write (lua_State *L) {
  274. FILE *f = getopthandle(L, OUTFILE);
  275. int nargs = lua_gettop(L)-1;
  276. int arg;
  277. int status = 1;
  278. for (arg=1; arg<=nargs; arg++) {
  279. if (lua_type(L, arg) == LUA_TNUMBER) { /* LUA_NUMBER */
  280. /* optimization: could be done exactly as for strings */
  281. status = status && fprintf(f, "%.16g", lua_tonumber(L, arg)) > 0;
  282. }
  283. else {
  284. size_t l;
  285. const char *s = luaL_check_lstr(L, arg, &l);
  286. status = status && (fwrite(s, sizeof(char), l, f) == l);
  287. }
  288. }
  289. pushresult(L, status);
  290. return 1;
  291. }
  292. static int io_seek (lua_State *L) {
  293. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  294. static const char *const modenames[] = {"set", "cur", "end", NULL};
  295. FILE *f = (FILE *)luaL_check_userdata(L, 1, FILEHANDLE);
  296. int op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
  297. long offset = luaL_opt_long(L, 3, 0);
  298. luaL_arg_check(L, op != -1, 2, "invalid mode");
  299. op = fseek(f, offset, mode[op]);
  300. if (op)
  301. return pushresult(L, 0); /* error */
  302. else {
  303. lua_pushnumber(L, ftell(f));
  304. return 1;
  305. }
  306. }
  307. static int io_flush (lua_State *L) {
  308. FILE *f = getopthandle(L, NOFILE);
  309. luaL_arg_check(L, f || lua_isnull(L, 1), 1, "invalid file handle");
  310. return pushresult(L, fflush(f) == 0);
  311. }
  312. /* }====================================================== */
  313. /*
  314. ** {======================================================
  315. ** Other O.S. Operations
  316. ** =======================================================
  317. */
  318. static int io_execute (lua_State *L) {
  319. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  320. return 1;
  321. }
  322. static int io_remove (lua_State *L) {
  323. return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  324. }
  325. static int io_rename (lua_State *L) {
  326. return pushresult(L, rename(luaL_check_string(L, 1),
  327. luaL_check_string(L, 2)) == 0);
  328. }
  329. static int io_tmpname (lua_State *L) {
  330. char buff[L_tmpnam];
  331. if (tmpnam(buff) != buff)
  332. lua_error(L, "unable to generate a unique filename");
  333. lua_pushstring(L, buff);
  334. return 1;
  335. }
  336. static int io_getenv (lua_State *L) {
  337. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  338. return 1;
  339. }
  340. static int io_clock (lua_State *L) {
  341. lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
  342. return 1;
  343. }
  344. /*
  345. ** {======================================================
  346. ** Time/Date operations
  347. ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
  348. ** wday=%w+1, yday=%j, isdst=? }
  349. ** =======================================================
  350. */
  351. static void setfield (lua_State *L, const char *key, int value) {
  352. lua_pushstring(L, key);
  353. lua_pushnumber(L, value);
  354. lua_rawset(L, -3);
  355. }
  356. static int getfield (lua_State *L, const char *key, int d) {
  357. int res;
  358. lua_pushstring(L, key);
  359. lua_rawget(L, -2);
  360. if (lua_isnumber(L, -1))
  361. res = (int)lua_tonumber(L, -1);
  362. else {
  363. if (d == -2)
  364. luaL_verror(L, "field `%.20s' missing in date table", key);
  365. res = d;
  366. }
  367. lua_pop(L, 1);
  368. return res;
  369. }
  370. static int io_date (lua_State *L) {
  371. const char *s = luaL_opt_string(L, 1, "%c");
  372. time_t t = (time_t)luaL_opt_number(L, 2, -1);
  373. struct tm *stm;
  374. if (t == (time_t)-1) /* no time given? */
  375. t = time(NULL); /* use current time */
  376. if (*s == '!') { /* UTC? */
  377. stm = gmtime(&t);
  378. s++; /* skip `!' */
  379. }
  380. else
  381. stm = localtime(&t);
  382. if (stm == NULL) /* invalid date? */
  383. lua_pushnil(L);
  384. else if (strcmp(s, "*t") == 0) {
  385. lua_newtable(L);
  386. setfield(L, "sec", stm->tm_sec);
  387. setfield(L, "min", stm->tm_min);
  388. setfield(L, "hour", stm->tm_hour);
  389. setfield(L, "day", stm->tm_mday);
  390. setfield(L, "month", stm->tm_mon+1);
  391. setfield(L, "year", stm->tm_year+1900);
  392. setfield(L, "wday", stm->tm_wday+1);
  393. setfield(L, "yday", stm->tm_yday+1);
  394. setfield(L, "isdst", stm->tm_isdst);
  395. }
  396. else {
  397. char b[256];
  398. if (strftime(b, sizeof(b), s, stm))
  399. lua_pushstring(L, b);
  400. else
  401. lua_error(L, "invalid `date' format");
  402. }
  403. return 1;
  404. }
  405. static int io_time (lua_State *L) {
  406. if (lua_isnull(L, 1)) /* called without args? */
  407. lua_pushnumber(L, time(NULL)); /* return current time */
  408. else {
  409. time_t t;
  410. struct tm ts;
  411. luaL_checktype(L, 1, LUA_TTABLE);
  412. lua_settop(L, 1); /* make sure table is at the top */
  413. ts.tm_sec = getfield(L, "sec", 0);
  414. ts.tm_min = getfield(L, "min", 0);
  415. ts.tm_hour = getfield(L, "hour", 12);
  416. ts.tm_mday = getfield(L, "day", -2);
  417. ts.tm_mon = getfield(L, "month", -2)-1;
  418. ts.tm_year = getfield(L, "year", -2)-1900;
  419. ts.tm_isdst = getfield(L, "isdst", -1);
  420. t = mktime(&ts);
  421. if (t == (time_t)-1)
  422. lua_pushnil(L);
  423. else
  424. lua_pushnumber(L, t);
  425. }
  426. return 1;
  427. }
  428. static int io_difftime (lua_State *L) {
  429. lua_pushnumber(L, difftime((time_t)luaL_check_number(L, 1),
  430. (time_t)luaL_opt_number(L, 2, 0)));
  431. return 1;
  432. }
  433. /* }====================================================== */
  434. static int io_setloc (lua_State *L) {
  435. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  436. LC_NUMERIC, LC_TIME};
  437. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  438. "numeric", "time", NULL};
  439. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  440. luaL_arg_check(L, op != -1, 2, "invalid option");
  441. lua_pushstring(L, setlocale(cat[op], luaL_check_string(L, 1)));
  442. return 1;
  443. }
  444. static int io_exit (lua_State *L) {
  445. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  446. return 0; /* to avoid warnings */
  447. }
  448. /* }====================================================== */
  449. static int io_debug (lua_State *L) {
  450. for (;;) {
  451. char buffer[250];
  452. fprintf(stderr, "lua_debug> ");
  453. if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
  454. strcmp(buffer, "cont\n") == 0)
  455. return 0;
  456. lua_dostring(L, buffer);
  457. lua_settop(L, 0); /* remove eventual returns */
  458. }
  459. }
  460. #define LEVELS1 12 /* size of the first part of the stack */
  461. #define LEVELS2 10 /* size of the second part of the stack */
  462. static int errorfb (lua_State *L) {
  463. int level = 1; /* skip level 0 (it's this function) */
  464. int firstpart = 1; /* still before eventual `...' */
  465. lua_Debug ar;
  466. luaL_Buffer b;
  467. luaL_buffinit(L, &b);
  468. luaL_addstring(&b, "error: ");
  469. luaL_addstring(&b, luaL_check_string(L, 1));
  470. luaL_addstring(&b, "\n");
  471. while (lua_getstack(L, level++, &ar)) {
  472. char buff[120]; /* enough to fit following `sprintf's */
  473. if (level == 2)
  474. luaL_addstring(&b, "stack traceback:\n");
  475. else if (level > LEVELS1 && firstpart) {
  476. /* no more than `LEVELS2' more levels? */
  477. if (!lua_getstack(L, level+LEVELS2, &ar))
  478. level--; /* keep going */
  479. else {
  480. luaL_addstring(&b, " ...\n"); /* too many levels */
  481. while (lua_getstack(L, level+LEVELS2, &ar)) /* find last levels */
  482. level++;
  483. }
  484. firstpart = 0;
  485. continue;
  486. }
  487. sprintf(buff, "%4d: ", level-1);
  488. luaL_addstring(&b, buff);
  489. lua_getinfo(L, "Snl", &ar);
  490. switch (*ar.namewhat) {
  491. case 'g': case 'l': /* global, local */
  492. sprintf(buff, "function `%.50s'", ar.name);
  493. break;
  494. case 'f': /* field */
  495. sprintf(buff, "method `%.50s'", ar.name);
  496. break;
  497. case 't': /* tag method */
  498. sprintf(buff, "`%.50s' tag method", ar.name);
  499. break;
  500. default: {
  501. if (*ar.what == 'm') /* main? */
  502. sprintf(buff, "main of %.70s", ar.short_src);
  503. else if (*ar.what == 'C') /* C function? */
  504. sprintf(buff, "%.70s", ar.short_src);
  505. else
  506. sprintf(buff, "function <%d:%.70s>", ar.linedefined, ar.short_src);
  507. ar.source = NULL; /* do not print source again */
  508. }
  509. }
  510. luaL_addstring(&b, buff);
  511. if (ar.currentline > 0) {
  512. sprintf(buff, " at line %d", ar.currentline);
  513. luaL_addstring(&b, buff);
  514. }
  515. if (ar.source) {
  516. sprintf(buff, " [%.70s]", ar.short_src);
  517. luaL_addstring(&b, buff);
  518. }
  519. luaL_addstring(&b, "\n");
  520. }
  521. luaL_pushresult(&b);
  522. lua_getglobal(L, LUA_ALERT);
  523. if (lua_isfunction(L, -1)) { /* avoid loop if _ALERT is not defined */
  524. lua_pushvalue(L, -2); /* error message */
  525. lua_rawcall(L, 1, 0);
  526. }
  527. return 0;
  528. }
  529. static const luaL_reg iolib[] = {
  530. {"appendto", io_appendto},
  531. {"clock", io_clock},
  532. {"closefile", io_close},
  533. {"date", io_date},
  534. {"debug", io_debug},
  535. {"difftime", io_difftime},
  536. {"execute", io_execute},
  537. {"exit", io_exit},
  538. {"flush", io_flush},
  539. {"getenv", io_getenv},
  540. {"openfile", io_open},
  541. {"read", io_read},
  542. {"readfrom", io_readfrom},
  543. {"remove", io_remove},
  544. {"rename", io_rename},
  545. {"seek", io_seek},
  546. {"setlocale", io_setloc},
  547. {"time", io_time},
  548. {"tmpfile", io_tmpfile},
  549. {"tmpname", io_tmpname},
  550. {"write", io_write},
  551. {"writeto", io_writeto},
  552. {LUA_ERRORMESSAGE, errorfb}
  553. };
  554. LUALIB_API void lua_iolibopen (lua_State *L) {
  555. int iotag = lua_newtype(L, FILEHANDLE, LUA_TUSERDATA);
  556. lua_newtype(L, "ClosedFileHandle", LUA_TUSERDATA);
  557. luaL_openl(L, iolib);
  558. /* predefined file handles */
  559. setfile(L, stdin, INFILE);
  560. setfile(L, stdout, OUTFILE);
  561. setfilebyname(L, stdin, "_STDIN");
  562. setfilebyname(L, stdout, "_STDOUT");
  563. setfilebyname(L, stderr, "_STDERR");
  564. /* close files when collected */
  565. lua_pushcfunction(L, file_collect);
  566. lua_settagmethod(L, iotag, "gc");
  567. }