liolib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /*
  2. ** $Id: liolib.c,v 1.57 2000/02/08 16:34:31 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <errno.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #define LUA_REENTRANT
  13. #include "lauxlib.h"
  14. #include "lua.h"
  15. #include "luadebug.h"
  16. #include "lualib.h"
  17. #ifndef OLD_ANSI
  18. #include <locale.h>
  19. #else
  20. /* no support for locale and for strerror: fake them */
  21. #define setlocale(a,b) ((void)a, strcmp((b),"C")==0?"C":NULL)
  22. #define LC_ALL 0
  23. #define LC_COLLATE 0
  24. #define LC_CTYPE 0
  25. #define LC_MONETARY 0
  26. #define LC_NUMERIC 0
  27. #define LC_TIME 0
  28. #define strerror(e) "(no error message provided by operating system)"
  29. #endif
  30. #define IOTAG 1
  31. #define FIRSTARG 2 /* 1st is upvalue */
  32. #define CLOSEDTAG(L, tag) ((tag)-1) /* assume that CLOSEDTAG = iotag-1 */
  33. #define FINPUT "_INPUT"
  34. #define FOUTPUT "_OUTPUT"
  35. #ifdef POPEN
  36. /* FILE *popen();
  37. int pclose(); */
  38. #define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
  39. #else
  40. /* no support for popen */
  41. #define popen(x,y) NULL /* that is, popen always fails */
  42. #define CLOSEFILE(L, f) (fclose(f))
  43. #endif
  44. static void pushresult (lua_State *L, int i) {
  45. if (i)
  46. lua_pushuserdata(L, NULL);
  47. else {
  48. lua_pushnil(L);
  49. lua_pushstring(L, strerror(errno));
  50. lua_pushnumber(L, errno);
  51. }
  52. }
  53. /*
  54. ** {======================================================
  55. ** FILE Operations
  56. ** =======================================================
  57. */
  58. static int gettag (lua_State *L) {
  59. return (int)lua_getnumber(L, lua_getparam(L, IOTAG));
  60. }
  61. static FILE *gethandle (lua_State *L, lua_Object f) {
  62. if (lua_isuserdata(L, f)) {
  63. int ftag = lua_tag(L, f);
  64. int iotag = gettag(L);
  65. if (ftag == iotag)
  66. return (FILE *)lua_getuserdata(L, f);
  67. if (ftag == CLOSEDTAG(L, iotag))
  68. lua_error(L, "cannot access a closed file");
  69. /* else go through */
  70. }
  71. return NULL;
  72. }
  73. static FILE *getfilebyname (lua_State *L, const char *name) {
  74. FILE *handle = gethandle(L, lua_rawgetglobal(L, name));
  75. if (!handle)
  76. luaL_verror(L, "`%.50s' is not a file handle", name);
  77. return handle;
  78. }
  79. static FILE *getfile (lua_State *L, int arg) {
  80. return gethandle(L, lua_getparam(L, arg));
  81. }
  82. static FILE *getnonullfile (lua_State *L, int arg) {
  83. FILE *f = getfile(L, arg);
  84. luaL_arg_check(L, f, arg, "invalid file handle");
  85. return f;
  86. }
  87. static FILE *getfileparam (lua_State *L, const char *name, int *arg) {
  88. FILE *f = getfile(L, *arg);
  89. if (f) {
  90. (*arg)++;
  91. return f;
  92. }
  93. else
  94. return getfilebyname(L, name);
  95. }
  96. static int closefile (lua_State *L, FILE *f) {
  97. if (f == stdin || f == stdout)
  98. return 1;
  99. else {
  100. int tag = gettag(L);
  101. lua_pushusertag(L, f, tag);
  102. lua_settag(L, CLOSEDTAG(L, tag));
  103. return (CLOSEFILE(L, f) == 0);
  104. }
  105. }
  106. static void io_close (lua_State *L) {
  107. pushresult(L, closefile(L, getnonullfile(L, FIRSTARG)));
  108. }
  109. static void gc_close (lua_State *L) {
  110. FILE *f = getnonullfile(L, FIRSTARG);
  111. if (f != stdin && f != stdout && f != stderr) {
  112. CLOSEFILE(L, f);
  113. }
  114. }
  115. static void io_open (lua_State *L) {
  116. FILE *f = fopen(luaL_check_string(L, FIRSTARG), luaL_check_string(L, FIRSTARG+1));
  117. if (f) lua_pushusertag(L, f, gettag(L));
  118. else pushresult(L, 0);
  119. }
  120. static void setfile (lua_State *L, FILE *f, const char *name, int tag) {
  121. lua_pushusertag(L, f, tag);
  122. lua_setglobal(L, name);
  123. }
  124. static void setreturn (lua_State *L, FILE *f, const char *name) {
  125. if (f == NULL)
  126. pushresult(L, 0);
  127. else {
  128. int tag = gettag(L);
  129. setfile(L, f, name, tag);
  130. lua_pushusertag(L, f, tag);
  131. }
  132. }
  133. static void io_readfrom (lua_State *L) {
  134. FILE *current;
  135. lua_Object f = lua_getparam(L, FIRSTARG);
  136. if (f == LUA_NOOBJECT) {
  137. if (closefile(L, getfilebyname(L, FINPUT)))
  138. current = stdin;
  139. else
  140. current = NULL; /* to signal error */
  141. }
  142. else if (lua_tag(L, f) == gettag(L)) /* deprecated option */
  143. current = (FILE *)lua_getuserdata(L, f);
  144. else {
  145. const char *s = luaL_check_string(L, FIRSTARG);
  146. current = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
  147. }
  148. setreturn(L, current, FINPUT);
  149. }
  150. static void io_writeto (lua_State *L) {
  151. FILE *current;
  152. lua_Object f = lua_getparam(L, FIRSTARG);
  153. if (f == LUA_NOOBJECT) {
  154. if (closefile(L, getfilebyname(L, FOUTPUT)))
  155. current = stdout;
  156. else
  157. current = NULL; /* to signal error */
  158. }
  159. else if (lua_tag(L, f) == gettag(L)) /* deprecated option */
  160. current = (FILE *)lua_getuserdata(L, f);
  161. else {
  162. const char *s = luaL_check_string(L, FIRSTARG);
  163. current = (*s == '|') ? popen(s+1,"w") : fopen(s, "w");
  164. }
  165. setreturn(L, current, FOUTPUT);
  166. }
  167. static void io_appendto (lua_State *L) {
  168. FILE *current = fopen(luaL_check_string(L, FIRSTARG), "a");
  169. setreturn(L, current, FOUTPUT);
  170. }
  171. /*
  172. ** {======================================================
  173. ** READ
  174. ** =======================================================
  175. */
  176. #ifdef COMPAT_READPATTERN
  177. /*
  178. ** We cannot lookahead without need, because this can lock stdin.
  179. ** This flag signals when we need to read a next char.
  180. */
  181. #define NEED_OTHER (EOF-1) /* just some flag different from EOF */
  182. static int read_pattern (lua_State *L, FILE *f, const char *p) {
  183. int inskip = 0; /* {skip} level */
  184. int c = NEED_OTHER;
  185. while (*p != '\0') {
  186. switch (*p) {
  187. case '{':
  188. inskip++;
  189. p++;
  190. continue;
  191. case '}':
  192. if (!inskip) lua_error(L, "unbalanced braces in read pattern");
  193. inskip--;
  194. p++;
  195. continue;
  196. default: {
  197. const char *ep = luaI_classend(L, p); /* get what is next */
  198. int m; /* match result */
  199. if (c == NEED_OTHER) c = getc(f);
  200. m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
  201. if (m) {
  202. if (!inskip) luaL_addchar(L, c);
  203. c = NEED_OTHER;
  204. }
  205. switch (*ep) {
  206. case '+': /* repetition (1 or more) */
  207. if (!m) goto break_while; /* pattern fails? */
  208. /* else go through */
  209. case '*': /* repetition (0 or more) */
  210. while (m) { /* reads the same item until it fails */
  211. c = getc(f);
  212. m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
  213. if (m && !inskip) luaL_addchar(L, c);
  214. }
  215. /* go through to continue reading the pattern */
  216. case '?': /* optional */
  217. p = ep+1; /* continues reading the pattern */
  218. continue;
  219. default:
  220. if (!m) goto break_while; /* pattern fails? */
  221. p = ep; /* else continues reading the pattern */
  222. }
  223. }
  224. }
  225. } break_while:
  226. if (c != NEED_OTHER) ungetc(c, f);
  227. return (*p == '\0');
  228. }
  229. #else
  230. #define read_pattern(L, f, p) (lua_error(L, "read patterns are deprecated"), 0)
  231. #endif
  232. static int read_number (lua_State *L, FILE *f) {
  233. double d;
  234. if (fscanf(f, "%lf", &d) == 1) {
  235. lua_pushnumber(L, d);
  236. return 1;
  237. }
  238. else return 0; /* read fails */
  239. }
  240. static void read_word (lua_State *L, FILE *f) {
  241. int c;
  242. do { c = fgetc(f); } while (isspace(c)); /* skip spaces */
  243. while (c != EOF && !isspace(c)) {
  244. luaL_addchar(L, c);
  245. c = fgetc(f);
  246. }
  247. ungetc(c, f);
  248. }
  249. #define HUNK_LINE 256
  250. #define HUNK_FILE BUFSIZ
  251. static int read_line (lua_State *L, FILE *f) {
  252. int n;
  253. char *b;
  254. do {
  255. b = luaL_openspace(L, HUNK_LINE);
  256. if (!fgets(b, HUNK_LINE, f)) return 0; /* read fails */
  257. n = strlen(b);
  258. luaL_addsize(L, n);
  259. } while (b[n-1] != '\n');
  260. luaL_addsize(L, -1); /* remove '\n' */
  261. return 1;
  262. }
  263. static void read_file (lua_State *L, FILE *f) {
  264. int n;
  265. do {
  266. char *b = luaL_openspace(L, HUNK_FILE);
  267. n = fread(b, sizeof(char), HUNK_FILE, f);
  268. luaL_addsize(L, n);
  269. } while (n==HUNK_FILE);
  270. }
  271. static int read_chars (lua_State *L, FILE *f, int n) {
  272. char *b = luaL_openspace(L, n);
  273. int n1 = fread(b, sizeof(char), n, f);
  274. luaL_addsize(L, n1);
  275. return (n == n1);
  276. }
  277. static void io_read (lua_State *L) {
  278. int arg = FIRSTARG;
  279. FILE *f = getfileparam(L, FINPUT, &arg);
  280. lua_Object op = lua_getparam(L, arg);
  281. do { /* repeat for each part */
  282. long l;
  283. int success;
  284. luaL_resetbuffer(L);
  285. if (lua_isnumber(L, op))
  286. success = read_chars(L, f, (int)lua_getnumber(L, op));
  287. else {
  288. const char *p = luaL_opt_string(L, arg, "*l");
  289. if (p[0] != '*')
  290. success = read_pattern(L, f, p); /* deprecated! */
  291. else {
  292. switch (p[1]) {
  293. case 'n': /* number */
  294. if (!read_number(L, f)) return; /* read fails */
  295. continue; /* number is already pushed; avoid the "pushstring" */
  296. case 'l': /* line */
  297. success = read_line(L, f);
  298. break;
  299. case 'a': /* file */
  300. read_file(L, f);
  301. success = 1; /* always success */
  302. break;
  303. case 'w': /* word */
  304. read_word(L, f);
  305. success = 0; /* must read something to succeed */
  306. break;
  307. default:
  308. luaL_argerror(L, arg, "invalid format");
  309. success = 0; /* to avoid warnings */
  310. }
  311. }
  312. }
  313. l = luaL_getsize(L);
  314. if (!success && l==0) return; /* read fails */
  315. lua_pushlstring(L, luaL_buffer(L), l);
  316. } while ((op = lua_getparam(L, ++arg)) != LUA_NOOBJECT);
  317. }
  318. /* }====================================================== */
  319. static void io_write (lua_State *L) {
  320. int arg = FIRSTARG;
  321. FILE *f = getfileparam(L, FOUTPUT, &arg);
  322. int status = 1;
  323. lua_Object o;
  324. while ((o = lua_getparam(L, arg)) != LUA_NOOBJECT) {
  325. if (lua_type(L, o)[2] == 'm') { /* nuMber? */ /* LUA_NUMBER */
  326. /* optimization: could be done exactly as for strings */
  327. status = status && fprintf(f, "%.16g", lua_getnumber(L, o)) > 0;
  328. }
  329. else {
  330. long l;
  331. const char *s = luaL_check_lstr(L, arg, &l);
  332. status = status && ((long)fwrite(s, sizeof(char), l, f) == l);
  333. }
  334. arg++;
  335. }
  336. pushresult(L, status);
  337. }
  338. static void io_seek (lua_State *L) {
  339. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  340. static const char *const modenames[] = {"set", "cur", "end", NULL};
  341. FILE *f = getnonullfile(L, FIRSTARG);
  342. int op = luaL_findstring(luaL_opt_string(L, FIRSTARG+1, "cur"), modenames);
  343. long offset = luaL_opt_long(L, FIRSTARG+2, 0);
  344. luaL_arg_check(L, op != -1, FIRSTARG+1, "invalid mode");
  345. op = fseek(f, offset, mode[op]);
  346. if (op)
  347. pushresult(L, 0); /* error */
  348. else
  349. lua_pushnumber(L, ftell(f));
  350. }
  351. static void io_flush (lua_State *L) {
  352. FILE *f = getfile(L, FIRSTARG);
  353. luaL_arg_check(L, f || lua_getparam(L, FIRSTARG) == LUA_NOOBJECT, FIRSTARG,
  354. "invalid file handle");
  355. pushresult(L, fflush(f) == 0);
  356. }
  357. /* }====================================================== */
  358. /*
  359. ** {======================================================
  360. ** Other O.S. Operations
  361. ** =======================================================
  362. */
  363. static void io_execute (lua_State *L) {
  364. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  365. }
  366. static void io_remove (lua_State *L) {
  367. pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  368. }
  369. static void io_rename (lua_State *L) {
  370. pushresult(L, rename(luaL_check_string(L, 1),
  371. luaL_check_string(L, 2)) == 0);
  372. }
  373. static void io_tmpname (lua_State *L) {
  374. lua_pushstring(L, tmpnam(NULL));
  375. }
  376. static void io_getenv (lua_State *L) {
  377. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  378. }
  379. static void io_clock (lua_State *L) {
  380. lua_pushnumber(L, ((double)clock())/CLOCKS_PER_SEC);
  381. }
  382. static void io_date (lua_State *L) {
  383. char b[256];
  384. const char *s = luaL_opt_string(L, 1, "%c");
  385. struct tm *stm;
  386. time_t t;
  387. time(&t); stm = localtime(&t);
  388. if (strftime(b, sizeof(b), s, stm))
  389. lua_pushstring(L, b);
  390. else
  391. lua_error(L, "invalid `date' format");
  392. }
  393. static void setloc (lua_State *L) {
  394. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  395. LC_NUMERIC, LC_TIME};
  396. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  397. "numeric", "time", NULL};
  398. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  399. luaL_arg_check(L, op != -1, 2, "invalid option");
  400. lua_pushstring(L, setlocale(cat[op], luaL_check_string(L, 1)));
  401. }
  402. static void io_exit (lua_State *L) {
  403. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  404. }
  405. /* }====================================================== */
  406. static void io_debug (lua_State *L) {
  407. for (;;) {
  408. char buffer[250];
  409. fprintf(stderr, "lua_debug> ");
  410. if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
  411. strcmp(buffer, "cont\n") == 0)
  412. return;
  413. lua_dostring(L, buffer);
  414. }
  415. }
  416. #define MESSAGESIZE 150
  417. #define MAXMESSAGE (MESSAGESIZE*10)
  418. static void errorfb (lua_State *L) {
  419. char buff[MAXMESSAGE];
  420. int level = 1; /* skip level 0 (it's this function) */
  421. lua_Dbgactreg ar;
  422. lua_Object alertfunc = lua_rawgetglobal(L, "_ALERT");
  423. sprintf(buff, "error: %.200s\n", lua_getstring(L, lua_getparam(L, 1)));
  424. while (lua_getstack(L, level++, &ar)) {
  425. char buffchunk[60];
  426. lua_getinfo(L, "Snl", &ar);
  427. luaL_chunkid(buffchunk, ar.source, sizeof(buffchunk));
  428. if (level == 2) strcat(buff, "Stack traceback:\n");
  429. strcat(buff, " ");
  430. if (strlen(buff) > MAXMESSAGE-MESSAGESIZE) {
  431. strcat(buff, "...\n");
  432. break; /* buffer is full */
  433. }
  434. switch (*ar.namewhat) {
  435. case 'g': case 'l': /* global, local */
  436. sprintf(buff+strlen(buff), "function `%.50s'", ar.name);
  437. break;
  438. case 'f': /* field */
  439. sprintf(buff+strlen(buff), "method `%.50s'", ar.name);
  440. break;
  441. case 't': /* tag method */
  442. sprintf(buff+strlen(buff), "`%.50s' tag method", ar.name);
  443. break;
  444. default: {
  445. if (*ar.what == 'm') /* main? */
  446. sprintf(buff+strlen(buff), "main of %.70s", buffchunk);
  447. else if (*ar.what == 'C') /* C function? */
  448. sprintf(buff+strlen(buff), "%.70s", buffchunk);
  449. else
  450. sprintf(buff+strlen(buff), "function <%d:%.70s>",
  451. ar.linedefined, buffchunk);
  452. ar.source = NULL;
  453. }
  454. }
  455. if (ar.currentline > 0)
  456. sprintf(buff+strlen(buff), " at line %d", ar.currentline);
  457. if (ar.source)
  458. sprintf(buff+strlen(buff), " [%.70s]", buffchunk);
  459. strcat(buff, "\n");
  460. }
  461. if (lua_isfunction(L, alertfunc)) { /* avoid loop if _ALERT is not defined */
  462. lua_pushstring(L, buff);
  463. lua_callfunction(L, alertfunc);
  464. }
  465. }
  466. static const struct luaL_reg iolib[] = {
  467. {"_ERRORMESSAGE", errorfb},
  468. {"clock", io_clock},
  469. {"date", io_date},
  470. {"debug", io_debug},
  471. {"execute", io_execute},
  472. {"exit", io_exit},
  473. {"getenv", io_getenv},
  474. {"remove", io_remove},
  475. {"rename", io_rename},
  476. {"setlocale", setloc},
  477. {"tmpname", io_tmpname}
  478. };
  479. static const struct luaL_reg iolibtag[] = {
  480. {"appendto", io_appendto},
  481. {"closefile", io_close},
  482. {"flush", io_flush},
  483. {"openfile", io_open},
  484. {"read", io_read},
  485. {"readfrom", io_readfrom},
  486. {"seek", io_seek},
  487. {"write", io_write},
  488. {"writeto", io_writeto}
  489. };
  490. static void openwithtags (lua_State *L) {
  491. unsigned int i;
  492. int iotag = lua_newtag(L);
  493. lua_newtag(L); /* alloc CLOSEDTAG: assume that CLOSEDTAG = iotag-1 */
  494. for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
  495. /* put iotag as upvalue for these functions */
  496. lua_pushnumber(L, iotag);
  497. lua_pushcclosure(L, iolibtag[i].func, 1);
  498. lua_setglobal(L, iolibtag[i].name);
  499. }
  500. /* predefined file handles */
  501. setfile(L, stdin, FINPUT, iotag);
  502. setfile(L, stdout, FOUTPUT, iotag);
  503. setfile(L, stdin, "_STDIN", iotag);
  504. setfile(L, stdout, "_STDOUT", iotag);
  505. setfile(L, stderr, "_STDERR", iotag);
  506. /* close file when collected */
  507. lua_pushnumber(L, iotag);
  508. lua_pushcclosure(L, gc_close, 1);
  509. lua_settagmethod(L, iotag, "gc");
  510. }
  511. void lua_iolibopen (lua_State *L) {
  512. luaL_openl(L, iolib);
  513. openwithtags(L);
  514. }