liolib.c 17 KB

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