liolib.c 15 KB

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