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