luajit.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /*
  2. ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
  3. ** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
  4. **
  5. ** Major portions taken verbatim or adapted from the Lua interpreter.
  6. ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #define luajit_c
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. #include "luajit.h"
  16. #include "lj_arch.h"
  17. #if LJ_TARGET_POSIX
  18. #include <unistd.h>
  19. #define lua_stdin_is_tty() isatty(0)
  20. #elif LJ_TARGET_WINDOWS
  21. #include <io.h>
  22. #ifdef __BORLANDC__
  23. #define lua_stdin_is_tty() isatty(_fileno(stdin))
  24. #else
  25. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  26. #endif
  27. #else
  28. #define lua_stdin_is_tty() 1
  29. #endif
  30. #if !LJ_TARGET_CONSOLE
  31. #include <signal.h>
  32. #endif
  33. static lua_State *globalL = NULL;
  34. static const char *progname = LUA_PROGNAME;
  35. #if !LJ_TARGET_CONSOLE
  36. static void lstop(lua_State *L, lua_Debug *ar)
  37. {
  38. (void)ar; /* unused arg. */
  39. lua_sethook(L, NULL, 0, 0);
  40. /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
  41. luaL_where(L, 0);
  42. lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
  43. lua_error(L);
  44. }
  45. static void laction(int i)
  46. {
  47. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  48. terminate process (default action) */
  49. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  50. }
  51. #endif
  52. static void print_usage(void)
  53. {
  54. fprintf(stderr,
  55. "usage: %s [options]... [script [args]...].\n"
  56. "Available options are:\n"
  57. " -e chunk Execute string " LUA_QL("chunk") ".\n"
  58. " -l name Require library " LUA_QL("name") ".\n"
  59. " -b ... Save or list bytecode.\n"
  60. " -j cmd Perform LuaJIT control command.\n"
  61. " -O[opt] Control LuaJIT optimizations.\n"
  62. " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
  63. " -v Show version information.\n"
  64. " -E Ignore environment variables.\n"
  65. " -- Stop handling options.\n"
  66. " - Execute stdin and stop handling options.\n"
  67. ,
  68. progname);
  69. fflush(stderr);
  70. }
  71. static void l_message(const char *pname, const char *msg)
  72. {
  73. if (pname) fprintf(stderr, "%s: ", pname);
  74. fprintf(stderr, "%s\n", msg);
  75. fflush(stderr);
  76. }
  77. static int report(lua_State *L, int status)
  78. {
  79. if (status && !lua_isnil(L, -1)) {
  80. const char *msg = lua_tostring(L, -1);
  81. if (msg == NULL) msg = "(error object is not a string)";
  82. l_message(progname, msg);
  83. lua_pop(L, 1);
  84. }
  85. return status;
  86. }
  87. static int traceback(lua_State *L)
  88. {
  89. if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
  90. if (lua_isnoneornil(L, 1) ||
  91. !luaL_callmeta(L, 1, "__tostring") ||
  92. !lua_isstring(L, -1))
  93. return 1; /* Return non-string error object. */
  94. lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
  95. }
  96. luaL_traceback(L, L, lua_tostring(L, 1), 1);
  97. return 1;
  98. }
  99. static int docall(lua_State *L, int narg, int clear)
  100. {
  101. int status;
  102. int base = lua_gettop(L) - narg; /* function index */
  103. lua_pushcfunction(L, traceback); /* push traceback function */
  104. lua_insert(L, base); /* put it under chunk and args */
  105. #if !LJ_TARGET_CONSOLE
  106. signal(SIGINT, laction);
  107. #endif
  108. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  109. #if !LJ_TARGET_CONSOLE
  110. signal(SIGINT, SIG_DFL);
  111. #endif
  112. lua_remove(L, base); /* remove traceback function */
  113. /* force a complete garbage collection in case of errors */
  114. if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  115. return status;
  116. }
  117. static void print_version(void)
  118. {
  119. fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout);
  120. }
  121. static void print_jit_status(lua_State *L)
  122. {
  123. int n;
  124. const char *s;
  125. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  126. lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
  127. lua_remove(L, -2);
  128. lua_getfield(L, -1, "status");
  129. lua_remove(L, -2);
  130. n = lua_gettop(L);
  131. lua_call(L, 0, LUA_MULTRET);
  132. fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout);
  133. for (n++; (s = lua_tostring(L, n)); n++) {
  134. putc(' ', stdout);
  135. fputs(s, stdout);
  136. }
  137. putc('\n', stdout);
  138. }
  139. static int getargs(lua_State *L, char **argv, int n)
  140. {
  141. int narg;
  142. int i;
  143. int argc = 0;
  144. while (argv[argc]) argc++; /* count total number of arguments */
  145. narg = argc - (n + 1); /* number of arguments to the script */
  146. luaL_checkstack(L, narg + 3, "too many arguments to script");
  147. for (i = n+1; i < argc; i++)
  148. lua_pushstring(L, argv[i]);
  149. lua_createtable(L, narg, n + 1);
  150. for (i = 0; i < argc; i++) {
  151. lua_pushstring(L, argv[i]);
  152. lua_rawseti(L, -2, i - n);
  153. }
  154. return narg;
  155. }
  156. static int dofile(lua_State *L, const char *name)
  157. {
  158. int status = luaL_loadfile(L, name) || docall(L, 0, 1);
  159. return report(L, status);
  160. }
  161. static int dostring(lua_State *L, const char *s, const char *name)
  162. {
  163. int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
  164. return report(L, status);
  165. }
  166. static int dolibrary(lua_State *L, const char *name)
  167. {
  168. lua_getglobal(L, "require");
  169. lua_pushstring(L, name);
  170. return report(L, docall(L, 1, 1));
  171. }
  172. static void write_prompt(lua_State *L, int firstline)
  173. {
  174. const char *p;
  175. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  176. p = lua_tostring(L, -1);
  177. if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
  178. fputs(p, stdout);
  179. fflush(stdout);
  180. lua_pop(L, 1); /* remove global */
  181. }
  182. static int incomplete(lua_State *L, int status)
  183. {
  184. if (status == LUA_ERRSYNTAX) {
  185. size_t lmsg;
  186. const char *msg = lua_tolstring(L, -1, &lmsg);
  187. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  188. if (strstr(msg, LUA_QL("<eof>")) == tp) {
  189. lua_pop(L, 1);
  190. return 1;
  191. }
  192. }
  193. return 0; /* else... */
  194. }
  195. static int pushline(lua_State *L, int firstline)
  196. {
  197. char buf[LUA_MAXINPUT];
  198. write_prompt(L, firstline);
  199. if (fgets(buf, LUA_MAXINPUT, stdin)) {
  200. size_t len = strlen(buf);
  201. if (len > 0 && buf[len-1] == '\n')
  202. buf[len-1] = '\0';
  203. if (firstline && buf[0] == '=')
  204. lua_pushfstring(L, "return %s", buf+1);
  205. else
  206. lua_pushstring(L, buf);
  207. return 1;
  208. }
  209. return 0;
  210. }
  211. static int loadline(lua_State *L)
  212. {
  213. int status;
  214. lua_settop(L, 0);
  215. if (!pushline(L, 1))
  216. return -1; /* no input */
  217. for (;;) { /* repeat until gets a complete line */
  218. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  219. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  220. if (!pushline(L, 0)) /* no more input? */
  221. return -1;
  222. lua_pushliteral(L, "\n"); /* add a new line... */
  223. lua_insert(L, -2); /* ...between the two lines */
  224. lua_concat(L, 3); /* join them */
  225. }
  226. lua_remove(L, 1); /* remove line */
  227. return status;
  228. }
  229. static void dotty(lua_State *L)
  230. {
  231. int status;
  232. const char *oldprogname = progname;
  233. progname = NULL;
  234. while ((status = loadline(L)) != -1) {
  235. if (status == 0) status = docall(L, 0, 0);
  236. report(L, status);
  237. if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
  238. lua_getglobal(L, "print");
  239. lua_insert(L, 1);
  240. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  241. l_message(progname,
  242. lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
  243. lua_tostring(L, -1)));
  244. }
  245. }
  246. lua_settop(L, 0); /* clear stack */
  247. fputs("\n", stdout);
  248. fflush(stdout);
  249. progname = oldprogname;
  250. }
  251. static int handle_script(lua_State *L, char **argv, int n)
  252. {
  253. int status;
  254. const char *fname;
  255. int narg = getargs(L, argv, n); /* collect arguments */
  256. lua_setglobal(L, "arg");
  257. fname = argv[n];
  258. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  259. fname = NULL; /* stdin */
  260. status = luaL_loadfile(L, fname);
  261. lua_insert(L, -(narg+1));
  262. if (status == 0)
  263. status = docall(L, narg, 0);
  264. else
  265. lua_pop(L, narg);
  266. return report(L, status);
  267. }
  268. /* Load add-on module. */
  269. static int loadjitmodule(lua_State *L)
  270. {
  271. lua_getglobal(L, "require");
  272. lua_pushliteral(L, "jit.");
  273. lua_pushvalue(L, -3);
  274. lua_concat(L, 2);
  275. if (lua_pcall(L, 1, 1, 0)) {
  276. const char *msg = lua_tostring(L, -1);
  277. if (msg && !strncmp(msg, "module ", 7)) {
  278. err:
  279. l_message(progname,
  280. "unknown luaJIT command or jit.* modules not installed");
  281. return 1;
  282. } else {
  283. return report(L, 1);
  284. }
  285. }
  286. lua_getfield(L, -1, "start");
  287. if (lua_isnil(L, -1)) goto err;
  288. lua_remove(L, -2); /* Drop module table. */
  289. return 0;
  290. }
  291. /* Run command with options. */
  292. static int runcmdopt(lua_State *L, const char *opt)
  293. {
  294. int narg = 0;
  295. if (opt && *opt) {
  296. for (;;) { /* Split arguments. */
  297. const char *p = strchr(opt, ',');
  298. narg++;
  299. if (!p) break;
  300. if (p == opt)
  301. lua_pushnil(L);
  302. else
  303. lua_pushlstring(L, opt, (size_t)(p - opt));
  304. opt = p + 1;
  305. }
  306. if (*opt)
  307. lua_pushstring(L, opt);
  308. else
  309. lua_pushnil(L);
  310. }
  311. return report(L, lua_pcall(L, narg, 0, 0));
  312. }
  313. /* JIT engine control command: try jit library first or load add-on module. */
  314. static int dojitcmd(lua_State *L, const char *cmd)
  315. {
  316. const char *opt = strchr(cmd, '=');
  317. lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
  318. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  319. lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
  320. lua_remove(L, -2);
  321. lua_pushvalue(L, -2);
  322. lua_gettable(L, -2); /* Lookup library function. */
  323. if (!lua_isfunction(L, -1)) {
  324. lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
  325. if (loadjitmodule(L))
  326. return 1;
  327. } else {
  328. lua_remove(L, -2); /* Drop jit.* table. */
  329. }
  330. lua_remove(L, -2); /* Drop module name. */
  331. return runcmdopt(L, opt ? opt+1 : opt);
  332. }
  333. /* Optimization flags. */
  334. static int dojitopt(lua_State *L, const char *opt)
  335. {
  336. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  337. lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
  338. lua_remove(L, -2);
  339. lua_getfield(L, -1, "start");
  340. lua_remove(L, -2);
  341. return runcmdopt(L, opt);
  342. }
  343. /* Save or list bytecode. */
  344. static int dobytecode(lua_State *L, char **argv)
  345. {
  346. int narg = 0;
  347. lua_pushliteral(L, "bcsave");
  348. if (loadjitmodule(L))
  349. return 1;
  350. if (argv[0][2]) {
  351. narg++;
  352. argv[0][1] = '-';
  353. lua_pushstring(L, argv[0]+1);
  354. }
  355. for (argv++; *argv != NULL; narg++, argv++)
  356. lua_pushstring(L, *argv);
  357. return report(L, lua_pcall(L, narg, 0, 0));
  358. }
  359. /* check that argument has no extra characters at the end */
  360. #define notail(x) {if ((x)[2] != '\0') return -1;}
  361. #define FLAGS_INTERACTIVE 1
  362. #define FLAGS_VERSION 2
  363. #define FLAGS_EXEC 4
  364. #define FLAGS_OPTION 8
  365. #define FLAGS_NOENV 16
  366. static int collectargs(char **argv, int *flags)
  367. {
  368. int i;
  369. for (i = 1; argv[i] != NULL; i++) {
  370. if (argv[i][0] != '-') /* Not an option? */
  371. return i;
  372. switch (argv[i][1]) { /* Check option. */
  373. case '-':
  374. notail(argv[i]);
  375. return (argv[i+1] != NULL ? i+1 : 0);
  376. case '\0':
  377. return i;
  378. case 'i':
  379. notail(argv[i]);
  380. *flags |= FLAGS_INTERACTIVE;
  381. /* fallthrough */
  382. case 'v':
  383. notail(argv[i]);
  384. *flags |= FLAGS_VERSION;
  385. break;
  386. case 'e':
  387. *flags |= FLAGS_EXEC;
  388. case 'j': /* LuaJIT extension */
  389. case 'l':
  390. *flags |= FLAGS_OPTION;
  391. if (argv[i][2] == '\0') {
  392. i++;
  393. if (argv[i] == NULL) return -1;
  394. }
  395. break;
  396. case 'O': break; /* LuaJIT extension */
  397. case 'b': /* LuaJIT extension */
  398. if (*flags) return -1;
  399. *flags |= FLAGS_EXEC;
  400. return 0;
  401. case 'E':
  402. *flags |= FLAGS_NOENV;
  403. break;
  404. default: return -1; /* invalid option */
  405. }
  406. }
  407. return 0;
  408. }
  409. static int runargs(lua_State *L, char **argv, int n)
  410. {
  411. int i;
  412. for (i = 1; i < n; i++) {
  413. if (argv[i] == NULL) continue;
  414. lua_assert(argv[i][0] == '-');
  415. switch (argv[i][1]) { /* option */
  416. case 'e': {
  417. const char *chunk = argv[i] + 2;
  418. if (*chunk == '\0') chunk = argv[++i];
  419. lua_assert(chunk != NULL);
  420. if (dostring(L, chunk, "=(command line)") != 0)
  421. return 1;
  422. break;
  423. }
  424. case 'l': {
  425. const char *filename = argv[i] + 2;
  426. if (*filename == '\0') filename = argv[++i];
  427. lua_assert(filename != NULL);
  428. if (dolibrary(L, filename))
  429. return 1; /* stop if file fails */
  430. break;
  431. }
  432. case 'j': { /* LuaJIT extension */
  433. const char *cmd = argv[i] + 2;
  434. if (*cmd == '\0') cmd = argv[++i];
  435. lua_assert(cmd != NULL);
  436. if (dojitcmd(L, cmd))
  437. return 1;
  438. break;
  439. }
  440. case 'O': /* LuaJIT extension */
  441. if (dojitopt(L, argv[i] + 2))
  442. return 1;
  443. break;
  444. case 'b': /* LuaJIT extension */
  445. return dobytecode(L, argv+i);
  446. default: break;
  447. }
  448. }
  449. return 0;
  450. }
  451. static int handle_luainit(lua_State *L)
  452. {
  453. #if LJ_TARGET_CONSOLE
  454. const char *init = NULL;
  455. #else
  456. const char *init = getenv(LUA_INIT);
  457. #endif
  458. if (init == NULL)
  459. return 0; /* status OK */
  460. else if (init[0] == '@')
  461. return dofile(L, init+1);
  462. else
  463. return dostring(L, init, "=" LUA_INIT);
  464. }
  465. static struct Smain {
  466. char **argv;
  467. int argc;
  468. int status;
  469. } smain;
  470. static int pmain(lua_State *L)
  471. {
  472. struct Smain *s = &smain;
  473. char **argv = s->argv;
  474. int script;
  475. int flags = 0;
  476. globalL = L;
  477. if (argv[0] && argv[0][0]) progname = argv[0];
  478. LUAJIT_VERSION_SYM(); /* linker-enforced version check */
  479. script = collectargs(argv, &flags);
  480. if (script < 0) { /* invalid args? */
  481. print_usage();
  482. s->status = 1;
  483. return 0;
  484. }
  485. if ((flags & FLAGS_NOENV)) {
  486. lua_pushboolean(L, 1);
  487. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  488. }
  489. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  490. luaL_openlibs(L); /* open libraries */
  491. lua_gc(L, LUA_GCRESTART, -1);
  492. if (!(flags & FLAGS_NOENV)) {
  493. s->status = handle_luainit(L);
  494. if (s->status != 0) return 0;
  495. }
  496. if ((flags & FLAGS_VERSION)) print_version();
  497. s->status = runargs(L, argv, (script > 0) ? script : s->argc);
  498. if (s->status != 0) return 0;
  499. if (script) {
  500. s->status = handle_script(L, argv, script);
  501. if (s->status != 0) return 0;
  502. }
  503. if ((flags & FLAGS_INTERACTIVE)) {
  504. print_jit_status(L);
  505. dotty(L);
  506. } else if (script == 0 && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
  507. if (lua_stdin_is_tty()) {
  508. print_version();
  509. print_jit_status(L);
  510. dotty(L);
  511. } else {
  512. dofile(L, NULL); /* executes stdin as a file */
  513. }
  514. }
  515. return 0;
  516. }
  517. int main(int argc, char **argv)
  518. {
  519. int status;
  520. lua_State *L = lua_open(); /* create state */
  521. if (L == NULL) {
  522. l_message(argv[0], "cannot create state: not enough memory");
  523. return EXIT_FAILURE;
  524. }
  525. smain.argc = argc;
  526. smain.argv = argv;
  527. status = lua_cpcall(L, pmain, NULL);
  528. report(L, status);
  529. lua_close(L);
  530. return (status || smain.status) ? EXIT_FAILURE : EXIT_SUCCESS;
  531. }