src/luajit.c - luajit-2.0-src

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
  3. ** Copyright (C) 2005-2015 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 != 0) 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. }

  138. static int getargs(lua_State *L, char **argv, int n)
  139. {
  140.   int narg;
  141.   int i;
  142.   int argc = 0;
  143.   while (argv[argc]) argc++;  /* count total number of arguments */
  144.   narg = argc - (n + 1);  /* number of arguments to the script */
  145.   luaL_checkstack(L, narg + 3, "too many arguments to script");
  146.   for (i = n+1; i < argc; i++)
  147.     lua_pushstring(L, argv[i]);
  148.   lua_createtable(L, narg, n + 1);
  149.   for (i = 0; i < argc; i++) {
  150.     lua_pushstring(L, argv[i]);
  151.     lua_rawseti(L, -2, i - n);
  152.   }
  153.   return narg;
  154. }

  155. static int dofile(lua_State *L, const char *name)
  156. {
  157.   int status = luaL_loadfile(L, name) || docall(L, 0, 1);
  158.   return report(L, status);
  159. }

  160. static int dostring(lua_State *L, const char *s, const char *name)
  161. {
  162.   int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
  163.   return report(L, status);
  164. }

  165. static int dolibrary(lua_State *L, const char *name)
  166. {
  167.   lua_getglobal(L, "require");
  168.   lua_pushstring(L, name);
  169.   return report(L, docall(L, 1, 1));
  170. }

  171. static void write_prompt(lua_State *L, int firstline)
  172. {
  173.   const char *p;
  174.   lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  175.   p = lua_tostring(L, -1);
  176.   if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
  177.   fputs(p, stdout);
  178.   fflush(stdout);
  179.   lua_pop(L, 1);  /* remove global */
  180. }

  181. static int incomplete(lua_State *L, int status)
  182. {
  183.   if (status == LUA_ERRSYNTAX) {
  184.     size_t lmsg;
  185.     const char *msg = lua_tolstring(L, -1, &lmsg);
  186.     const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  187.     if (strstr(msg, LUA_QL("<eof>")) == tp) {
  188.       lua_pop(L, 1);
  189.       return 1;
  190.     }
  191.   }
  192.   return 0/* else... */
  193. }

  194. static int pushline(lua_State *L, int firstline)
  195. {
  196.   char buf[LUA_MAXINPUT];
  197.   write_prompt(L, firstline);
  198.   if (fgets(buf, LUA_MAXINPUT, stdin)) {
  199.     size_t len = strlen(buf);
  200.     if (len > 0 && buf[len-1] == '\n')
  201.       buf[len-1] = '\0';
  202.     if (firstline && buf[0] == '=')
  203.       lua_pushfstring(L, "return %s", buf+1);
  204.     else
  205.       lua_pushstring(L, buf);
  206.     return 1;
  207.   }
  208.   return 0;
  209. }

  210. static int loadline(lua_State *L)
  211. {
  212.   int status;
  213.   lua_settop(L, 0);
  214.   if (!pushline(L, 1))
  215.     return -1/* no input */
  216.   for (;;) {  /* repeat until gets a complete line */
  217.     status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  218.     if (!incomplete(L, status)) break/* cannot try to add lines? */
  219.     if (!pushline(L, 0))  /* no more input? */
  220.       return -1;
  221.     lua_pushliteral(L, "\n");  /* add a new line... */
  222.     lua_insert(L, -2);  /* ...between the two lines */
  223.     lua_concat(L, 3);  /* join them */
  224.   }
  225.   lua_remove(L, 1);  /* remove line */
  226.   return status;
  227. }

  228. static void dotty(lua_State *L)
  229. {
  230.   int status;
  231.   const char *oldprogname = progname;
  232.   progname = NULL;
  233.   while ((status = loadline(L)) != -1) {
  234.     if (status == 0) status = docall(L, 0, 0);
  235.     report(L, status);
  236.     if (status == 0 && lua_gettop(L) > 0) {  /* any result to print? */
  237.       lua_getglobal(L, "print");
  238.       lua_insert(L, 1);
  239.       if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  240.         l_message(progname,
  241.           lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
  242.                               lua_tostring(L, -1)));
  243.     }
  244.   }
  245.   lua_settop(L, 0);  /* clear stack */
  246.   fputs("\n", stdout);
  247.   fflush(stdout);
  248.   progname = oldprogname;
  249. }

  250. static int handle_script(lua_State *L, char **argv, int n)
  251. {
  252.   int status;
  253.   const char *fname;
  254.   int narg = getargs(L, argv, n);  /* collect arguments */
  255.   lua_setglobal(L, "arg");
  256.   fname = argv[n];
  257.   if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  258.     fname = NULL/* stdin */
  259.   status = luaL_loadfile(L, fname);
  260.   lua_insert(L, -(narg+1));
  261.   if (status == 0)
  262.     status = docall(L, narg, 0);
  263.   else
  264.     lua_pop(L, narg);
  265.   return report(L, status);
  266. }

  267. /* Load add-on module. */
  268. static int loadjitmodule(lua_State *L)
  269. {
  270.   lua_getglobal(L, "require");
  271.   lua_pushliteral(L, "jit.");
  272.   lua_pushvalue(L, -3);
  273.   lua_concat(L, 2);
  274.   if (lua_pcall(L, 1, 1, 0)) {
  275.     const char *msg = lua_tostring(L, -1);
  276.     if (msg && !strncmp(msg, "module ", 7))
  277.       goto nomodule;
  278.     return report(L, 1);
  279.   }
  280.   lua_getfield(L, -1, "start");
  281.   if (lua_isnil(L, -1)) {
  282.   nomodule:
  283.     l_message(progname,
  284.               "unknown luaJIT command or jit.* modules not installed");
  285.     return 1;
  286.   }
  287.   lua_remove(L, -2);  /* Drop module table. */
  288.   return 0;
  289. }

  290. /* Run command with options. */
  291. static int runcmdopt(lua_State *L, const char *opt)
  292. {
  293.   int narg = 0;
  294.   if (opt && *opt) {
  295.     for (;;) {  /* Split arguments. */
  296.       const char *p = strchr(opt, ',');
  297.       narg++;
  298.       if (!p) break;
  299.       if (p == opt)
  300.         lua_pushnil(L);
  301.       else
  302.         lua_pushlstring(L, opt, (size_t)(p - opt));
  303.       opt = p + 1;
  304.     }
  305.     if (*opt)
  306.       lua_pushstring(L, opt);
  307.     else
  308.       lua_pushnil(L);
  309.   }
  310.   return report(L, lua_pcall(L, narg, 0, 0));
  311. }

  312. /* JIT engine control command: try jit library first or load add-on module. */
  313. static int dojitcmd(lua_State *L, const char *cmd)
  314. {
  315.   const char *opt = strchr(cmd, '=');
  316.   lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
  317.   lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  318.   lua_getfield(L, -1, "jit");  /* Get jit.* module table. */
  319.   lua_remove(L, -2);
  320.   lua_pushvalue(L, -2);
  321.   lua_gettable(L, -2);  /* Lookup library function. */
  322.   if (!lua_isfunction(L, -1)) {
  323.     lua_pop(L, 2);  /* Drop non-function and jit.* table, keep module name. */
  324.     if (loadjitmodule(L))
  325.       return 1;
  326.   } else {
  327.     lua_remove(L, -2);  /* Drop jit.* table. */
  328.   }
  329.   lua_remove(L, -2);  /* Drop module name. */
  330.   return runcmdopt(L, opt ? opt+1 : opt);
  331. }

  332. /* Optimization flags. */
  333. static int dojitopt(lua_State *L, const char *opt)
  334. {
  335.   lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  336.   lua_getfield(L, -1, "jit.opt");  /* Get jit.opt.* module table. */
  337.   lua_remove(L, -2);
  338.   lua_getfield(L, -1, "start");
  339.   lua_remove(L, -2);
  340.   return runcmdopt(L, opt);
  341. }

  342. /* Save or list bytecode. */
  343. static int dobytecode(lua_State *L, char **argv)
  344. {
  345.   int narg = 0;
  346.   lua_pushliteral(L, "bcsave");
  347.   if (loadjitmodule(L))
  348.     return 1;
  349.   if (argv[0][2]) {
  350.     narg++;
  351.     argv[0][1] = '-';
  352.     lua_pushstring(L, argv[0]+1);
  353.   }
  354.   for (argv++; *argv != NULL; narg++, argv++)
  355.     lua_pushstring(L, *argv);
  356.   return report(L, lua_pcall(L, narg, 0, 0));
  357. }

  358. /* check that argument has no extra characters at the end */
  359. #define notail(x)        {if ((x)[2] != '\0') return -1;}

  360. #define FLAGS_INTERACTIVE        1
  361. #define FLAGS_VERSION                2
  362. #define FLAGS_EXEC                4
  363. #define FLAGS_OPTION                8
  364. #define FLAGS_NOENV                16

  365. static int collectargs(char **argv, int *flags)
  366. {
  367.   int i;
  368.   for (i = 1; argv[i] != NULL; i++) {
  369.     if (argv[i][0] != '-'/* Not an option? */
  370.       return i;
  371.     switch (argv[i][1]) {  /* Check option. */
  372.     case '-':
  373.       notail(argv[i]);
  374.       return (argv[i+1] != NULL ? i+1 : 0);
  375.     case '\0':
  376.       return i;
  377.     case 'i':
  378.       notail(argv[i]);
  379.       *flags |= FLAGS_INTERACTIVE;
  380.       /* fallthrough */
  381.     case 'v':
  382.       notail(argv[i]);
  383.       *flags |= FLAGS_VERSION;
  384.       break;
  385.     case 'e':
  386.       *flags |= FLAGS_EXEC;
  387.     case 'j'/* LuaJIT extension */
  388.     case 'l':
  389.       *flags |= FLAGS_OPTION;
  390.       if (argv[i][2] == '\0') {
  391.         i++;
  392.         if (argv[i] == NULL) return -1;
  393.       }
  394.       break;
  395.     case 'O': break/* LuaJIT extension */
  396.     case 'b'/* LuaJIT extension */
  397.       if (*flags) return -1;
  398.       *flags |= FLAGS_EXEC;
  399.       return 0;
  400.     case 'E':
  401.       *flags |= FLAGS_NOENV;
  402.       break;
  403.     default: return -1/* invalid option */
  404.     }
  405.   }
  406.   return 0;
  407. }

  408. static int runargs(lua_State *L, char **argv, int n)
  409. {
  410.   int i;
  411.   for (i = 1; i < n; i++) {
  412.     if (argv[i] == NULL) continue;
  413.     lua_assert(argv[i][0] == '-');
  414.     switch (argv[i][1]) {  /* option */
  415.     case 'e': {
  416.       const char *chunk = argv[i] + 2;
  417.       if (*chunk == '\0') chunk = argv[++i];
  418.       lua_assert(chunk != NULL);
  419.       if (dostring(L, chunk, "=(command line)") != 0)
  420.         return 1;
  421.       break;
  422.       }
  423.     case 'l': {
  424.       const char *filename = argv[i] + 2;
  425.       if (*filename == '\0') filename = argv[++i];
  426.       lua_assert(filename != NULL);
  427.       if (dolibrary(L, filename))
  428.         return 1/* stop if file fails */
  429.       break;
  430.       }
  431.     case 'j': {  /* LuaJIT extension */
  432.       const char *cmd = argv[i] + 2;
  433.       if (*cmd == '\0') cmd = argv[++i];
  434.       lua_assert(cmd != NULL);
  435.       if (dojitcmd(L, cmd))
  436.         return 1;
  437.       break;
  438.       }
  439.     case 'O'/* LuaJIT extension */
  440.       if (dojitopt(L, argv[i] + 2))
  441.         return 1;
  442.       break;
  443.     case 'b'/* LuaJIT extension */
  444.       return dobytecode(L, argv+i);
  445.     default: break;
  446.     }
  447.   }
  448.   return 0;
  449. }

  450. static int handle_luainit(lua_State *L)
  451. {
  452. #if LJ_TARGET_CONSOLE
  453.   const char *init = NULL;
  454. #else
  455.   const char *init = getenv(LUA_INIT);
  456. #endif
  457.   if (init == NULL)
  458.     return 0/* status OK */
  459.   else if (init[0] == '@')
  460.     return dofile(L, init+1);
  461.   else
  462.     return dostring(L, init, "=" LUA_INIT);
  463. }

  464. static struct Smain {
  465.   char **argv;
  466.   int argc;
  467.   int status;
  468. } smain;

  469. static int pmain(lua_State *L)
  470. {
  471.   struct Smain *s = &smain;
  472.   char **argv = s->argv;
  473.   int script;
  474.   int flags = 0;
  475.   globalL = L;
  476.   if (argv[0] && argv[0][0]) progname = argv[0];
  477.   LUAJIT_VERSION_SYM();  /* linker-enforced version check */
  478.   script = collectargs(argv, &flags);
  479.   if (script < 0) {  /* invalid args? */
  480.     print_usage();
  481.     s->status = 1;
  482.     return 0;
  483.   }
  484.   if ((flags & FLAGS_NOENV)) {
  485.     lua_pushboolean(L, 1);
  486.     lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  487.   }
  488.   lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
  489.   luaL_openlibs(L);  /* open libraries */
  490.   lua_gc(L, LUA_GCRESTART, -1);
  491.   if (!(flags & FLAGS_NOENV)) {
  492.     s->status = handle_luainit(L);
  493.     if (s->status != 0) return 0;
  494.   }
  495.   if ((flags & FLAGS_VERSION)) print_version();
  496.   s->status = runargs(L, argv, (script > 0) ? script : s->argc);
  497.   if (s->status != 0) return 0;
  498.   if (script) {
  499.     s->status = handle_script(L, argv, script);
  500.     if (s->status != 0) return 0;
  501.   }
  502.   if ((flags & FLAGS_INTERACTIVE)) {
  503.     print_jit_status(L);
  504.     dotty(L);
  505.   } else if (script == 0 && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
  506.     if (lua_stdin_is_tty()) {
  507.       print_version();
  508.       print_jit_status(L);
  509.       dotty(L);
  510.     } else {
  511.       dofile(L, NULL);  /* executes stdin as a file */
  512.     }
  513.   }
  514.   return 0;
  515. }

  516. int main(int argc, char **argv)
  517. {
  518.   int status;
  519.   lua_State *L = lua_open();  /* create state */
  520.   if (L == NULL) {
  521.     l_message(argv[0], "cannot create state: not enough memory");
  522.     return EXIT_FAILURE;
  523.   }
  524.   smain.argc = argc;
  525.   smain.argv = argv;
  526.   status = lua_cpcall(L, pmain, NULL);
  527.   report(L, status);
  528.   lua_close(L);
  529.   return (status || smain.status) ? EXIT_FAILURE : EXIT_SUCCESS;
  530. }