liolib.c 17 KB

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