liolib.c 14 KB

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