Merge branch 'master' into v2.1
[luajit-2.0.git] / src / luajit.c
blob2e2e9150da08ba4994aa5dea8e506f9afc034362
1 /*
2 ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
3 ** Copyright (C) 2005-2025 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 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
13 #define luajit_c
15 #include "lua.h"
16 #include "lauxlib.h"
17 #include "lualib.h"
18 #include "luajit.h"
20 #include "lj_arch.h"
22 #if LJ_TARGET_POSIX
23 #include <unistd.h>
24 #define lua_stdin_is_tty() isatty(0)
25 #elif LJ_TARGET_WINDOWS
26 #include <io.h>
27 #ifdef __BORLANDC__
28 #define lua_stdin_is_tty() isatty(_fileno(stdin))
29 #else
30 #define lua_stdin_is_tty() _isatty(_fileno(stdin))
31 #endif
32 #else
33 #define lua_stdin_is_tty() 1
34 #endif
36 #if !LJ_TARGET_CONSOLE
37 #include <signal.h>
39 #if LJ_TARGET_POSIX
40 /* Improve signal handling on POSIX. Try CTRL-C on: luajit -e 'io.read()' */
41 static void signal_set(int sig, void (*h)(int))
43 struct sigaction sa;
44 memset(&sa, 0, sizeof(sa));
45 sa.sa_handler = h;
46 sigemptyset(&sa.sa_mask);
47 sigaction(sig, &sa, NULL);
49 #else
50 #define signal_set signal
51 #endif
53 #endif
55 static lua_State *globalL = NULL;
56 static const char *progname = LUA_PROGNAME;
57 static char *empty_argv[2] = { NULL, NULL };
59 #if !LJ_TARGET_CONSOLE
60 static void lstop(lua_State *L, lua_Debug *ar)
62 (void)ar; /* unused arg. */
63 lua_sethook(L, NULL, 0, 0);
64 /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
65 luaL_where(L, 0);
66 lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
67 lua_error(L);
70 static void laction(int i)
72 /* Terminate process if another SIGINT happens (double CTRL-C). */
73 signal_set(i, SIG_DFL);
74 lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
76 #endif
78 static void print_usage(void)
80 fputs("usage: ", stderr);
81 fputs(progname, stderr);
82 fputs(" [options]... [script [args]...].\n"
83 "Available options are:\n"
84 " -e chunk Execute string " LUA_QL("chunk") ".\n"
85 " -l name Require library " LUA_QL("name") ".\n"
86 " -b ... Save or list bytecode.\n"
87 " -j cmd Perform LuaJIT control command.\n"
88 " -O[opt] Control LuaJIT optimizations.\n"
89 " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
90 " -v Show version information.\n"
91 " -E Ignore environment variables.\n"
92 " -- Stop handling options.\n"
93 " - Execute stdin and stop handling options.\n", stderr);
94 fflush(stderr);
97 static void l_message(const char *msg)
99 if (progname) { fputs(progname, stderr); fputc(':', stderr); fputc(' ', stderr); }
100 fputs(msg, stderr); fputc('\n', stderr);
101 fflush(stderr);
104 static int report(lua_State *L, int status)
106 if (status && !lua_isnil(L, -1)) {
107 const char *msg = lua_tostring(L, -1);
108 if (msg == NULL) msg = "(error object is not a string)";
109 l_message(msg);
110 lua_pop(L, 1);
112 return status;
115 static int traceback(lua_State *L)
117 if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
118 if (lua_isnoneornil(L, 1) ||
119 !luaL_callmeta(L, 1, "__tostring") ||
120 !lua_isstring(L, -1))
121 return 1; /* Return non-string error object. */
122 lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
124 luaL_traceback(L, L, lua_tostring(L, 1), 1);
125 return 1;
128 static int docall(lua_State *L, int narg, int clear)
130 int status;
131 int base = lua_gettop(L) - narg; /* function index */
132 lua_pushcfunction(L, traceback); /* push traceback function */
133 lua_insert(L, base); /* put it under chunk and args */
134 #if !LJ_TARGET_CONSOLE
135 signal_set(SIGINT, laction);
136 #endif
137 status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
138 #if !LJ_TARGET_CONSOLE
139 signal_set(SIGINT, SIG_DFL);
140 #endif
141 lua_remove(L, base); /* remove traceback function */
142 /* force a complete garbage collection in case of errors */
143 if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
144 return status;
147 static void print_version(void)
149 fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout);
152 static void print_jit_status(lua_State *L)
154 int n;
155 const char *s;
156 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
157 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
158 lua_remove(L, -2);
159 lua_getfield(L, -1, "status");
160 lua_remove(L, -2);
161 n = lua_gettop(L);
162 lua_call(L, 0, LUA_MULTRET);
163 fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout);
164 for (n++; (s = lua_tostring(L, n)); n++) {
165 putc(' ', stdout);
166 fputs(s, stdout);
168 putc('\n', stdout);
169 lua_settop(L, 0); /* clear stack */
172 static void createargtable(lua_State *L, char **argv, int argc, int argf)
174 int i;
175 lua_createtable(L, argc - argf, argf);
176 for (i = 0; i < argc; i++) {
177 lua_pushstring(L, argv[i]);
178 lua_rawseti(L, -2, i - argf);
180 lua_setglobal(L, "arg");
183 static int dofile(lua_State *L, const char *name)
185 int status = luaL_loadfile(L, name) || docall(L, 0, 1);
186 return report(L, status);
189 static int dostring(lua_State *L, const char *s, const char *name)
191 int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
192 return report(L, status);
195 static int dolibrary(lua_State *L, const char *name)
197 lua_getglobal(L, "require");
198 lua_pushstring(L, name);
199 return report(L, docall(L, 1, 1));
202 static void write_prompt(lua_State *L, int firstline)
204 const char *p;
205 lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
206 p = lua_tostring(L, -1);
207 if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
208 fputs(p, stdout);
209 fflush(stdout);
210 lua_pop(L, 1); /* remove global */
213 static int incomplete(lua_State *L, int status)
215 if (status == LUA_ERRSYNTAX) {
216 size_t lmsg;
217 const char *msg = lua_tolstring(L, -1, &lmsg);
218 const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
219 if (strstr(msg, LUA_QL("<eof>")) == tp) {
220 lua_pop(L, 1);
221 return 1;
224 return 0; /* else... */
227 static int pushline(lua_State *L, int firstline)
229 char buf[LUA_MAXINPUT];
230 write_prompt(L, firstline);
231 if (fgets(buf, LUA_MAXINPUT, stdin)) {
232 size_t len = strlen(buf);
233 if (len > 0 && buf[len-1] == '\n')
234 buf[len-1] = '\0';
235 if (firstline && buf[0] == '=')
236 lua_pushfstring(L, "return %s", buf+1);
237 else
238 lua_pushstring(L, buf);
239 return 1;
241 return 0;
244 static int loadline(lua_State *L)
246 int status;
247 lua_settop(L, 0);
248 if (!pushline(L, 1))
249 return -1; /* no input */
250 for (;;) { /* repeat until gets a complete line */
251 status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
252 if (!incomplete(L, status)) break; /* cannot try to add lines? */
253 if (!pushline(L, 0)) /* no more input? */
254 return -1;
255 lua_pushliteral(L, "\n"); /* add a new line... */
256 lua_insert(L, -2); /* ...between the two lines */
257 lua_concat(L, 3); /* join them */
259 lua_remove(L, 1); /* remove line */
260 return status;
263 static void dotty(lua_State *L)
265 int status;
266 const char *oldprogname = progname;
267 progname = NULL;
268 while ((status = loadline(L)) != -1) {
269 if (status == LUA_OK) status = docall(L, 0, 0);
270 report(L, status);
271 if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
272 lua_getglobal(L, "print");
273 lua_insert(L, 1);
274 if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
275 l_message(lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
276 lua_tostring(L, -1)));
279 lua_settop(L, 0); /* clear stack */
280 fputs("\n", stdout);
281 fflush(stdout);
282 progname = oldprogname;
285 static int handle_script(lua_State *L, char **argx)
287 int status;
288 const char *fname = argx[0];
289 if (strcmp(fname, "-") == 0 && strcmp(argx[-1], "--") != 0)
290 fname = NULL; /* stdin */
291 status = luaL_loadfile(L, fname);
292 if (status == LUA_OK) {
293 /* Fetch args from arg table. LUA_INIT or -e might have changed them. */
294 int narg = 0;
295 lua_getglobal(L, "arg");
296 if (lua_istable(L, -1)) {
297 do {
298 narg++;
299 lua_rawgeti(L, -narg, narg);
300 } while (!lua_isnil(L, -1));
301 lua_pop(L, 1);
302 lua_remove(L, -narg);
303 narg--;
304 } else {
305 lua_pop(L, 1);
307 status = docall(L, narg, 0);
309 return report(L, status);
312 /* Load add-on module. */
313 static int loadjitmodule(lua_State *L)
315 lua_getglobal(L, "require");
316 lua_pushliteral(L, "jit.");
317 lua_pushvalue(L, -3);
318 lua_concat(L, 2);
319 if (lua_pcall(L, 1, 1, 0)) {
320 const char *msg = lua_tostring(L, -1);
321 if (msg && !strncmp(msg, "module ", 7))
322 goto nomodule;
323 return report(L, 1);
325 lua_getfield(L, -1, "start");
326 if (lua_isnil(L, -1)) {
327 nomodule:
328 l_message("unknown luaJIT command or jit.* modules not installed");
329 return 1;
331 lua_remove(L, -2); /* Drop module table. */
332 return 0;
335 /* Run command with options. */
336 static int runcmdopt(lua_State *L, const char *opt)
338 int narg = 0;
339 if (opt && *opt) {
340 for (;;) { /* Split arguments. */
341 const char *p = strchr(opt, ',');
342 narg++;
343 if (!p) break;
344 if (p == opt)
345 lua_pushnil(L);
346 else
347 lua_pushlstring(L, opt, (size_t)(p - opt));
348 opt = p + 1;
350 if (*opt)
351 lua_pushstring(L, opt);
352 else
353 lua_pushnil(L);
355 return report(L, lua_pcall(L, narg, 0, 0));
358 /* JIT engine control command: try jit library first or load add-on module. */
359 static int dojitcmd(lua_State *L, const char *cmd)
361 const char *opt = strchr(cmd, '=');
362 lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
363 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
364 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
365 lua_remove(L, -2);
366 lua_pushvalue(L, -2);
367 lua_gettable(L, -2); /* Lookup library function. */
368 if (!lua_isfunction(L, -1)) {
369 lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
370 if (loadjitmodule(L))
371 return 1;
372 } else {
373 lua_remove(L, -2); /* Drop jit.* table. */
375 lua_remove(L, -2); /* Drop module name. */
376 return runcmdopt(L, opt ? opt+1 : opt);
379 /* Optimization flags. */
380 static int dojitopt(lua_State *L, const char *opt)
382 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
383 lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
384 lua_remove(L, -2);
385 lua_getfield(L, -1, "start");
386 lua_remove(L, -2);
387 return runcmdopt(L, opt);
390 /* Save or list bytecode. */
391 static int dobytecode(lua_State *L, char **argv)
393 int narg = 0;
394 lua_pushliteral(L, "bcsave");
395 if (loadjitmodule(L))
396 return 1;
397 if (argv[0][2]) {
398 narg++;
399 argv[0][1] = '-';
400 lua_pushstring(L, argv[0]+1);
402 for (argv++; *argv != NULL; narg++, argv++)
403 lua_pushstring(L, *argv);
404 report(L, lua_pcall(L, narg, 0, 0));
405 return -1;
408 /* check that argument has no extra characters at the end */
409 #define notail(x) {if ((x)[2] != '\0') return -1;}
411 #define FLAGS_INTERACTIVE 1
412 #define FLAGS_VERSION 2
413 #define FLAGS_EXEC 4
414 #define FLAGS_OPTION 8
415 #define FLAGS_NOENV 16
417 static int collectargs(char **argv, int *flags)
419 int i;
420 for (i = 1; argv[i] != NULL; i++) {
421 if (argv[i][0] != '-') /* Not an option? */
422 return i;
423 switch (argv[i][1]) { /* Check option. */
424 case '-':
425 notail(argv[i]);
426 return i+1;
427 case '\0':
428 return i;
429 case 'i':
430 notail(argv[i]);
431 *flags |= FLAGS_INTERACTIVE;
432 /* fallthrough */
433 case 'v':
434 notail(argv[i]);
435 *flags |= FLAGS_VERSION;
436 break;
437 case 'e':
438 *flags |= FLAGS_EXEC;
439 /* fallthrough */
440 case 'j': /* LuaJIT extension */
441 case 'l':
442 *flags |= FLAGS_OPTION;
443 if (argv[i][2] == '\0') {
444 i++;
445 if (argv[i] == NULL) return -1;
447 break;
448 case 'O': break; /* LuaJIT extension */
449 case 'b': /* LuaJIT extension */
450 if (*flags) return -1;
451 *flags |= FLAGS_EXEC;
452 return i+1;
453 case 'E':
454 *flags |= FLAGS_NOENV;
455 break;
456 default: return -1; /* invalid option */
459 return i;
462 static int runargs(lua_State *L, char **argv, int argn)
464 int i;
465 for (i = 1; i < argn; i++) {
466 if (argv[i] == NULL) continue;
467 lua_assert(argv[i][0] == '-');
468 switch (argv[i][1]) {
469 case 'e': {
470 const char *chunk = argv[i] + 2;
471 if (*chunk == '\0') chunk = argv[++i];
472 lua_assert(chunk != NULL);
473 if (dostring(L, chunk, "=(command line)") != 0)
474 return 1;
475 break;
477 case 'l': {
478 const char *filename = argv[i] + 2;
479 if (*filename == '\0') filename = argv[++i];
480 lua_assert(filename != NULL);
481 if (dolibrary(L, filename))
482 return 1;
483 break;
485 case 'j': { /* LuaJIT extension. */
486 const char *cmd = argv[i] + 2;
487 if (*cmd == '\0') cmd = argv[++i];
488 lua_assert(cmd != NULL);
489 if (dojitcmd(L, cmd))
490 return 1;
491 break;
493 case 'O': /* LuaJIT extension. */
494 if (dojitopt(L, argv[i] + 2))
495 return 1;
496 break;
497 case 'b': /* LuaJIT extension. */
498 return dobytecode(L, argv+i);
499 default: break;
502 return LUA_OK;
505 static int handle_luainit(lua_State *L)
507 #if LJ_TARGET_CONSOLE
508 const char *init = NULL;
509 #else
510 const char *init = getenv(LUA_INIT);
511 #endif
512 if (init == NULL)
513 return LUA_OK;
514 else if (init[0] == '@')
515 return dofile(L, init+1);
516 else
517 return dostring(L, init, "=" LUA_INIT);
520 static struct Smain {
521 char **argv;
522 int argc;
523 int status;
524 } smain;
526 static int pmain(lua_State *L)
528 struct Smain *s = &smain;
529 char **argv = s->argv;
530 int argn;
531 int flags = 0;
532 globalL = L;
533 LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */
535 argn = collectargs(argv, &flags);
536 if (argn < 0) { /* Invalid args? */
537 print_usage();
538 s->status = 1;
539 return 0;
542 if ((flags & FLAGS_NOENV)) {
543 lua_pushboolean(L, 1);
544 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
547 /* Stop collector during library initialization. */
548 lua_gc(L, LUA_GCSTOP, 0);
549 luaL_openlibs(L);
550 lua_gc(L, LUA_GCRESTART, -1);
552 createargtable(L, argv, s->argc, argn);
554 if (!(flags & FLAGS_NOENV)) {
555 s->status = handle_luainit(L);
556 if (s->status != LUA_OK) return 0;
559 if ((flags & FLAGS_VERSION)) print_version();
561 s->status = runargs(L, argv, argn);
562 if (s->status != LUA_OK) return 0;
564 if (s->argc > argn) {
565 s->status = handle_script(L, argv + argn);
566 if (s->status != LUA_OK) return 0;
569 if ((flags & FLAGS_INTERACTIVE)) {
570 print_jit_status(L);
571 dotty(L);
572 } else if (s->argc == argn && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
573 if (lua_stdin_is_tty()) {
574 print_version();
575 print_jit_status(L);
576 dotty(L);
577 } else {
578 dofile(L, NULL); /* Executes stdin as a file. */
581 return 0;
584 int main(int argc, char **argv)
586 int status;
587 lua_State *L;
588 if (!argv[0]) argv = empty_argv; else if (argv[0][0]) progname = argv[0];
589 L = lua_open();
590 if (L == NULL) {
591 l_message("cannot create state: not enough memory");
592 return EXIT_FAILURE;
594 smain.argc = argc;
595 smain.argv = argv;
596 status = lua_cpcall(L, pmain, NULL);
597 report(L, status);
598 lua_close(L);
599 return (status || smain.status > 0) ? EXIT_FAILURE : EXIT_SUCCESS;