1 /* 2 ** $Id: lua.c $ 3 ** Lua stand-alone interpreter 4 ** See Copyright Notice in lua.h 5 */ 6 7 #define lua_c 8 9 #include "lprefix.h" 10 11 12 #include <stdio.h> 13 #include <stdlib.h> 14 #include <string.h> 15 16 #include <signal.h> 17 18 #include "lua.h" 19 20 #include "lauxlib.h" 21 #include "lualib.h" 22 23 24 #if !defined(LUA_PROGNAME) 25 #define LUA_PROGNAME "lua" 26 #endif 27 28 #if !defined(LUA_INIT_VAR) 29 #define LUA_INIT_VAR "LUA_INIT" 30 #endif 31 32 #define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX 33 34 35 static lua_State *globalL = NULL; 36 37 static const char *progname = LUA_PROGNAME; 38 39 40 #if defined(LUA_USE_POSIX) /* { */ 41 42 /* 43 ** Use 'sigaction' when available. 44 */ 45 static void setsignal (int sig, void (*handler)(int)) { 46 struct sigaction sa; 47 sa.sa_handler = handler; 48 sa.sa_flags = 0; 49 sigemptyset(&sa.sa_mask); /* do not mask any signal */ 50 sigaction(sig, &sa, NULL); 51 } 52 53 #else /* }{ */ 54 55 #define setsignal signal 56 57 #endif /* } */ 58 59 60 /* 61 ** Hook set by signal function to stop the interpreter. 62 */ 63 static void lstop (lua_State *L, lua_Debug *ar) { 64 (void)ar; /* unused arg. */ 65 lua_sethook(L, NULL, 0, 0); /* reset hook */ 66 luaL_error(L, "interrupted!"); 67 } 68 69 70 /* 71 ** Function to be called at a C signal. Because a C signal cannot 72 ** just change a Lua state (as there is no proper synchronization), 73 ** this function only sets a hook that, when called, will stop the 74 ** interpreter. 75 */ 76 static void laction (int i) { 77 int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT; 78 setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */ 79 lua_sethook(globalL, lstop, flag, 1); 80 } 81 82 83 static void print_usage (const char *badoption) { 84 lua_writestringerror("%s: ", progname); 85 if (badoption[1] == 'e' || badoption[1] == 'l') 86 lua_writestringerror("'%s' needs argument\n", badoption); 87 else 88 lua_writestringerror("unrecognized option '%s'\n", badoption); 89 lua_writestringerror( 90 "usage: %s [options] [script [args]]\n" 91 "Available options are:\n" 92 " -e stat execute string 'stat'\n" 93 " -i enter interactive mode after executing 'script'\n" 94 " -l mod require library 'mod' into global 'mod'\n" 95 " -l g=mod require library 'mod' into global 'g'\n" 96 " -v show version information\n" 97 " -E ignore environment variables\n" 98 " -W turn warnings on\n" 99 " -- stop handling options\n" 100 " - stop handling options and execute stdin\n" 101 , 102 progname); 103 } 104 105 106 /* 107 ** Prints an error message, adding the program name in front of it 108 ** (if present) 109 */ 110 static void l_message (const char *pname, const char *msg) { 111 if (pname) lua_writestringerror("%s: ", pname); 112 lua_writestringerror("%s\n", msg); 113 } 114 115 116 /* 117 ** Check whether 'status' is not OK and, if so, prints the error 118 ** message on the top of the stack. It assumes that the error object 119 ** is a string, as it was either generated by Lua or by 'msghandler'. 120 */ 121 static int report (lua_State *L, int status) { 122 if (status != LUA_OK) { 123 const char *msg = lua_tostring(L, -1); 124 l_message(progname, msg); 125 lua_pop(L, 1); /* remove message */ 126 } 127 return status; 128 } 129 130 131 /* 132 ** Message handler used to run all chunks 133 */ 134 static int msghandler (lua_State *L) { 135 const char *msg = lua_tostring(L, 1); 136 if (msg == NULL) { /* is error object not a string? */ 137 if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */ 138 lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */ 139 return 1; /* that is the message */ 140 else 141 msg = lua_pushfstring(L, "(error object is a %s value)", 142 luaL_typename(L, 1)); 143 } 144 luaL_traceback(L, L, msg, 1); /* append a standard traceback */ 145 return 1; /* return the traceback */ 146 } 147 148 149 /* 150 ** Interface to 'lua_pcall', which sets appropriate message function 151 ** and C-signal handler. Used to run all chunks. 152 */ 153 static int docall (lua_State *L, int narg, int nres) { 154 int status; 155 int base = lua_gettop(L) - narg; /* function index */ 156 lua_pushcfunction(L, msghandler); /* push message handler */ 157 lua_insert(L, base); /* put it under function and args */ 158 globalL = L; /* to be available to 'laction' */ 159 setsignal(SIGINT, laction); /* set C-signal handler */ 160 status = lua_pcall(L, narg, nres, base); 161 setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */ 162 lua_remove(L, base); /* remove message handler from the stack */ 163 return status; 164 } 165 166 167 static void print_version (void) { 168 lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); 169 lua_writeline(); 170 } 171 172 173 /* 174 ** Create the 'arg' table, which stores all arguments from the 175 ** command line ('argv'). It should be aligned so that, at index 0, 176 ** it has 'argv[script]', which is the script name. The arguments 177 ** to the script (everything after 'script') go to positive indices; 178 ** other arguments (before the script name) go to negative indices. 179 ** If there is no script name, assume interpreter's name as base. 180 */ 181 static void createargtable (lua_State *L, char **argv, int argc, int script) { 182 int i, narg; 183 if (script == argc) script = 0; /* no script name? */ 184 narg = argc - (script + 1); /* number of positive indices */ 185 lua_createtable(L, narg, script + 1); 186 for (i = 0; i < argc; i++) { 187 lua_pushstring(L, argv[i]); 188 lua_rawseti(L, -2, i - script); 189 } 190 lua_setglobal(L, "arg"); 191 } 192 193 194 static int dochunk (lua_State *L, int status) { 195 if (status == LUA_OK) status = docall(L, 0, 0); 196 return report(L, status); 197 } 198 199 200 static int dofile (lua_State *L, const char *name) { 201 return dochunk(L, luaL_loadfile(L, name)); 202 } 203 204 205 static int dostring (lua_State *L, const char *s, const char *name) { 206 return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name)); 207 } 208 209 210 /* 211 ** Receives 'globname[=modname]' and runs 'globname = require(modname)'. 212 */ 213 static int dolibrary (lua_State *L, char *globname) { 214 int status; 215 char *modname = strchr(globname, '='); 216 if (modname == NULL) /* no explicit name? */ 217 modname = globname; /* module name is equal to global name */ 218 else { 219 *modname = '\0'; /* global name ends here */ 220 modname++; /* module name starts after the '=' */ 221 } 222 lua_getglobal(L, "require"); 223 lua_pushstring(L, modname); 224 status = docall(L, 1, 1); /* call 'require(modname)' */ 225 if (status == LUA_OK) 226 lua_setglobal(L, globname); /* globname = require(modname) */ 227 return report(L, status); 228 } 229 230 231 /* 232 ** Push on the stack the contents of table 'arg' from 1 to #arg 233 */ 234 static int pushargs (lua_State *L) { 235 int i, n; 236 if (lua_getglobal(L, "arg") != LUA_TTABLE) 237 luaL_error(L, "'arg' is not a table"); 238 n = (int)luaL_len(L, -1); 239 luaL_checkstack(L, n + 3, "too many arguments to script"); 240 for (i = 1; i <= n; i++) 241 lua_rawgeti(L, -i, i); 242 lua_remove(L, -i); /* remove table from the stack */ 243 return n; 244 } 245 246 247 static int handle_script (lua_State *L, char **argv) { 248 int status; 249 const char *fname = argv[0]; 250 if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0) 251 fname = NULL; /* stdin */ 252 status = luaL_loadfile(L, fname); 253 if (status == LUA_OK) { 254 int n = pushargs(L); /* push arguments to script */ 255 status = docall(L, n, LUA_MULTRET); 256 } 257 return report(L, status); 258 } 259 260 261 /* bits of various argument indicators in 'args' */ 262 #define has_error 1 /* bad option */ 263 #define has_i 2 /* -i */ 264 #define has_v 4 /* -v */ 265 #define has_e 8 /* -e */ 266 #define has_E 16 /* -E */ 267 268 269 /* 270 ** Traverses all arguments from 'argv', returning a mask with those 271 ** needed before running any Lua code (or an error code if it finds 272 ** any invalid argument). 'first' returns the first not-handled argument 273 ** (either the script name or a bad argument in case of error). 274 */ 275 static int collectargs (char **argv, int *first) { 276 int args = 0; 277 int i; 278 for (i = 1; argv[i] != NULL; i++) { 279 *first = i; 280 if (argv[i][0] != '-') /* not an option? */ 281 return args; /* stop handling options */ 282 switch (argv[i][1]) { /* else check option */ 283 case '-': /* '--' */ 284 if (argv[i][2] != '\0') /* extra characters after '--'? */ 285 return has_error; /* invalid option */ 286 *first = i + 1; 287 return args; 288 case '\0': /* '-' */ 289 return args; /* script "name" is '-' */ 290 case 'E': 291 if (argv[i][2] != '\0') /* extra characters? */ 292 return has_error; /* invalid option */ 293 args |= has_E; 294 break; 295 case 'W': 296 if (argv[i][2] != '\0') /* extra characters? */ 297 return has_error; /* invalid option */ 298 break; 299 case 'i': 300 args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */ 301 case 'v': 302 if (argv[i][2] != '\0') /* extra characters? */ 303 return has_error; /* invalid option */ 304 args |= has_v; 305 break; 306 case 'e': 307 args |= has_e; /* FALLTHROUGH */ 308 case 'l': /* both options need an argument */ 309 if (argv[i][2] == '\0') { /* no concatenated argument? */ 310 i++; /* try next 'argv' */ 311 if (argv[i] == NULL || argv[i][0] == '-') 312 return has_error; /* no next argument or it is another option */ 313 } 314 break; 315 default: /* invalid option */ 316 return has_error; 317 } 318 } 319 *first = i; /* no script name */ 320 return args; 321 } 322 323 324 /* 325 ** Processes options 'e' and 'l', which involve running Lua code, and 326 ** 'W', which also affects the state. 327 ** Returns 0 if some code raises an error. 328 */ 329 static int runargs (lua_State *L, char **argv, int n) { 330 int i; 331 for (i = 1; i < n; i++) { 332 int option = argv[i][1]; 333 lua_assert(argv[i][0] == '-'); /* already checked */ 334 switch (option) { 335 case 'e': case 'l': { 336 int status; 337 char *extra = argv[i] + 2; /* both options need an argument */ 338 if (*extra == '\0') extra = argv[++i]; 339 lua_assert(extra != NULL); 340 status = (option == 'e') 341 ? dostring(L, extra, "=(command line)") 342 : dolibrary(L, extra); 343 if (status != LUA_OK) return 0; 344 break; 345 } 346 case 'W': 347 lua_warning(L, "@on", 0); /* warnings on */ 348 break; 349 } 350 } 351 return 1; 352 } 353 354 355 static int handle_luainit (lua_State *L) { 356 const char *name = "=" LUA_INITVARVERSION; 357 const char *init = getenv(name + 1); 358 if (init == NULL) { 359 name = "=" LUA_INIT_VAR; 360 init = getenv(name + 1); /* try alternative name */ 361 } 362 if (init == NULL) return LUA_OK; 363 else if (init[0] == '@') 364 return dofile(L, init+1); 365 else 366 return dostring(L, init, name); 367 } 368 369 370 /* 371 ** {================================================================== 372 ** Read-Eval-Print Loop (REPL) 373 ** =================================================================== 374 */ 375 376 #if !defined(LUA_PROMPT) 377 #define LUA_PROMPT "> " 378 #define LUA_PROMPT2 ">> " 379 #endif 380 381 #if !defined(LUA_MAXINPUT) 382 #define LUA_MAXINPUT 512 383 #endif 384 385 386 /* 387 ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that 388 ** is, whether we're running lua interactively). 389 */ 390 #if !defined(lua_stdin_is_tty) /* { */ 391 392 #if defined(LUA_USE_POSIX) /* { */ 393 394 #include <unistd.h> 395 #define lua_stdin_is_tty() isatty(0) 396 397 #elif defined(LUA_USE_WINDOWS) /* }{ */ 398 399 #include <io.h> 400 #include <windows.h> 401 402 #define lua_stdin_is_tty() _isatty(_fileno(stdin)) 403 404 #else /* }{ */ 405 406 /* ISO C definition */ 407 #define lua_stdin_is_tty() 1 /* assume stdin is a tty */ 408 409 #endif /* } */ 410 411 #endif /* } */ 412 413 414 /* 415 ** lua_readline defines how to show a prompt and then read a line from 416 ** the standard input. 417 ** lua_saveline defines how to "save" a read line in a "history". 418 ** lua_freeline defines how to free a line read by lua_readline. 419 */ 420 #if !defined(lua_readline) /* { */ 421 422 #if defined(LUA_USE_READLINE) /* { */ 423 424 #include <readline/readline.h> 425 #include <readline/history.h> 426 #define lua_initreadline(L) ((void)L, rl_readline_name="lua") 427 #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) 428 #define lua_saveline(L,line) ((void)L, add_history(line)) 429 #define lua_freeline(L,b) ((void)L, free(b)) 430 431 #else /* }{ */ 432 433 #define lua_initreadline(L) ((void)L) 434 #define lua_readline(L,b,p) \ 435 ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ 436 fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ 437 #define lua_saveline(L,line) { (void)L; (void)line; } 438 #define lua_freeline(L,b) { (void)L; (void)b; } 439 440 #endif /* } */ 441 442 #endif /* } */ 443 444 445 /* 446 ** Return the string to be used as a prompt by the interpreter. Leave 447 ** the string (or nil, if using the default value) on the stack, to keep 448 ** it anchored. 449 */ 450 static const char *get_prompt (lua_State *L, int firstline) { 451 if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL) 452 return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */ 453 else { /* apply 'tostring' over the value */ 454 const char *p = luaL_tolstring(L, -1, NULL); 455 lua_remove(L, -2); /* remove original value */ 456 return p; 457 } 458 } 459 460 /* mark in error messages for incomplete statements */ 461 #define EOFMARK "<eof>" 462 #define marklen (sizeof(EOFMARK)/sizeof(char) - 1) 463 464 465 /* 466 ** Check whether 'status' signals a syntax error and the error 467 ** message at the top of the stack ends with the above mark for 468 ** incomplete statements. 469 */ 470 static int incomplete (lua_State *L, int status) { 471 if (status == LUA_ERRSYNTAX) { 472 size_t lmsg; 473 const char *msg = lua_tolstring(L, -1, &lmsg); 474 if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) { 475 lua_pop(L, 1); 476 return 1; 477 } 478 } 479 return 0; /* else... */ 480 } 481 482 483 /* 484 ** Prompt the user, read a line, and push it into the Lua stack. 485 */ 486 static int pushline (lua_State *L, int firstline) { 487 char buffer[LUA_MAXINPUT]; 488 char *b = buffer; 489 size_t l; 490 const char *prmt = get_prompt(L, firstline); 491 int readstatus = lua_readline(L, b, prmt); 492 if (readstatus == 0) 493 return 0; /* no input (prompt will be popped by caller) */ 494 lua_pop(L, 1); /* remove prompt */ 495 l = strlen(b); 496 if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ 497 b[--l] = '\0'; /* remove it */ 498 if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */ 499 lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */ 500 else 501 lua_pushlstring(L, b, l); 502 lua_freeline(L, b); 503 return 1; 504 } 505 506 507 /* 508 ** Try to compile line on the stack as 'return <line>;'; on return, stack 509 ** has either compiled chunk or original line (if compilation failed). 510 */ 511 static int addreturn (lua_State *L) { 512 const char *line = lua_tostring(L, -1); /* original line */ 513 const char *retline = lua_pushfstring(L, "return %s;", line); 514 int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin"); 515 if (status == LUA_OK) { 516 lua_remove(L, -2); /* remove modified line */ 517 if (line[0] != '\0') /* non empty? */ 518 lua_saveline(L, line); /* keep history */ 519 } 520 else 521 lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */ 522 return status; 523 } 524 525 526 /* 527 ** Read multiple lines until a complete Lua statement 528 */ 529 static int multiline (lua_State *L) { 530 for (;;) { /* repeat until gets a complete statement */ 531 size_t len; 532 const char *line = lua_tolstring(L, 1, &len); /* get what it has */ 533 int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */ 534 if (!incomplete(L, status) || !pushline(L, 0)) { 535 lua_saveline(L, line); /* keep history */ 536 return status; /* cannot or should not try to add continuation line */ 537 } 538 lua_pushliteral(L, "\n"); /* add newline... */ 539 lua_insert(L, -2); /* ...between the two lines */ 540 lua_concat(L, 3); /* join them */ 541 } 542 } 543 544 545 /* 546 ** Read a line and try to load (compile) it first as an expression (by 547 ** adding "return " in front of it) and second as a statement. Return 548 ** the final status of load/call with the resulting function (if any) 549 ** in the top of the stack. 550 */ 551 static int loadline (lua_State *L) { 552 int status; 553 lua_settop(L, 0); 554 if (!pushline(L, 1)) 555 return -1; /* no input */ 556 if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */ 557 status = multiline(L); /* try as command, maybe with continuation lines */ 558 lua_remove(L, 1); /* remove line from the stack */ 559 lua_assert(lua_gettop(L) == 1); 560 return status; 561 } 562 563 564 /* 565 ** Prints (calling the Lua 'print' function) any values on the stack 566 */ 567 static void l_print (lua_State *L) { 568 int n = lua_gettop(L); 569 if (n > 0) { /* any result to be printed? */ 570 luaL_checkstack(L, LUA_MINSTACK, "too many results to print"); 571 lua_getglobal(L, "print"); 572 lua_insert(L, 1); 573 if (lua_pcall(L, n, 0, 0) != LUA_OK) 574 l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)", 575 lua_tostring(L, -1))); 576 } 577 } 578 579 580 /* 581 ** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and 582 ** print any results. 583 */ 584 static void doREPL (lua_State *L) { 585 int status; 586 const char *oldprogname = progname; 587 progname = NULL; /* no 'progname' on errors in interactive mode */ 588 lua_initreadline(L); 589 while ((status = loadline(L)) != -1) { 590 if (status == LUA_OK) 591 status = docall(L, 0, LUA_MULTRET); 592 if (status == LUA_OK) l_print(L); 593 else report(L, status); 594 } 595 lua_settop(L, 0); /* clear stack */ 596 lua_writeline(); 597 progname = oldprogname; 598 } 599 600 /* }================================================================== */ 601 602 603 /* 604 ** Main body of stand-alone interpreter (to be called in protected mode). 605 ** Reads the options and handles them all. 606 */ 607 static int pmain (lua_State *L) { 608 int argc = (int)lua_tointeger(L, 1); 609 char **argv = (char **)lua_touserdata(L, 2); 610 int script; 611 int args = collectargs(argv, &script); 612 luaL_checkversion(L); /* check that interpreter has correct version */ 613 if (argv[0] && argv[0][0]) progname = argv[0]; 614 if (args == has_error) { /* bad arg? */ 615 print_usage(argv[script]); /* 'script' has index of bad arg. */ 616 return 0; 617 } 618 if (args & has_v) /* option '-v'? */ 619 print_version(); 620 if (args & has_E) { /* option '-E'? */ 621 lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */ 622 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); 623 } 624 luaL_openlibs(L); /* open standard libraries */ 625 createargtable(L, argv, argc, script); /* create table 'arg' */ 626 lua_gc(L, LUA_GCGEN, 0, 0); /* GC in generational mode */ 627 if (!(args & has_E)) { /* no option '-E'? */ 628 if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */ 629 return 0; /* error running LUA_INIT */ 630 } 631 if (!runargs(L, argv, script)) /* execute arguments -e and -l */ 632 return 0; /* something failed */ 633 if (script < argc && /* execute main script (if there is one) */ 634 handle_script(L, argv + script) != LUA_OK) 635 return 0; 636 if (args & has_i) /* -i option? */ 637 doREPL(L); /* do read-eval-print loop */ 638 else if (script == argc && !(args & (has_e | has_v))) { /* no arguments? */ 639 if (lua_stdin_is_tty()) { /* running in interactive mode? */ 640 print_version(); 641 doREPL(L); /* do read-eval-print loop */ 642 } 643 else dofile(L, NULL); /* executes stdin as a file */ 644 } 645 lua_pushboolean(L, 1); /* signal no errors */ 646 return 1; 647 } 648 649 650 int main (int argc, char **argv) { 651 int status, result; 652 lua_State *L = luaL_newstate(); /* create state */ 653 if (L == NULL) { 654 l_message(argv[0], "cannot create state: not enough memory"); 655 return EXIT_FAILURE; 656 } 657 lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */ 658 lua_pushinteger(L, argc); /* 1st argument */ 659 lua_pushlightuserdata(L, argv); /* 2nd argument */ 660 status = lua_pcall(L, 2, 1, 0); /* do the call */ 661 result = lua_toboolean(L, -1); /* get result */ 662 report(L, status); 663 lua_close(L); 664 return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE; 665 } 666 667