1/*-
2 * Copyright (c) 2011 Wojciech A. Koszek <wkoszek@FreeBSD.org>
3 * Copyright (c) 2014 Pedro Souza <pedrosouza@freebsd.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <stand.h>
29#include "bootstrap.h"
30
31#define lua_c
32
33#include "lstd.h"
34
35#include <lua.h>
36#include <ldebug.h>
37#include <lauxlib.h>
38#include <lualib.h>
39
40#include <lerrno.h>
41#include <lfs.h>
42#include <lutils.h>
43
44struct interp_lua_softc {
45	lua_State	*luap;
46};
47
48static struct interp_lua_softc lua_softc;
49
50#ifdef LUA_DEBUG
51#define	LDBG(...)	do {			\
52	printf("%s(%d): ", __func__, __LINE__);	\
53	printf(__VA_ARGS__);			\
54	printf("\n");				\
55} while (0)
56#else
57#define	LDBG(...)
58#endif
59
60#define	LOADER_LUA	LUA_PATH "/loader.lua"
61
62INTERP_DEFINE("lua");
63
64static void *
65interp_lua_realloc(void *ud __unused, void *ptr, size_t osize __unused, size_t nsize)
66{
67
68	if (nsize == 0) {
69		free(ptr);
70		return NULL;
71	}
72	return realloc(ptr, nsize);
73}
74
75/*
76 * The libraries commented out below either lack the proper
77 * support from libsa, or they are unlikely to be useful
78 * in the bootloader, so have been commented out.
79 */
80static const luaL_Reg loadedlibs[] = {
81  {"_G", luaopen_base},
82  {LUA_LOADLIBNAME, luaopen_package},
83//  {LUA_COLIBNAME, luaopen_coroutine},
84//  {LUA_TABLIBNAME, luaopen_table},
85  {LUA_STRLIBNAME, luaopen_string},
86//  {LUA_IOLIBNAME, luaopen_io},
87//  {LUA_OSLIBNAME, luaopen_os},
88//  {LUA_MATHLIBNAME, luaopen_math},
89//  {LUA_UTF8LIBNAME, luaopen_utf8},
90//  {LUA_DBLIBNAME, luaopen_debug},
91  {"errno", luaopen_errno},
92  {"io", luaopen_io},
93  {"lfs", luaopen_lfs},
94  {"loader", luaopen_loader},
95  {"pager", luaopen_pager},
96  {NULL, NULL}
97};
98
99void
100interp_init(void)
101{
102	lua_State *luap;
103	struct interp_lua_softc	*softc = &lua_softc;
104	const char *filename;
105	const luaL_Reg *lib;
106	lua_init_md_t **fnpp;
107
108	TSENTER();
109
110	setenv("script.lang", "lua", 1);
111	LDBG("creating context");
112
113	luap = lua_newstate(interp_lua_realloc, NULL);
114	if (luap == NULL) {
115		printf("problem initializing the Lua interpreter\n");
116		abort();
117	}
118	softc->luap = luap;
119
120	/* "require" functions from 'loadedlibs' and set results to global table */
121	for (lib = loadedlibs; lib->func; lib++) {
122		luaL_requiref(luap, lib->name, lib->func, 1);
123		lua_pop(luap, 1);  /* remove lib */
124	}
125
126	LUA_FOREACH_SET(fnpp)
127	    (*fnpp)(luap);
128
129	filename = getenv("loader_lua");
130	if (filename == NULL)
131		filename = LOADER_LUA;
132	if (interp_include(filename) != 0) {
133		const char *errstr = lua_tostring(luap, -1);
134		errstr = errstr == NULL ? "unknown" : errstr;
135		printf("ERROR: %s.\n", errstr);
136		lua_pop(luap, 1);
137		setenv("autoboot_delay", "NO", 1);
138	}
139
140	TSEXIT();
141}
142
143int
144interp_run(const char *line)
145{
146	int	argc, nargc;
147	char	**argv;
148	lua_State *luap;
149	struct interp_lua_softc	*softc = &lua_softc;
150	int status, ret;
151
152	TSENTER();
153	luap = softc->luap;
154	LDBG("executing line...");
155	if ((status = luaL_dostring(luap, line)) != 0) {
156		lua_pop(luap, 1);
157		/*
158		 * The line wasn't executable as lua; run it through parse to
159		 * to get consistent parsing of command line arguments, then
160		 * run it through cli_execute. If that fails, then we'll try it
161		 * as a builtin.
162		 */
163		command_errmsg = NULL;
164		if (parse(&argc, &argv, line) == 0) {
165			lua_getglobal(luap, "cli_execute");
166			for (nargc = 0; nargc < argc; ++nargc) {
167				lua_pushstring(luap, argv[nargc]);
168			}
169			status = lua_pcall(luap, argc, 1, 0);
170			ret = lua_tointeger(luap, 1);
171			lua_pop(luap, 1);
172			if (status != 0 || ret != 0) {
173				/*
174				 * Lua cli_execute will pass the function back
175				 * through loader.command, which is a proxy to
176				 * interp_builtin_cmd. If we failed to interpret
177				 * the command, though, then there's a chance
178				 * that didn't happen. Call interp_builtin_cmd
179				 * directly if our lua_pcall was not successful.
180				 */
181				status = interp_builtin_cmd(argc, argv);
182			}
183			if (status != 0) {
184				if (command_errmsg != NULL)
185					printf("%s\n", command_errmsg);
186				else
187					printf("Command failed\n");
188				status = CMD_ERROR;
189			}
190			free(argv);
191		} else {
192			printf("Failed to parse \'%s\'\n", line);
193			status = CMD_ERROR;
194		}
195	}
196
197	TSEXIT();
198	return (status == 0 ? CMD_OK : CMD_ERROR);
199}
200
201int
202interp_include(const char *filename)
203{
204	struct interp_lua_softc	*softc = &lua_softc;
205
206	LDBG("loading file %s", filename);
207
208	return (luaL_dofile(softc->luap, filename));
209}
210