liolib.c 13 KB

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