liolib.c 14 KB

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