liolib.c 17 KB

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