luajit.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. /*
  2. ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
  3. ** Copyright (C) 2005-2023 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. static char *empty_argv[2] = { NULL, NULL };
  36. #if !LJ_TARGET_CONSOLE
  37. static void lstop(lua_State *L, lua_Debug *ar)
  38. {
  39. (void)ar; /* unused arg. */
  40. lua_sethook(L, NULL, 0, 0);
  41. /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
  42. luaL_where(L, 0);
  43. lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
  44. lua_error(L);
  45. }
  46. static void laction(int i)
  47. {
  48. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  49. terminate process (default action) */
  50. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  51. }
  52. #endif
  53. static void print_usage(void)
  54. {
  55. fputs("usage: ", stderr);
  56. fputs(progname, stderr);
  57. fputs(" [options]... [script [args]...].\n"
  58. "Available options are:\n"
  59. " -e chunk Execute string " LUA_QL("chunk") ".\n"
  60. " -l name Require library " LUA_QL("name") ".\n"
  61. " -b ... Save or list bytecode.\n"
  62. " -j cmd Perform LuaJIT control command.\n"
  63. " -O[opt] Control LuaJIT optimizations.\n"
  64. " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
  65. " -v Show version information.\n"
  66. " -E Ignore environment variables.\n"
  67. " -- Stop handling options.\n"
  68. " - Execute stdin and stop handling options.\n", stderr);
  69. fflush(stderr);
  70. }
  71. static void l_message(const char *msg)
  72. {
  73. if (progname) { fputs(progname, stderr); fputc(':', stderr); fputc(' ', stderr); }
  74. fputs(msg, stderr); fputc('\n', stderr);
  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(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 != LUA_OK) 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. lua_settop(L, 0); /* clear stack */
  139. }
  140. static void createargtable(lua_State *L, char **argv, int argc, int argf)
  141. {
  142. int i;
  143. lua_createtable(L, argc - argf, argf);
  144. for (i = 0; i < argc; i++) {
  145. lua_pushstring(L, argv[i]);
  146. lua_rawseti(L, -2, i - argf);
  147. }
  148. lua_setglobal(L, "arg");
  149. }
  150. static int dofile(lua_State *L, const char *name)
  151. {
  152. int status = luaL_loadfile(L, name) || docall(L, 0, 1);
  153. return report(L, status);
  154. }
  155. static int dostring(lua_State *L, const char *s, const char *name)
  156. {
  157. int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
  158. return report(L, status);
  159. }
  160. static int dolibrary(lua_State *L, const char *name)
  161. {
  162. lua_getglobal(L, "require");
  163. lua_pushstring(L, name);
  164. return report(L, docall(L, 1, 1));
  165. }
  166. static void write_prompt(lua_State *L, int firstline)
  167. {
  168. const char *p;
  169. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  170. p = lua_tostring(L, -1);
  171. if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
  172. fputs(p, stdout);
  173. fflush(stdout);
  174. lua_pop(L, 1); /* remove global */
  175. }
  176. static int incomplete(lua_State *L, int status)
  177. {
  178. if (status == LUA_ERRSYNTAX) {
  179. size_t lmsg;
  180. const char *msg = lua_tolstring(L, -1, &lmsg);
  181. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  182. if (strstr(msg, LUA_QL("<eof>")) == tp) {
  183. lua_pop(L, 1);
  184. return 1;
  185. }
  186. }
  187. return 0; /* else... */
  188. }
  189. static int pushline(lua_State *L, int firstline)
  190. {
  191. char buf[LUA_MAXINPUT];
  192. write_prompt(L, firstline);
  193. if (fgets(buf, LUA_MAXINPUT, stdin)) {
  194. size_t len = strlen(buf);
  195. if (len > 0 && buf[len-1] == '\n')
  196. buf[len-1] = '\0';
  197. if (firstline && buf[0] == '=')
  198. lua_pushfstring(L, "return %s", buf+1);
  199. else
  200. lua_pushstring(L, buf);
  201. return 1;
  202. }
  203. return 0;
  204. }
  205. static int loadline(lua_State *L)
  206. {
  207. int status;
  208. lua_settop(L, 0);
  209. if (!pushline(L, 1))
  210. return -1; /* no input */
  211. for (;;) { /* repeat until gets a complete line */
  212. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  213. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  214. if (!pushline(L, 0)) /* no more input? */
  215. return -1;
  216. lua_pushliteral(L, "\n"); /* add a new line... */
  217. lua_insert(L, -2); /* ...between the two lines */
  218. lua_concat(L, 3); /* join them */
  219. }
  220. lua_remove(L, 1); /* remove line */
  221. return status;
  222. }
  223. static void dotty(lua_State *L)
  224. {
  225. int status;
  226. const char *oldprogname = progname;
  227. progname = NULL;
  228. while ((status = loadline(L)) != -1) {
  229. if (status == LUA_OK) status = docall(L, 0, 0);
  230. report(L, status);
  231. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  232. lua_getglobal(L, "print");
  233. lua_insert(L, 1);
  234. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  235. l_message(lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
  236. lua_tostring(L, -1)));
  237. }
  238. }
  239. lua_settop(L, 0); /* clear stack */
  240. fputs("\n", stdout);
  241. fflush(stdout);
  242. progname = oldprogname;
  243. }
  244. static int handle_script(lua_State *L, char **argx)
  245. {
  246. int status;
  247. const char *fname = argx[0];
  248. if (strcmp(fname, "-") == 0 && strcmp(argx[-1], "--") != 0)
  249. fname = NULL; /* stdin */
  250. status = luaL_loadfile(L, fname);
  251. if (status == LUA_OK) {
  252. /* Fetch args from arg table. LUA_INIT or -e might have changed them. */
  253. int narg = 0;
  254. lua_getglobal(L, "arg");
  255. if (lua_istable(L, -1)) {
  256. do {
  257. narg++;
  258. lua_rawgeti(L, -narg, narg);
  259. } while (!lua_isnil(L, -1));
  260. lua_pop(L, 1);
  261. lua_remove(L, -narg);
  262. narg--;
  263. } else {
  264. lua_pop(L, 1);
  265. }
  266. status = docall(L, narg, 0);
  267. }
  268. return report(L, status);
  269. }
  270. /* Load add-on module. */
  271. static int loadjitmodule(lua_State *L)
  272. {
  273. lua_getglobal(L, "require");
  274. lua_pushliteral(L, "jit.");
  275. lua_pushvalue(L, -3);
  276. lua_concat(L, 2);
  277. if (lua_pcall(L, 1, 1, 0)) {
  278. const char *msg = lua_tostring(L, -1);
  279. if (msg && !strncmp(msg, "module ", 7))
  280. goto nomodule;
  281. return report(L, 1);
  282. }
  283. lua_getfield(L, -1, "start");
  284. if (lua_isnil(L, -1)) {
  285. nomodule:
  286. l_message("unknown luaJIT command or jit.* modules not installed");
  287. return 1;
  288. }
  289. lua_remove(L, -2); /* Drop module table. */
  290. return 0;
  291. }
  292. /* Run command with options. */
  293. static int runcmdopt(lua_State *L, const char *opt)
  294. {
  295. int narg = 0;
  296. if (opt && *opt) {
  297. for (;;) { /* Split arguments. */
  298. const char *p = strchr(opt, ',');
  299. narg++;
  300. if (!p) break;
  301. if (p == opt)
  302. lua_pushnil(L);
  303. else
  304. lua_pushlstring(L, opt, (size_t)(p - opt));
  305. opt = p + 1;
  306. }
  307. if (*opt)
  308. lua_pushstring(L, opt);
  309. else
  310. lua_pushnil(L);
  311. }
  312. return report(L, lua_pcall(L, narg, 0, 0));
  313. }
  314. /* JIT engine control command: try jit library first or load add-on module. */
  315. static int dojitcmd(lua_State *L, const char *cmd)
  316. {
  317. const char *opt = strchr(cmd, '=');
  318. lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
  319. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  320. lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
  321. lua_remove(L, -2);
  322. lua_pushvalue(L, -2);
  323. lua_gettable(L, -2); /* Lookup library function. */
  324. if (!lua_isfunction(L, -1)) {
  325. lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
  326. if (loadjitmodule(L))
  327. return 1;
  328. } else {
  329. lua_remove(L, -2); /* Drop jit.* table. */
  330. }
  331. lua_remove(L, -2); /* Drop module name. */
  332. return runcmdopt(L, opt ? opt+1 : opt);
  333. }
  334. /* Optimization flags. */
  335. static int dojitopt(lua_State *L, const char *opt)
  336. {
  337. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  338. lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
  339. lua_remove(L, -2);
  340. lua_getfield(L, -1, "start");
  341. lua_remove(L, -2);
  342. return runcmdopt(L, opt);
  343. }
  344. /* Save or list bytecode. */
  345. static int dobytecode(lua_State *L, char **argv)
  346. {
  347. int narg = 0;
  348. lua_pushliteral(L, "bcsave");
  349. if (loadjitmodule(L))
  350. return 1;
  351. if (argv[0][2]) {
  352. narg++;
  353. argv[0][1] = '-';
  354. lua_pushstring(L, argv[0]+1);
  355. }
  356. for (argv++; *argv != NULL; narg++, argv++)
  357. lua_pushstring(L, *argv);
  358. report(L, lua_pcall(L, narg, 0, 0));
  359. return -1;
  360. }
  361. /* check that argument has no extra characters at the end */
  362. #define notail(x) {if ((x)[2] != '\0') return -1;}
  363. #define FLAGS_INTERACTIVE 1
  364. #define FLAGS_VERSION 2
  365. #define FLAGS_EXEC 4
  366. #define FLAGS_OPTION 8
  367. #define FLAGS_NOENV 16
  368. static int collectargs(char **argv, int *flags)
  369. {
  370. int i;
  371. for (i = 1; argv[i] != NULL; i++) {
  372. if (argv[i][0] != '-') /* Not an option? */
  373. return i;
  374. switch (argv[i][1]) { /* Check option. */
  375. case '-':
  376. notail(argv[i]);
  377. return i+1;
  378. case '\0':
  379. return i;
  380. case 'i':
  381. notail(argv[i]);
  382. *flags |= FLAGS_INTERACTIVE;
  383. /* fallthrough */
  384. case 'v':
  385. notail(argv[i]);
  386. *flags |= FLAGS_VERSION;
  387. break;
  388. case 'e':
  389. *flags |= FLAGS_EXEC;
  390. /* fallthrough */
  391. case 'j': /* LuaJIT extension */
  392. case 'l':
  393. *flags |= FLAGS_OPTION;
  394. if (argv[i][2] == '\0') {
  395. i++;
  396. if (argv[i] == NULL) return -1;
  397. }
  398. break;
  399. case 'O': break; /* LuaJIT extension */
  400. case 'b': /* LuaJIT extension */
  401. if (*flags) return -1;
  402. *flags |= FLAGS_EXEC;
  403. return i+1;
  404. case 'E':
  405. *flags |= FLAGS_NOENV;
  406. break;
  407. default: return -1; /* invalid option */
  408. }
  409. }
  410. return i;
  411. }
  412. static int runargs(lua_State *L, char **argv, int argn)
  413. {
  414. int i;
  415. for (i = 1; i < argn; i++) {
  416. if (argv[i] == NULL) continue;
  417. lua_assert(argv[i][0] == '-');
  418. switch (argv[i][1]) {
  419. case 'e': {
  420. const char *chunk = argv[i] + 2;
  421. if (*chunk == '\0') chunk = argv[++i];
  422. lua_assert(chunk != NULL);
  423. if (dostring(L, chunk, "=(command line)") != 0)
  424. return 1;
  425. break;
  426. }
  427. case 'l': {
  428. const char *filename = argv[i] + 2;
  429. if (*filename == '\0') filename = argv[++i];
  430. lua_assert(filename != NULL);
  431. if (dolibrary(L, filename))
  432. return 1;
  433. break;
  434. }
  435. case 'j': { /* LuaJIT extension. */
  436. const char *cmd = argv[i] + 2;
  437. if (*cmd == '\0') cmd = argv[++i];
  438. lua_assert(cmd != NULL);
  439. if (dojitcmd(L, cmd))
  440. return 1;
  441. break;
  442. }
  443. case 'O': /* LuaJIT extension. */
  444. if (dojitopt(L, argv[i] + 2))
  445. return 1;
  446. break;
  447. case 'b': /* LuaJIT extension. */
  448. return dobytecode(L, argv+i);
  449. default: break;
  450. }
  451. }
  452. return LUA_OK;
  453. }
  454. static int handle_luainit(lua_State *L)
  455. {
  456. #if LJ_TARGET_CONSOLE
  457. const char *init = NULL;
  458. #else
  459. const char *init = getenv(LUA_INIT);
  460. #endif
  461. if (init == NULL)
  462. return LUA_OK;
  463. else if (init[0] == '@')
  464. return dofile(L, init+1);
  465. else
  466. return dostring(L, init, "=" LUA_INIT);
  467. }
  468. static struct Smain {
  469. char **argv;
  470. int argc;
  471. int status;
  472. } smain;
  473. static int pmain(lua_State *L)
  474. {
  475. struct Smain *s = &smain;
  476. char **argv = s->argv;
  477. int argn;
  478. int flags = 0;
  479. globalL = L;
  480. LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */
  481. argn = collectargs(argv, &flags);
  482. if (argn < 0) { /* Invalid args? */
  483. print_usage();
  484. s->status = 1;
  485. return 0;
  486. }
  487. if ((flags & FLAGS_NOENV)) {
  488. lua_pushboolean(L, 1);
  489. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  490. }
  491. /* Stop collector during library initialization. */
  492. lua_gc(L, LUA_GCSTOP, 0);
  493. luaL_openlibs(L);
  494. lua_gc(L, LUA_GCRESTART, -1);
  495. createargtable(L, argv, s->argc, argn);
  496. if (!(flags & FLAGS_NOENV)) {
  497. s->status = handle_luainit(L);
  498. if (s->status != LUA_OK) return 0;
  499. }
  500. if ((flags & FLAGS_VERSION)) print_version();
  501. s->status = runargs(L, argv, argn);
  502. if (s->status != LUA_OK) return 0;
  503. if (s->argc > argn) {
  504. s->status = handle_script(L, argv + argn);
  505. if (s->status != LUA_OK) return 0;
  506. }
  507. if ((flags & FLAGS_INTERACTIVE)) {
  508. print_jit_status(L);
  509. dotty(L);
  510. } else if (s->argc == argn && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
  511. if (lua_stdin_is_tty()) {
  512. print_version();
  513. print_jit_status(L);
  514. dotty(L);
  515. } else {
  516. dofile(L, NULL); /* Executes stdin as a file. */
  517. }
  518. }
  519. return 0;
  520. }
  521. int main(int argc, char **argv)
  522. {
  523. int status;
  524. lua_State *L;
  525. if (!argv[0]) argv = empty_argv; else if (argv[0][0]) progname = argv[0];
  526. L = lua_open();
  527. if (L == NULL) {
  528. l_message("cannot create state: not enough memory");
  529. return EXIT_FAILURE;
  530. }
  531. smain.argc = argc;
  532. smain.argv = argv;
  533. status = lua_cpcall(L, pmain, NULL);
  534. report(L, status);
  535. lua_close(L);
  536. return (status || smain.status > 0) ? EXIT_FAILURE : EXIT_SUCCESS;
  537. }