OSX/iOS: Fix SDK incompatibility.
[luajit-2.0.git] / src / luajit.c
blob73e29d44f69ef783e4b7914dfced050646a1919d
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 */
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>
38 #endif
40 static lua_State *globalL = NULL;
41 static const char *progname = LUA_PROGNAME;
42 static char *empty_argv[2] = { NULL, NULL };
44 #if !LJ_TARGET_CONSOLE
45 static void lstop(lua_State *L, lua_Debug *ar)
47 (void)ar; /* unused arg. */
48 lua_sethook(L, NULL, 0, 0);
49 /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
50 luaL_where(L, 0);
51 lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
52 lua_error(L);
55 static void laction(int i)
57 signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
58 terminate process (default action) */
59 lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
61 #endif
63 static void print_usage(void)
65 fputs("usage: ", stderr);
66 fputs(progname, stderr);
67 fputs(" [options]... [script [args]...].\n"
68 "Available options are:\n"
69 " -e chunk Execute string " LUA_QL("chunk") ".\n"
70 " -l name Require library " LUA_QL("name") ".\n"
71 " -b ... Save or list bytecode.\n"
72 " -j cmd Perform LuaJIT control command.\n"
73 " -O[opt] Control LuaJIT optimizations.\n"
74 " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
75 " -v Show version information.\n"
76 " -E Ignore environment variables.\n"
77 " -- Stop handling options.\n"
78 " - Execute stdin and stop handling options.\n", stderr);
79 fflush(stderr);
82 static void l_message(const char *msg)
84 if (progname) { fputs(progname, stderr); fputc(':', stderr); fputc(' ', stderr); }
85 fputs(msg, stderr); fputc('\n', stderr);
86 fflush(stderr);
89 static int report(lua_State *L, int status)
91 if (status && !lua_isnil(L, -1)) {
92 const char *msg = lua_tostring(L, -1);
93 if (msg == NULL) msg = "(error object is not a string)";
94 l_message(msg);
95 lua_pop(L, 1);
97 return status;
100 static int traceback(lua_State *L)
102 if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
103 if (lua_isnoneornil(L, 1) ||
104 !luaL_callmeta(L, 1, "__tostring") ||
105 !lua_isstring(L, -1))
106 return 1; /* Return non-string error object. */
107 lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
109 luaL_traceback(L, L, lua_tostring(L, 1), 1);
110 return 1;
113 static int docall(lua_State *L, int narg, int clear)
115 int status;
116 int base = lua_gettop(L) - narg; /* function index */
117 lua_pushcfunction(L, traceback); /* push traceback function */
118 lua_insert(L, base); /* put it under chunk and args */
119 #if !LJ_TARGET_CONSOLE
120 signal(SIGINT, laction);
121 #endif
122 status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
123 #if !LJ_TARGET_CONSOLE
124 signal(SIGINT, SIG_DFL);
125 #endif
126 lua_remove(L, base); /* remove traceback function */
127 /* force a complete garbage collection in case of errors */
128 if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0);
129 return status;
132 static void print_version(void)
134 fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout);
137 static void print_jit_status(lua_State *L)
139 int n;
140 const char *s;
141 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
142 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
143 lua_remove(L, -2);
144 lua_getfield(L, -1, "status");
145 lua_remove(L, -2);
146 n = lua_gettop(L);
147 lua_call(L, 0, LUA_MULTRET);
148 fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout);
149 for (n++; (s = lua_tostring(L, n)); n++) {
150 putc(' ', stdout);
151 fputs(s, stdout);
153 putc('\n', stdout);
154 lua_settop(L, 0); /* clear stack */
157 static void createargtable(lua_State *L, char **argv, int argc, int argf)
159 int i;
160 lua_createtable(L, argc - argf, argf);
161 for (i = 0; i < argc; i++) {
162 lua_pushstring(L, argv[i]);
163 lua_rawseti(L, -2, i - argf);
165 lua_setglobal(L, "arg");
168 static int dofile(lua_State *L, const char *name)
170 int status = luaL_loadfile(L, name) || docall(L, 0, 1);
171 return report(L, status);
174 static int dostring(lua_State *L, const char *s, const char *name)
176 int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
177 return report(L, status);
180 static int dolibrary(lua_State *L, const char *name)
182 lua_getglobal(L, "require");
183 lua_pushstring(L, name);
184 return report(L, docall(L, 1, 1));
187 static void write_prompt(lua_State *L, int firstline)
189 const char *p;
190 lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
191 p = lua_tostring(L, -1);
192 if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
193 fputs(p, stdout);
194 fflush(stdout);
195 lua_pop(L, 1); /* remove global */
198 static int incomplete(lua_State *L, int status)
200 if (status == LUA_ERRSYNTAX) {
201 size_t lmsg;
202 const char *msg = lua_tolstring(L, -1, &lmsg);
203 const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
204 if (strstr(msg, LUA_QL("<eof>")) == tp) {
205 lua_pop(L, 1);
206 return 1;
209 return 0; /* else... */
212 static int pushline(lua_State *L, int firstline)
214 char buf[LUA_MAXINPUT];
215 write_prompt(L, firstline);
216 if (fgets(buf, LUA_MAXINPUT, stdin)) {
217 size_t len = strlen(buf);
218 if (len > 0 && buf[len-1] == '\n')
219 buf[len-1] = '\0';
220 if (firstline && buf[0] == '=')
221 lua_pushfstring(L, "return %s", buf+1);
222 else
223 lua_pushstring(L, buf);
224 return 1;
226 return 0;
229 static int loadline(lua_State *L)
231 int status;
232 lua_settop(L, 0);
233 if (!pushline(L, 1))
234 return -1; /* no input */
235 for (;;) { /* repeat until gets a complete line */
236 status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
237 if (!incomplete(L, status)) break; /* cannot try to add lines? */
238 if (!pushline(L, 0)) /* no more input? */
239 return -1;
240 lua_pushliteral(L, "\n"); /* add a new line... */
241 lua_insert(L, -2); /* ...between the two lines */
242 lua_concat(L, 3); /* join them */
244 lua_remove(L, 1); /* remove line */
245 return status;
248 static void dotty(lua_State *L)
250 int status;
251 const char *oldprogname = progname;
252 progname = NULL;
253 while ((status = loadline(L)) != -1) {
254 if (status == LUA_OK) status = docall(L, 0, 0);
255 report(L, status);
256 if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
257 lua_getglobal(L, "print");
258 lua_insert(L, 1);
259 if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
260 l_message(lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
261 lua_tostring(L, -1)));
264 lua_settop(L, 0); /* clear stack */
265 fputs("\n", stdout);
266 fflush(stdout);
267 progname = oldprogname;
270 static int handle_script(lua_State *L, char **argx)
272 int status;
273 const char *fname = argx[0];
274 if (strcmp(fname, "-") == 0 && strcmp(argx[-1], "--") != 0)
275 fname = NULL; /* stdin */
276 status = luaL_loadfile(L, fname);
277 if (status == LUA_OK) {
278 /* Fetch args from arg table. LUA_INIT or -e might have changed them. */
279 int narg = 0;
280 lua_getglobal(L, "arg");
281 if (lua_istable(L, -1)) {
282 do {
283 narg++;
284 lua_rawgeti(L, -narg, narg);
285 } while (!lua_isnil(L, -1));
286 lua_pop(L, 1);
287 lua_remove(L, -narg);
288 narg--;
289 } else {
290 lua_pop(L, 1);
292 status = docall(L, narg, 0);
294 return report(L, status);
297 /* Load add-on module. */
298 static int loadjitmodule(lua_State *L)
300 lua_getglobal(L, "require");
301 lua_pushliteral(L, "jit.");
302 lua_pushvalue(L, -3);
303 lua_concat(L, 2);
304 if (lua_pcall(L, 1, 1, 0)) {
305 const char *msg = lua_tostring(L, -1);
306 if (msg && !strncmp(msg, "module ", 7))
307 goto nomodule;
308 return report(L, 1);
310 lua_getfield(L, -1, "start");
311 if (lua_isnil(L, -1)) {
312 nomodule:
313 l_message("unknown luaJIT command or jit.* modules not installed");
314 return 1;
316 lua_remove(L, -2); /* Drop module table. */
317 return 0;
320 /* Run command with options. */
321 static int runcmdopt(lua_State *L, const char *opt)
323 int narg = 0;
324 if (opt && *opt) {
325 for (;;) { /* Split arguments. */
326 const char *p = strchr(opt, ',');
327 narg++;
328 if (!p) break;
329 if (p == opt)
330 lua_pushnil(L);
331 else
332 lua_pushlstring(L, opt, (size_t)(p - opt));
333 opt = p + 1;
335 if (*opt)
336 lua_pushstring(L, opt);
337 else
338 lua_pushnil(L);
340 return report(L, lua_pcall(L, narg, 0, 0));
343 /* JIT engine control command: try jit library first or load add-on module. */
344 static int dojitcmd(lua_State *L, const char *cmd)
346 const char *opt = strchr(cmd, '=');
347 lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
348 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
349 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
350 lua_remove(L, -2);
351 lua_pushvalue(L, -2);
352 lua_gettable(L, -2); /* Lookup library function. */
353 if (!lua_isfunction(L, -1)) {
354 lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
355 if (loadjitmodule(L))
356 return 1;
357 } else {
358 lua_remove(L, -2); /* Drop jit.* table. */
360 lua_remove(L, -2); /* Drop module name. */
361 return runcmdopt(L, opt ? opt+1 : opt);
364 /* Optimization flags. */
365 static int dojitopt(lua_State *L, const char *opt)
367 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
368 lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
369 lua_remove(L, -2);
370 lua_getfield(L, -1, "start");
371 lua_remove(L, -2);
372 return runcmdopt(L, opt);
375 /* Save or list bytecode. */
376 static int dobytecode(lua_State *L, char **argv)
378 int narg = 0;
379 lua_pushliteral(L, "bcsave");
380 if (loadjitmodule(L))
381 return 1;
382 if (argv[0][2]) {
383 narg++;
384 argv[0][1] = '-';
385 lua_pushstring(L, argv[0]+1);
387 for (argv++; *argv != NULL; narg++, argv++)
388 lua_pushstring(L, *argv);
389 report(L, lua_pcall(L, narg, 0, 0));
390 return -1;
393 /* check that argument has no extra characters at the end */
394 #define notail(x) {if ((x)[2] != '\0') return -1;}
396 #define FLAGS_INTERACTIVE 1
397 #define FLAGS_VERSION 2
398 #define FLAGS_EXEC 4
399 #define FLAGS_OPTION 8
400 #define FLAGS_NOENV 16
402 static int collectargs(char **argv, int *flags)
404 int i;
405 for (i = 1; argv[i] != NULL; i++) {
406 if (argv[i][0] != '-') /* Not an option? */
407 return i;
408 switch (argv[i][1]) { /* Check option. */
409 case '-':
410 notail(argv[i]);
411 return i+1;
412 case '\0':
413 return i;
414 case 'i':
415 notail(argv[i]);
416 *flags |= FLAGS_INTERACTIVE;
417 /* fallthrough */
418 case 'v':
419 notail(argv[i]);
420 *flags |= FLAGS_VERSION;
421 break;
422 case 'e':
423 *flags |= FLAGS_EXEC;
424 /* fallthrough */
425 case 'j': /* LuaJIT extension */
426 case 'l':
427 *flags |= FLAGS_OPTION;
428 if (argv[i][2] == '\0') {
429 i++;
430 if (argv[i] == NULL) return -1;
432 break;
433 case 'O': break; /* LuaJIT extension */
434 case 'b': /* LuaJIT extension */
435 if (*flags) return -1;
436 *flags |= FLAGS_EXEC;
437 return i+1;
438 case 'E':
439 *flags |= FLAGS_NOENV;
440 break;
441 default: return -1; /* invalid option */
444 return i;
447 static int runargs(lua_State *L, char **argv, int argn)
449 int i;
450 for (i = 1; i < argn; i++) {
451 if (argv[i] == NULL) continue;
452 lua_assert(argv[i][0] == '-');
453 switch (argv[i][1]) {
454 case 'e': {
455 const char *chunk = argv[i] + 2;
456 if (*chunk == '\0') chunk = argv[++i];
457 lua_assert(chunk != NULL);
458 if (dostring(L, chunk, "=(command line)") != 0)
459 return 1;
460 break;
462 case 'l': {
463 const char *filename = argv[i] + 2;
464 if (*filename == '\0') filename = argv[++i];
465 lua_assert(filename != NULL);
466 if (dolibrary(L, filename))
467 return 1;
468 break;
470 case 'j': { /* LuaJIT extension. */
471 const char *cmd = argv[i] + 2;
472 if (*cmd == '\0') cmd = argv[++i];
473 lua_assert(cmd != NULL);
474 if (dojitcmd(L, cmd))
475 return 1;
476 break;
478 case 'O': /* LuaJIT extension. */
479 if (dojitopt(L, argv[i] + 2))
480 return 1;
481 break;
482 case 'b': /* LuaJIT extension. */
483 return dobytecode(L, argv+i);
484 default: break;
487 return LUA_OK;
490 static int handle_luainit(lua_State *L)
492 #if LJ_TARGET_CONSOLE
493 const char *init = NULL;
494 #else
495 const char *init = getenv(LUA_INIT);
496 #endif
497 if (init == NULL)
498 return LUA_OK;
499 else if (init[0] == '@')
500 return dofile(L, init+1);
501 else
502 return dostring(L, init, "=" LUA_INIT);
505 static struct Smain {
506 char **argv;
507 int argc;
508 int status;
509 } smain;
511 static int pmain(lua_State *L)
513 struct Smain *s = &smain;
514 char **argv = s->argv;
515 int argn;
516 int flags = 0;
517 globalL = L;
518 LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */
520 argn = collectargs(argv, &flags);
521 if (argn < 0) { /* Invalid args? */
522 print_usage();
523 s->status = 1;
524 return 0;
527 if ((flags & FLAGS_NOENV)) {
528 lua_pushboolean(L, 1);
529 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
532 /* Stop collector during library initialization. */
533 lua_gc(L, LUA_GCSTOP, 0);
534 luaL_openlibs(L);
535 lua_gc(L, LUA_GCRESTART, -1);
537 createargtable(L, argv, s->argc, argn);
539 if (!(flags & FLAGS_NOENV)) {
540 s->status = handle_luainit(L);
541 if (s->status != LUA_OK) return 0;
544 if ((flags & FLAGS_VERSION)) print_version();
546 s->status = runargs(L, argv, argn);
547 if (s->status != LUA_OK) return 0;
549 if (s->argc > argn) {
550 s->status = handle_script(L, argv + argn);
551 if (s->status != LUA_OK) return 0;
554 if ((flags & FLAGS_INTERACTIVE)) {
555 print_jit_status(L);
556 dotty(L);
557 } else if (s->argc == argn && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
558 if (lua_stdin_is_tty()) {
559 print_version();
560 print_jit_status(L);
561 dotty(L);
562 } else {
563 dofile(L, NULL); /* Executes stdin as a file. */
566 return 0;
569 int main(int argc, char **argv)
571 int status;
572 lua_State *L;
573 if (!argv[0]) argv = empty_argv; else if (argv[0][0]) progname = argv[0];
574 L = lua_open();
575 if (L == NULL) {
576 l_message("cannot create state: not enough memory");
577 return EXIT_FAILURE;
579 smain.argc = argc;
580 smain.argv = argv;
581 status = lua_cpcall(L, pmain, NULL);
582 report(L, status);
583 lua_close(L);
584 return (status || smain.status > 0) ? EXIT_FAILURE : EXIT_SUCCESS;