luajit.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /*
  2. ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
  3. ** Copyright (C) 2005-2021 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. fputs("usage: ", stderr);
  55. fputs(progname, stderr);
  56. fputs(" [options]... [script [args]...].\n"
  57. "Available options are:\n"
  58. " -e chunk Execute string " LUA_QL("chunk") ".\n"
  59. " -l name Require library " LUA_QL("name") ".\n"
  60. " -b ... Save or list bytecode.\n"
  61. " -j cmd Perform LuaJIT control command.\n"
  62. " -O[opt] Control LuaJIT optimizations.\n"
  63. " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
  64. " -v Show version information.\n"
  65. " -E Ignore environment variables.\n"
  66. " -- Stop handling options.\n"
  67. " - Execute stdin and stop handling options.\n", stderr);
  68. fflush(stderr);
  69. }
  70. static void l_message(const char *pname, const char *msg)
  71. {
  72. if (pname) { fputs(pname, stderr); fputc(':', stderr); fputc(' ', stderr); }
  73. fputs(msg, stderr); fputc('\n', stderr);
  74. fflush(stderr);
  75. }
  76. static int report(lua_State *L, int status)
  77. {
  78. if (status && !lua_isnil(L, -1)) {
  79. const char *msg = lua_tostring(L, -1);
  80. if (msg == NULL) msg = "(error object is not a string)";
  81. l_message(progname, msg);
  82. lua_pop(L, 1);
  83. }
  84. return status;
  85. }
  86. static int traceback(lua_State *L)
  87. {
  88. if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
  89. if (lua_isnoneornil(L, 1) ||
  90. !luaL_callmeta(L, 1, "__tostring") ||
  91. !lua_isstring(L, -1))
  92. return 1; /* Return non-string error object. */
  93. lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
  94. }
  95. luaL_traceback(L, L, lua_tostring(L, 1), 1);
  96. return 1;
  97. }
  98. static int docall(lua_State *L, int narg, int clear)
  99. {
  100. int status;
  101. int base = lua_gettop(L) - narg; /* function index */
  102. lua_pushcfunction(L, traceback); /* push traceback function */
  103. lua_insert(L, base); /* put it under chunk and args */
  104. #if !LJ_TARGET_CONSOLE
  105. signal(SIGINT, laction);
  106. #endif
  107. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  108. #if !LJ_TARGET_CONSOLE
  109. signal(SIGINT, SIG_DFL);
  110. #endif
  111. lua_remove(L, base); /* remove traceback function */
  112. /* force a complete garbage collection in case of errors */
  113. if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
  114. return status;
  115. }
  116. static void print_version(void)
  117. {
  118. fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout);
  119. }
  120. static void print_jit_status(lua_State *L)
  121. {
  122. int n;
  123. const char *s;
  124. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  125. lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
  126. lua_remove(L, -2);
  127. lua_getfield(L, -1, "status");
  128. lua_remove(L, -2);
  129. n = lua_gettop(L);
  130. lua_call(L, 0, LUA_MULTRET);
  131. fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout);
  132. for (n++; (s = lua_tostring(L, n)); n++) {
  133. putc(' ', stdout);
  134. fputs(s, stdout);
  135. }
  136. putc('\n', stdout);
  137. lua_settop(L, 0); /* clear stack */
  138. }
  139. static void createargtable(lua_State *L, char **argv, int argc, int argf)
  140. {
  141. int i;
  142. lua_createtable(L, argc - argf, argf);
  143. for (i = 0; i < argc; i++) {
  144. lua_pushstring(L, argv[i]);
  145. lua_rawseti(L, -2, i - argf);
  146. }
  147. lua_setglobal(L, "arg");
  148. }
  149. static int dofile(lua_State *L, const char *name)
  150. {
  151. int status = luaL_loadfile(L, name) || docall(L, 0, 1);
  152. return report(L, status);
  153. }
  154. static int dostring(lua_State *L, const char *s, const char *name)
  155. {
  156. int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
  157. return report(L, status);
  158. }
  159. static int dolibrary(lua_State *L, const char *name)
  160. {
  161. lua_getglobal(L, "require");
  162. lua_pushstring(L, name);
  163. return report(L, docall(L, 1, 1));
  164. }
  165. static void write_prompt(lua_State *L, int firstline)
  166. {
  167. const char *p;
  168. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  169. p = lua_tostring(L, -1);
  170. if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
  171. fputs(p, stdout);
  172. fflush(stdout);
  173. lua_pop(L, 1); /* remove global */
  174. }
  175. static int incomplete(lua_State *L, int status)
  176. {
  177. if (status == LUA_ERRSYNTAX) {
  178. size_t lmsg;
  179. const char *msg = lua_tolstring(L, -1, &lmsg);
  180. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  181. if (strstr(msg, LUA_QL("<eof>")) == tp) {
  182. lua_pop(L, 1);
  183. return 1;
  184. }
  185. }
  186. return 0; /* else... */
  187. }
  188. static int pushline(lua_State *L, int firstline)
  189. {
  190. char buf[LUA_MAXINPUT];
  191. write_prompt(L, firstline);
  192. if (fgets(buf, LUA_MAXINPUT, stdin)) {
  193. size_t len = strlen(buf);
  194. if (len > 0 && buf[len-1] == '\n')
  195. buf[len-1] = '\0';
  196. if (firstline && buf[0] == '=')
  197. lua_pushfstring(L, "return %s", buf+1);
  198. else
  199. lua_pushstring(L, buf);
  200. return 1;
  201. }
  202. return 0;
  203. }
  204. static int loadline(lua_State *L)
  205. {
  206. int status;
  207. lua_settop(L, 0);
  208. if (!pushline(L, 1))
  209. return -1; /* no input */
  210. for (;;) { /* repeat until gets a complete line */
  211. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  212. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  213. if (!pushline(L, 0)) /* no more input? */
  214. return -1;
  215. lua_pushliteral(L, "\n"); /* add a new line... */
  216. lua_insert(L, -2); /* ...between the two lines */
  217. lua_concat(L, 3); /* join them */
  218. }
  219. lua_remove(L, 1); /* remove line */
  220. return status;
  221. }
  222. static void dotty(lua_State *L)
  223. {
  224. int status;
  225. const char *oldprogname = progname;
  226. progname = NULL;
  227. while ((status = loadline(L)) != -1) {
  228. if (status == LUA_OK) status = docall(L, 0, 0);
  229. report(L, status);
  230. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  231. lua_getglobal(L, "print");
  232. lua_insert(L, 1);
  233. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  234. l_message(progname,
  235. 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(progname,
  287. "unknown luaJIT command or jit.* modules not installed");
  288. return 1;
  289. }
  290. lua_remove(L, -2); /* Drop module table. */
  291. return 0;
  292. }
  293. /* Run command with options. */
  294. static int runcmdopt(lua_State *L, const char *opt)
  295. {
  296. int narg = 0;
  297. if (opt && *opt) {
  298. for (;;) { /* Split arguments. */
  299. const char *p = strchr(opt, ',');
  300. narg++;
  301. if (!p) break;
  302. if (p == opt)
  303. lua_pushnil(L);
  304. else
  305. lua_pushlstring(L, opt, (size_t)(p - opt));
  306. opt = p + 1;
  307. }
  308. if (*opt)
  309. lua_pushstring(L, opt);
  310. else
  311. lua_pushnil(L);
  312. }
  313. return report(L, lua_pcall(L, narg, 0, 0));
  314. }
  315. /* JIT engine control command: try jit library first or load add-on module. */
  316. static int dojitcmd(lua_State *L, const char *cmd)
  317. {
  318. const char *opt = strchr(cmd, '=');
  319. lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
  320. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  321. lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
  322. lua_remove(L, -2);
  323. lua_pushvalue(L, -2);
  324. lua_gettable(L, -2); /* Lookup library function. */
  325. if (!lua_isfunction(L, -1)) {
  326. lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
  327. if (loadjitmodule(L))
  328. return 1;
  329. } else {
  330. lua_remove(L, -2); /* Drop jit.* table. */
  331. }
  332. lua_remove(L, -2); /* Drop module name. */
  333. return runcmdopt(L, opt ? opt+1 : opt);
  334. }
  335. /* Optimization flags. */
  336. static int dojitopt(lua_State *L, const char *opt)
  337. {
  338. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  339. lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
  340. lua_remove(L, -2);
  341. lua_getfield(L, -1, "start");
  342. lua_remove(L, -2);
  343. return runcmdopt(L, opt);
  344. }
  345. /* Save or list bytecode. */
  346. static int dobytecode(lua_State *L, char **argv)
  347. {
  348. int narg = 0;
  349. lua_pushliteral(L, "bcsave");
  350. if (loadjitmodule(L))
  351. return 1;
  352. if (argv[0][2]) {
  353. narg++;
  354. argv[0][1] = '-';
  355. lua_pushstring(L, argv[0]+1);
  356. }
  357. for (argv++; *argv != NULL; narg++, argv++)
  358. lua_pushstring(L, *argv);
  359. report(L, lua_pcall(L, narg, 0, 0));
  360. return -1;
  361. }
  362. /* check that argument has no extra characters at the end */
  363. #define notail(x) {if ((x)[2] != '\0') return -1;}
  364. #define FLAGS_INTERACTIVE 1
  365. #define FLAGS_VERSION 2
  366. #define FLAGS_EXEC 4
  367. #define FLAGS_OPTION 8
  368. #define FLAGS_NOENV 16
  369. static int collectargs(char **argv, int *flags)
  370. {
  371. int i;
  372. for (i = 1; argv[i] != NULL; i++) {
  373. if (argv[i][0] != '-') /* Not an option? */
  374. return i;
  375. switch (argv[i][1]) { /* Check option. */
  376. case '-':
  377. notail(argv[i]);
  378. return i+1;
  379. case '\0':
  380. return i;
  381. case 'i':
  382. notail(argv[i]);
  383. *flags |= FLAGS_INTERACTIVE;
  384. /* fallthrough */
  385. case 'v':
  386. notail(argv[i]);
  387. *flags |= FLAGS_VERSION;
  388. break;
  389. case 'e':
  390. *flags |= FLAGS_EXEC;
  391. /* fallthrough */
  392. case 'j': /* LuaJIT extension */
  393. case 'l':
  394. *flags |= FLAGS_OPTION;
  395. if (argv[i][2] == '\0') {
  396. i++;
  397. if (argv[i] == NULL) return -1;
  398. }
  399. break;
  400. case 'O': break; /* LuaJIT extension */
  401. case 'b': /* LuaJIT extension */
  402. if (*flags) return -1;
  403. *flags |= FLAGS_EXEC;
  404. return i+1;
  405. case 'E':
  406. *flags |= FLAGS_NOENV;
  407. break;
  408. default: return -1; /* invalid option */
  409. }
  410. }
  411. return i;
  412. }
  413. static int runargs(lua_State *L, char **argv, int argn)
  414. {
  415. int i;
  416. for (i = 1; i < argn; i++) {
  417. if (argv[i] == NULL) continue;
  418. lua_assert(argv[i][0] == '-');
  419. switch (argv[i][1]) {
  420. case 'e': {
  421. const char *chunk = argv[i] + 2;
  422. if (*chunk == '\0') chunk = argv[++i];
  423. lua_assert(chunk != NULL);
  424. if (dostring(L, chunk, "=(command line)") != 0)
  425. return 1;
  426. break;
  427. }
  428. case 'l': {
  429. const char *filename = argv[i] + 2;
  430. if (*filename == '\0') filename = argv[++i];
  431. lua_assert(filename != NULL);
  432. if (dolibrary(L, filename))
  433. return 1;
  434. break;
  435. }
  436. case 'j': { /* LuaJIT extension. */
  437. const char *cmd = argv[i] + 2;
  438. if (*cmd == '\0') cmd = argv[++i];
  439. lua_assert(cmd != NULL);
  440. if (dojitcmd(L, cmd))
  441. return 1;
  442. break;
  443. }
  444. case 'O': /* LuaJIT extension. */
  445. if (dojitopt(L, argv[i] + 2))
  446. return 1;
  447. break;
  448. case 'b': /* LuaJIT extension. */
  449. return dobytecode(L, argv+i);
  450. default: break;
  451. }
  452. }
  453. return LUA_OK;
  454. }
  455. static int handle_luainit(lua_State *L)
  456. {
  457. #if LJ_TARGET_CONSOLE
  458. const char *init = NULL;
  459. #else
  460. const char *init = getenv(LUA_INIT);
  461. #endif
  462. if (init == NULL)
  463. return LUA_OK;
  464. else if (init[0] == '@')
  465. return dofile(L, init+1);
  466. else
  467. return dostring(L, init, "=" LUA_INIT);
  468. }
  469. static struct Smain {
  470. char **argv;
  471. int argc;
  472. int status;
  473. } smain;
  474. static int pmain(lua_State *L)
  475. {
  476. struct Smain *s = &smain;
  477. char **argv = s->argv;
  478. int argn;
  479. int flags = 0;
  480. globalL = L;
  481. if (argv[0] && argv[0][0]) progname = argv[0];
  482. LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */
  483. argn = collectargs(argv, &flags);
  484. if (argn < 0) { /* Invalid args? */
  485. print_usage();
  486. s->status = 1;
  487. return 0;
  488. }
  489. if ((flags & FLAGS_NOENV)) {
  490. lua_pushboolean(L, 1);
  491. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  492. }
  493. /* Stop collector during library initialization. */
  494. lua_gc(L, LUA_GCSTOP, 0);
  495. luaL_openlibs(L);
  496. lua_gc(L, LUA_GCRESTART, -1);
  497. createargtable(L, argv, s->argc, argn);
  498. if (!(flags & FLAGS_NOENV)) {
  499. s->status = handle_luainit(L);
  500. if (s->status != LUA_OK) return 0;
  501. }
  502. if ((flags & FLAGS_VERSION)) print_version();
  503. s->status = runargs(L, argv, argn);
  504. if (s->status != LUA_OK) return 0;
  505. if (s->argc > argn) {
  506. s->status = handle_script(L, argv + argn);
  507. if (s->status != LUA_OK) return 0;
  508. }
  509. if ((flags & FLAGS_INTERACTIVE)) {
  510. print_jit_status(L);
  511. dotty(L);
  512. } else if (s->argc == argn && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
  513. if (lua_stdin_is_tty()) {
  514. print_version();
  515. print_jit_status(L);
  516. dotty(L);
  517. } else {
  518. dofile(L, NULL); /* Executes stdin as a file. */
  519. }
  520. }
  521. return 0;
  522. }
  523. int main(int argc, char **argv)
  524. {
  525. int status;
  526. lua_State *L = lua_open();
  527. if (L == NULL) {
  528. l_message(argv[0], "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. }