liolib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /*
  2. ** $Id: liolib.c,v 1.37 1999/04/05 19:47:05 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; /* get what is next */
  194. int m; /* match result */
  195. if (c == NEED_OTHER) c = getc(f);
  196. if (c != EOF)
  197. m = luaI_singlematch(c, p, &ep);
  198. else {
  199. luaI_singlematch(0, p, &ep); /* to set "ep" */
  200. m = 0; /* EOF matches no pattern */
  201. }
  202. if (m) {
  203. if (!inskip) luaL_addchar(c);
  204. c = NEED_OTHER;
  205. }
  206. switch (*ep) {
  207. case '*': /* repetition */
  208. if (!m) p = ep+1; /* else stay in (repeat) the same item */
  209. continue;
  210. case '?': /* optional */
  211. p = ep+1; /* continues reading the pattern */
  212. continue;
  213. default:
  214. if (!m) goto break_while; /* pattern fails? */
  215. p = ep; /* else continues reading the pattern */
  216. }
  217. }
  218. }
  219. } break_while:
  220. if (c != NEED_OTHER) ungetc(c, f);
  221. return (*p == '\0');
  222. }
  223. static int read_number (FILE *f) {
  224. double d;
  225. if (fscanf(f, "%lf", &d) == 1) {
  226. lua_pushnumber(d);
  227. return 1;
  228. }
  229. else return 0; /* read fails */
  230. }
  231. #define HUNK_LINE 1024
  232. #define HUNK_FILE BUFSIZ
  233. static int read_line (FILE *f) {
  234. /* equivalent to: return read_pattern(f, "[^\n]*{\n}"); */
  235. int n;
  236. char *b;
  237. do {
  238. b = luaL_openspace(HUNK_LINE);
  239. if (!fgets(b, HUNK_LINE, f)) return 0; /* read fails */
  240. n = strlen(b);
  241. luaL_addsize(n);
  242. } while (b[n-1] != '\n');
  243. luaL_addsize(-1); /* remove '\n' */
  244. return 1;
  245. }
  246. static void read_file (FILE *f) {
  247. /* equivalent to: return read_pattern(f, ".*"); */
  248. int n;
  249. do {
  250. char *b = luaL_openspace(HUNK_FILE);
  251. n = fread(b, sizeof(char), HUNK_FILE, f);
  252. luaL_addsize(n);
  253. } while (n==HUNK_FILE);
  254. }
  255. static void io_read (void) {
  256. static char *options[] = {"*n", "*l", "*a", ".*", "*w", NULL};
  257. int arg = FIRSTARG;
  258. FILE *f = getfileparam(FINPUT, &arg);
  259. char *p = luaL_opt_string(arg++, "*l");
  260. do { /* repeat for each part */
  261. long l;
  262. int success;
  263. luaL_resetbuffer();
  264. switch (luaL_findstring(p, options)) {
  265. case 0: /* number */
  266. if (!read_number(f)) return; /* read fails */
  267. continue; /* number is already pushed; avoid the "pushstring" */
  268. case 1: /* line */
  269. success = read_line(f);
  270. break;
  271. case 2: case 3: /* file */
  272. read_file(f);
  273. success = 1; /* always success */
  274. break;
  275. case 4: /* word */
  276. success = read_pattern(f, "{%s*}%S%S*");
  277. break;
  278. default:
  279. success = read_pattern(f, p);
  280. }
  281. l = luaL_getsize();
  282. if (!success && l==0) return; /* read fails */
  283. lua_pushlstring(luaL_buffer(), l);
  284. } while ((p = luaL_opt_string(arg++, NULL)) != NULL);
  285. }
  286. /* }====================================================== */
  287. static void io_write (void) {
  288. int arg = FIRSTARG;
  289. FILE *f = getfileparam(FOUTPUT, &arg);
  290. int status = 1;
  291. char *s;
  292. long l;
  293. while ((s = luaL_opt_lstr(arg++, NULL, &l)) != NULL)
  294. status = status && ((long)fwrite(s, 1, l, f) == l);
  295. pushresult(status);
  296. }
  297. static void io_seek (void) {
  298. static int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  299. static char *modenames[] = {"set", "cur", "end", NULL};
  300. FILE *f = getnonullfile(FIRSTARG);
  301. int op = luaL_findstring(luaL_opt_string(FIRSTARG+1, "cur"), modenames);
  302. long offset = luaL_opt_long(FIRSTARG+2, 0);
  303. luaL_arg_check(op != -1, FIRSTARG+1, "invalid mode");
  304. op = fseek(f, offset, mode[op]);
  305. if (op)
  306. pushresult(0); /* error */
  307. else
  308. lua_pushnumber(ftell(f));
  309. }
  310. static void io_flush (void) {
  311. FILE *f = getfile(FIRSTARG);
  312. luaL_arg_check(f || lua_getparam(FIRSTARG) == LUA_NOOBJECT, FIRSTARG,
  313. "invalid file handle");
  314. pushresult(fflush(f) == 0);
  315. }
  316. /* }====================================================== */
  317. /*
  318. ** {======================================================
  319. ** Other O.S. Operations
  320. ** =======================================================
  321. */
  322. static void io_execute (void) {
  323. lua_pushnumber(system(luaL_check_string(1)));
  324. }
  325. static void io_remove (void) {
  326. pushresult(remove(luaL_check_string(1)) == 0);
  327. }
  328. static void io_rename (void) {
  329. pushresult(rename(luaL_check_string(1),
  330. luaL_check_string(2)) == 0);
  331. }
  332. static void io_tmpname (void) {
  333. lua_pushstring(tmpnam(NULL));
  334. }
  335. static void io_getenv (void) {
  336. lua_pushstring(getenv(luaL_check_string(1))); /* if NULL push nil */
  337. }
  338. static void io_clock (void) {
  339. lua_pushnumber(((double)clock())/CLOCKS_PER_SEC);
  340. }
  341. static void io_date (void) {
  342. char b[256];
  343. char *s = luaL_opt_string(1, "%c");
  344. struct tm *tm;
  345. time_t t;
  346. time(&t); tm = localtime(&t);
  347. if (strftime(b,sizeof(b),s,tm))
  348. lua_pushstring(b);
  349. else
  350. lua_error("invalid `date' format");
  351. }
  352. static void setloc (void) {
  353. static int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC,
  354. LC_TIME};
  355. static char *catnames[] = {"all", "collate", "ctype", "monetary",
  356. "numeric", "time", NULL};
  357. int op = luaL_findstring(luaL_opt_string(2, "all"), catnames);
  358. luaL_arg_check(op != -1, 2, "invalid option");
  359. lua_pushstring(setlocale(cat[op], luaL_check_string(1)));
  360. }
  361. static void io_exit (void) {
  362. lua_Object o = lua_getparam(1);
  363. exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
  364. }
  365. /* }====================================================== */
  366. static void io_debug (void) {
  367. for (;;) {
  368. char buffer[250];
  369. fprintf(stderr, "lua_debug> ");
  370. if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
  371. strcmp(buffer, "cont\n") == 0)
  372. return;
  373. lua_dostring(buffer);
  374. }
  375. }
  376. #define MESSAGESIZE 150
  377. #define MAXMESSAGE (MESSAGESIZE*10)
  378. #define MAXSRC 40
  379. static void errorfb (void) {
  380. char buff[MAXMESSAGE];
  381. int level = 1; /* skip level 0 (it's this function) */
  382. lua_Object func;
  383. sprintf(buff, "lua error: %.200s\n", lua_getstring(lua_getparam(1)));
  384. while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
  385. char *name;
  386. int currentline;
  387. char *chunkname;
  388. char buffchunk[MAXSRC];
  389. int linedefined;
  390. lua_funcinfo(func, &chunkname, &linedefined);
  391. luaL_chunkid(buffchunk, chunkname, sizeof(buffchunk));
  392. if (level == 2) strcat(buff, "Active Stack:\n");
  393. strcat(buff, "\t");
  394. if (strlen(buff) > MAXMESSAGE-MESSAGESIZE) {
  395. strcat(buff, "...\n");
  396. break; /* buffer is full */
  397. }
  398. switch (*lua_getobjname(func, &name)) {
  399. case 'g':
  400. sprintf(buff+strlen(buff), "function `%.50s'", name);
  401. break;
  402. case 't':
  403. sprintf(buff+strlen(buff), "`%.50s' tag method", name);
  404. break;
  405. default: {
  406. if (linedefined == 0)
  407. sprintf(buff+strlen(buff), "main of %.50s", buffchunk);
  408. else if (linedefined < 0)
  409. sprintf(buff+strlen(buff), "%.50s", buffchunk);
  410. else
  411. sprintf(buff+strlen(buff), "function <%d:%.50s>",
  412. linedefined, buffchunk);
  413. chunkname = NULL;
  414. }
  415. }
  416. if ((currentline = lua_currentline(func)) > 0)
  417. sprintf(buff+strlen(buff), " at line %d", currentline);
  418. if (chunkname)
  419. sprintf(buff+strlen(buff), " [%.50s]", buffchunk);
  420. strcat(buff, "\n");
  421. }
  422. func = lua_rawgetglobal("_ALERT");
  423. if (lua_isfunction(func)) { /* avoid error loop if _ALERT is not defined */
  424. lua_pushstring(buff);
  425. lua_callfunction(func);
  426. }
  427. }
  428. static struct luaL_reg iolib[] = {
  429. {"_ERRORMESSAGE", errorfb},
  430. {"clock", io_clock},
  431. {"date", io_date},
  432. {"debug", io_debug},
  433. {"execute", io_execute},
  434. {"exit", io_exit},
  435. {"getenv", io_getenv},
  436. {"remove", io_remove},
  437. {"rename", io_rename},
  438. {"setlocale", setloc},
  439. {"tmpname", io_tmpname}
  440. };
  441. static struct luaL_reg iolibtag[] = {
  442. {"appendto", io_appendto},
  443. {"closefile", io_close},
  444. {"flush", io_flush},
  445. {"openfile", io_open},
  446. {"read", io_read},
  447. {"readfrom", io_readfrom},
  448. {"seek", io_seek},
  449. {"write", io_write},
  450. {"writeto", io_writeto}
  451. };
  452. static void openwithtags (void) {
  453. int i;
  454. int iotag = lua_newtag();
  455. lua_newtag(); /* alloc CLOSEDTAG: assume that CLOSEDTAG = iotag-1 */
  456. for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
  457. /* put iotag as upvalue for these functions */
  458. lua_pushnumber(iotag);
  459. lua_pushcclosure(iolibtag[i].func, 1);
  460. lua_setglobal(iolibtag[i].name);
  461. }
  462. /* predefined file handles */
  463. setfile(stdin, FINPUT, iotag);
  464. setfile(stdout, FOUTPUT, iotag);
  465. setfile(stdin, "_STDIN", iotag);
  466. setfile(stdout, "_STDOUT", iotag);
  467. setfile(stderr, "_STDERR", iotag);
  468. /* close file when collected */
  469. lua_pushnumber(iotag);
  470. lua_pushcclosure(gc_close, 1);
  471. lua_settagmethod(iotag, "gc");
  472. }
  473. void lua_iolibopen (void) {
  474. /* register lib functions */
  475. luaL_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
  476. openwithtags();
  477. }