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