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