Debian Codegraph @

modules/module-lua-scripting/wplua/wplua.c

raw
1 /* WirePlumber
2 *
3 * Copyright © 2020 Collabora Ltd.
4 * @author George Kiagiadakis <[email protected]>
5 *
6 * SPDX-License-Identifier: MIT
7 */
8
9 #include "wplua.h"
10 #include "private.h"
11 #include <wp/wp.h>
12
13 WP_LOG_TOPIC (log_topic_wplua, "wplua")
14
15 #define URI_SANDBOX "resource:///org/freedesktop/pipewire/wireplumber/wplua/sandbox.lua"
16
17 extern void _wplua_register_resource (void);
18
19 typedef struct {
20 guint64 refcount;
21 } WpLuaExtraData;
22
23 G_DEFINE_QUARK (wplua, wp_domain_lua);
24
25 static WpLuaExtraData *
26 wplua_getextradata (lua_State *L)
27 {
28 WpLuaExtraData *data;
29
30 G_STATIC_ASSERT(LUA_EXTRASPACE >= sizeof(data));
31 memcpy (&data, lua_getextraspace (L), sizeof(data));
32 return data;
33 }
34
35 static void
36 _wplua_openlibs (lua_State *L)
37 {
38 /* http://www.lua.org/manual/5.3/manual.html#luaL_requiref
39 * http://www.lua.org/source/5.3/linit.c.html */
40 static const luaL_Reg loadedlibs[] = {
41 {"_G", luaopen_base},
42 {LUA_LOADLIBNAME, luaopen_package},
43 {LUA_COLIBNAME, luaopen_coroutine},
44 {LUA_TABLIBNAME, luaopen_table},
45 /* {LUA_IOLIBNAME, luaopen_io}, */
46 {LUA_OSLIBNAME, luaopen_os},
47 {LUA_STRLIBNAME, luaopen_string},
48 {LUA_MATHLIBNAME, luaopen_math},
49 {LUA_UTF8LIBNAME, luaopen_utf8},
50 {LUA_DBLIBNAME, luaopen_debug},
51 {NULL, NULL}
52 };
53 const luaL_Reg *lib;
54
55 for (lib = loadedlibs; lib->func; lib++) {
56 luaL_requiref (L, lib->name, lib->func, 1);
57 lua_pop (L, 1);
58 }
59 }
60
61 static int
62 _wplua_errhandler (lua_State *L)
63 {
64 luaL_traceback (L, L, NULL, 1);
65 wp_warning ("%s\n%s", lua_tostring (L, -2), lua_tostring (L, -1));
66 lua_pop (L, 2);
67 return 0;
68 }
69
70 int
71 _wplua_pcall (lua_State *L, int nargs, int nret)
72 {
73 int slots = lua_gettop (L);
74 int ret = LUA_OK;
75 /* 1 stack slot needed for error handler. */
76 int hpos, stack_slots = 1;
77
78 if (nargs < 0)
79 g_error ("negative number of arguments");
80 /* Need nargs + 1 stack slots for function and its arguments. */
81 if (slots <= nargs)
82 g_error ("not enough stack slots for arguments and function");
83 if (nret != LUA_MULTRET) {
84 if (nret - nargs > 1) {
85 /* Need more stack slots: 1 for the error handler and (nret - (nargs + 1))
86 * for the return values (after popping the function and its arguments). */
87 stack_slots = nret - nargs;
88 } else if (nret < 0)
89 g_error ("negative number of return values");
90 }
91 if (!lua_checkstack (L, stack_slots)) {
92 wp_critical ("_wplua_pcall: cannot grow Lua stack");
93 return LUA_ERRMEM;
94 }
95
96 hpos = slots - nargs;
97 lua_pushcfunction (L, _wplua_errhandler);
98 lua_insert (L, hpos);
99
100 ret = lua_pcall (L, nargs, nret, hpos);
101 switch (ret) {
102 case LUA_ERRMEM:
103 wp_critical ("not enough memory");
104 break;
105 case LUA_ERRERR:
106 wp_critical ("error running the message handler");
107 break;
108 default:
109 break;
110 }
111
112 lua_remove (L, hpos);
113 return ret;
114 }
115
116 lua_State *
117 wplua_new (void)
118 {
119 static gboolean resource_registered = FALSE;
120 lua_State *L = luaL_newstate ();
121
122 if (L == NULL)
123 g_error ("cannot create Lua state");
124 wp_debug ("initializing lua_State %p", L);
125 WpLuaExtraData *extradata = g_malloc(sizeof(*extradata));
126 extradata->refcount = 1;
127 memcpy (lua_getextraspace (L), &extradata, sizeof(extradata));
128
129 if (!resource_registered) {
130 _wplua_register_resource ();
131 resource_registered = TRUE;
132 }
133
134 _wplua_openlibs (L);
135 _wplua_init_gboxed (L);
136 _wplua_init_gobject (L);
137 _wplua_init_closure (L);
138
139 {
140 GHashTable *t = g_hash_table_new (g_direct_hash, g_direct_equal);
141 lua_pushliteral (L, "wplua_vtables");
142 wplua_pushboxed (L, G_TYPE_HASH_TABLE, t);
143 lua_settable (L, LUA_REGISTRYINDEX);
144 }
145
146 return L;
147 }
148
149 lua_State *
150 wplua_ref (lua_State *L)
151 {
152 WpLuaExtraData *data = wplua_getextradata(L);
153
154 if (data->refcount < 1 || data->refcount == UINT64_MAX)
155 g_error ("bad refcount");
156 else {
157 data->refcount++;
158 return L;
159 }
160 }
161
162 void
163 wplua_unref (lua_State * L)
164 {
165 WpLuaExtraData *data = wplua_getextradata(L);
166
167 if (data->refcount < 1)
168 g_error ("bad refcount");
169 else if (data->refcount > 1)
170 data->refcount--;
171 else {
172 wp_debug ("closing lua_State %p", L);
173 g_free (data);
174 lua_close (L);
175 }
176 }
177
178 void
179 wplua_enable_sandbox (lua_State * L, WpLuaSandboxFlags flags)
180 {
181 g_autoptr (GError) error = NULL;
182 wp_debug ("enabling Lua sandbox");
183
184 if (!wplua_load_uri (L, URI_SANDBOX, &error)) {
185 wp_critical ("Failed to load sandbox: %s", error->message);
186 return;
187 }
188
189 lua_newtable (L);
190 lua_pushliteral (L, "isolate_env");
191 lua_pushboolean (L, (flags & WP_LUA_SANDBOX_ISOLATE_ENV));
192 lua_settable (L, -3);
193
194 if (!wplua_pcall (L, 1, 0, &error)) {
195 wp_critical ("Failed to load sandbox: %s", error->message);
196 }
197 }
198
199 int
200 wplua_push_sandbox (lua_State * L)
201 {
202 return (lua_getglobal (L, "sandbox") == LUA_TFUNCTION) ? 1 : 0;
203 }
204
205 void
206 wplua_register_type_methods (lua_State * L, GType type,
207 lua_CFunction constructor, const luaL_Reg * methods)
208 {
209 g_return_if_fail (L != NULL);
210 g_return_if_fail (G_TYPE_FUNDAMENTAL (type) == G_TYPE_OBJECT ||
211 G_TYPE_FUNDAMENTAL (type) == G_TYPE_BOXED ||
212 G_TYPE_FUNDAMENTAL (type) == G_TYPE_INTERFACE);
213
214 /* register methods */
215 if (methods) {
216 GHashTable *vtables;
217
218 lua_pushliteral (L, "wplua_vtables");
219 lua_gettable (L, LUA_REGISTRYINDEX);
220 vtables = wplua_toboxed (L, -1);
221 lua_pop (L, 1);
222
223 wp_debug ("Registering methods for '%s'", g_type_name (type));
224
225 if (G_UNLIKELY (g_hash_table_contains (vtables, GUINT_TO_POINTER (type)))) {
226 wp_critical ("type '%s' was already registered", g_type_name (type));
227 return;
228 }
229
230 g_hash_table_insert (vtables, GUINT_TO_POINTER (type), (gpointer) methods);
231 }
232
233 /* register constructor */
234 if (constructor) {
235 luaL_Buffer b;
236
237 wp_debug ("Registering class for '%s'", g_type_name (type));
238
239 luaL_buffinit (L, &b);
240 luaL_addstring (&b, g_type_name (type));
241 luaL_addstring (&b, "_new");
242 luaL_pushresult (&b);
243 lua_pushcfunction (L, constructor);
244 lua_setglobal (L, lua_tostring (L, -2));
245 lua_pop (L, 1);
246 }
247 }
248
249 static gboolean
250 _wplua_load_buffer (lua_State * L, const gchar *buf, gsize size,
251 const gchar * name, GError **error)
252 {
253 int ret;
254
255 /* skip shebang, if present */
256 if (g_str_has_prefix (buf, "#!/")) {
257 const char *tmp = strchr (buf, '\n');
258 size -= (tmp - buf);
259 buf = tmp;
260 }
261
262 ret = luaL_loadbuffer (L, buf, size, name);
263 if (ret != LUA_OK) {
264 g_set_error (error, WP_DOMAIN_LUA, WP_LUA_ERROR_COMPILATION,
265 "Failed to compile: %s", lua_tostring (L, -1));
266 lua_pop (L, 1);
267 return FALSE;
268 }
269 return TRUE;
270 }
271
272 gboolean
273 wplua_load_buffer (lua_State * L, const gchar *buf, gsize size, GError **error)
274 {
275 g_return_val_if_fail (L != NULL, FALSE);
276 g_return_val_if_fail (buf != NULL, FALSE);
277 g_return_val_if_fail (size != 0, FALSE);
278
279 g_autofree gchar *name =
280 g_strdup_printf ("buffer@%p;size=%" G_GSIZE_FORMAT, buf, size);
281 return _wplua_load_buffer (L, buf, size, name, error);
282 }
283
284 gboolean
285 wplua_load_uri (lua_State * L, const gchar *uri, GError **error)
286 {
287 g_autoptr (GFile) file = NULL;
288 g_autoptr (GBytes) bytes = NULL;
289 g_autoptr (GError) err = NULL;
290 g_autofree gchar *name = NULL;
291 gconstpointer data;
292 gsize size;
293
294 g_return_val_if_fail (L != NULL, FALSE);
295 g_return_val_if_fail (uri != NULL, FALSE);
296
297 file = g_file_new_for_uri (uri);
298 if (!(bytes = g_file_load_bytes (file, NULL, NULL, &err))) {
299 g_propagate_prefixed_error (error, err, "Failed to load '%s':", uri);
300 err = NULL;
301 return FALSE;
302 }
303
304 name = g_path_get_basename (uri);
305 data = g_bytes_get_data (bytes, &size);
306 return _wplua_load_buffer (L, data, size, name, error);
307 }
308
309 gboolean
310 wplua_load_path (lua_State * L, const gchar *path, GError **error)
311 {
312 g_autofree gchar *abs_path = NULL;
313 g_autofree gchar *uri = NULL;
314
315 g_return_val_if_fail (L != NULL, FALSE);
316 g_return_val_if_fail (path != NULL, FALSE);
317
318 if (!g_path_is_absolute (path)) {
319 g_autofree gchar *cwd = g_get_current_dir ();
320 abs_path = g_build_filename (cwd, path, NULL);
321 }
322
323 if (!(uri = g_filename_to_uri (abs_path ? abs_path : path, NULL, error)))
324 return FALSE;
325
326 return wplua_load_uri (L, uri, error);
327 }
328
329 gboolean
330 wplua_pcall (lua_State * L, int nargs, int nres, GError **error)
331 {
332 int ret = _wplua_pcall (L, nargs, nres);
333 if (ret != LUA_OK) {
334 g_set_error (error, WP_DOMAIN_LUA, WP_LUA_ERROR_RUNTIME,
335 "Lua runtime error");
336 return FALSE;
337 }
338 return TRUE;
339 }