liolib.c 16 KB

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