Fix a tiny memory-leak when calling vfork
[ardour.git] / libs / ardour / luascripting.cc
1 /*
2  * Copyright (C) 2016 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  */
19 #include <cstring>
20 #include <glibmm.h>
21
22 #include "pbd/error.h"
23 #include "pbd/file_utils.h"
24 #include "pbd/compose.h"
25
26 #include "ardour/directory_names.h"
27 #include "ardour/filesystem_paths.h"
28 #include "ardour/luascripting.h"
29 #include "ardour/lua_script_params.h"
30 #include "ardour/search_paths.h"
31
32 #include "lua/luastate.h"
33 #include "LuaBridge/LuaBridge.h"
34
35 #include "pbd/i18n.h"
36 #include "sha1.c"
37
38 using namespace ARDOUR;
39 using namespace PBD;
40 using namespace std;
41
42 LuaScripting* LuaScripting::_instance = 0;
43
44 LuaScripting&
45 LuaScripting::instance ()
46 {
47         if (!_instance) {
48                 _instance = new LuaScripting;
49         }
50         return *_instance;
51 }
52
53 LuaScripting::LuaScripting ()
54         : _sl_dsp (0)
55         , _sl_session (0)
56         , _sl_hook (0)
57         , _sl_action (0)
58         , _sl_snippet (0)
59         , _sl_setup (0)
60         , _sl_tracks (0)
61 {
62         ;
63 }
64
65 LuaScripting::~LuaScripting ()
66 {
67         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
68                 // don't bother, just exit quickly.
69                 delete _sl_dsp;
70                 delete _sl_session;
71                 delete _sl_hook;
72                 delete _sl_action;
73                 delete _sl_snippet;
74                 delete _sl_setup;
75                 delete _sl_tracks;
76         }
77 }
78
79
80 void
81 LuaScripting::refresh (bool run_scan)
82 {
83         Glib::Threads::Mutex::Lock lm (_lock);
84
85         delete _sl_dsp;
86         delete _sl_session;
87         delete _sl_hook;
88         delete _sl_action;
89         delete _sl_snippet;
90         delete _sl_setup;
91         delete _sl_tracks;
92
93         _sl_dsp = 0;
94         _sl_session = 0;
95         _sl_hook = 0;
96         _sl_action = 0;
97         _sl_snippet = 0;
98         _sl_setup = 0;
99         _sl_tracks = 0;
100
101         if (run_scan) {
102                 lm.release ();
103                 scan ();
104         }
105 }
106
107 struct ScriptSorter {
108         bool operator () (LuaScriptInfoPtr a, LuaScriptInfoPtr b) {
109                 return a->name < b->name;
110         }
111 };
112
113 LuaScriptInfoPtr
114 LuaScripting::script_info (const std::string &script) {
115         return scan_script ("", script);
116 }
117
118 void
119 LuaScripting::scan ()
120 {
121         Glib::Threads::Mutex::Lock lm (_lock);
122
123 #define CLEAR_OR_NEW(LIST) \
124         if (LIST) { LIST->clear (); } else { LIST = new LuaScriptList (); }
125
126         CLEAR_OR_NEW (_sl_dsp)
127         CLEAR_OR_NEW (_sl_session)
128         CLEAR_OR_NEW (_sl_hook)
129         CLEAR_OR_NEW (_sl_action)
130         CLEAR_OR_NEW (_sl_snippet)
131         CLEAR_OR_NEW (_sl_setup)
132         CLEAR_OR_NEW (_sl_tracks)
133
134 #undef CLEAR_OR_NEW
135
136         vector<string> luascripts;
137         find_files_matching_pattern (luascripts, lua_search_path (), "*.lua");
138
139         for (vector<string>::iterator i = luascripts.begin(); i != luascripts.end (); ++i) {
140                 LuaScriptInfoPtr lsi = scan_script (*i);
141                 if (!lsi) {
142                         PBD::info << string_compose (_("Script '%1' has no valid descriptor."), *i) << endmsg;
143                         continue;
144                 }
145                 switch (lsi->type) {
146                         case LuaScriptInfo::DSP:
147                                 _sl_dsp->push_back(lsi);
148                                 break;
149                         case LuaScriptInfo::Session:
150                                 _sl_session->push_back(lsi);
151                                 break;
152                         case LuaScriptInfo::EditorHook:
153                                 _sl_hook->push_back(lsi);
154                                 break;
155                         case LuaScriptInfo::EditorAction:
156                                 _sl_action->push_back(lsi);
157                                 break;
158                         case LuaScriptInfo::Snippet:
159                                 _sl_snippet->push_back(lsi);
160                                 break;
161                         case LuaScriptInfo::SessionInit:
162                                 _sl_setup->push_back(lsi);
163                                 break;
164                         default:
165                                 break;
166                 }
167         }
168
169         std::sort (_sl_dsp->begin(), _sl_dsp->end(), ScriptSorter());
170         std::sort (_sl_session->begin(), _sl_session->end(), ScriptSorter());
171         std::sort (_sl_hook->begin(), _sl_hook->end(), ScriptSorter());
172         std::sort (_sl_action->begin(), _sl_action->end(), ScriptSorter());
173         std::sort (_sl_snippet->begin(), _sl_snippet->end(), ScriptSorter());
174         std::sort (_sl_setup->begin(), _sl_setup->end(), ScriptSorter());
175         std::sort (_sl_tracks->begin(), _sl_tracks->end(), ScriptSorter());
176
177         scripts_changed (); /* EMIT SIGNAL */
178 }
179
180 void
181 LuaScripting::lua_print (std::string s) {
182         PBD::info << "Lua: " << s << "\n";
183 }
184
185 LuaScriptInfoPtr
186 LuaScripting::scan_script (const std::string &fn, const std::string &sc)
187 {
188         LuaState lua;
189         if (!(fn.empty() ^ sc.empty())){
190                 // give either file OR script
191                 assert (0);
192                 return LuaScriptInfoPtr();
193         }
194
195         lua_State* L = lua.getState();
196         lua.Print.connect (&LuaScripting::lua_print);
197         lua.sandbox (true);
198
199         lua.do_command (
200                         "ardourluainfo = {}"
201                         "function ardour (entry)"
202                         "  ardourluainfo['type'] = assert(entry['type'])"
203                         "  ardourluainfo['name'] = assert(entry['name'])"
204                         "  ardourluainfo['category'] = entry['category'] or 'Unknown'"
205                         "  ardourluainfo['author'] = entry['author'] or 'Unknown'"
206                         "  ardourluainfo['license'] = entry['license'] or ''"
207                         "  ardourluainfo['description'] = entry['description'] or ''"
208                         " end"
209                         );
210
211         try {
212                 int err;
213                 if (fn.empty()) {
214                         err = lua.do_command (sc);
215                 } else {
216                         err = lua.do_file (fn);
217                 }
218                 if (err) {
219 #ifndef NDEBUG
220                 cerr << "failed to load lua script\n";
221 #endif
222                         return LuaScriptInfoPtr();
223                 }
224         } catch (...) { // luabridge::LuaException
225 #ifndef NDEBUG
226                 cerr << "failed to parse lua script\n";
227 #endif
228                 return LuaScriptInfoPtr();
229         }
230         luabridge::LuaRef nfo = luabridge::getGlobal (L, "ardourluainfo");
231         if (nfo.type() != LUA_TTABLE) {
232 #ifndef NDEBUG
233                 cerr << "failed to get ardour{} table from script\n";
234 #endif
235                 return LuaScriptInfoPtr();
236         }
237
238         if (nfo["name"].type() != LUA_TSTRING || nfo["type"].type() != LUA_TSTRING) {
239 #ifndef NDEBUG
240                 cerr << "script-type or script-name is not a string\n";
241 #endif
242                 return LuaScriptInfoPtr();
243         }
244
245         std::string name = nfo["name"].cast<std::string>();
246         LuaScriptInfo::ScriptType type = LuaScriptInfo::str2type (nfo["type"].cast<std::string>());
247
248         if (name.empty() || type == LuaScriptInfo::Invalid) {
249 #ifndef NDEBUG
250                 cerr << "invalid script-type or missing script name\n";
251 #endif
252                 return LuaScriptInfoPtr();
253         }
254
255         char hash[41];
256         Sha1Digest s;
257         sha1_init (&s);
258
259         if (fn.empty()) {
260                 sha1_write (&s, (const uint8_t *) sc.c_str(), sc.size ());
261         } else {
262                 try {
263                         std::string script = Glib::file_get_contents (fn);
264                         sha1_write (&s, (const uint8_t *) script.c_str(), script.size ());
265                 } catch (Glib::FileError const& err) {
266                         return LuaScriptInfoPtr();
267                 }
268         }
269         sha1_result_hash (&s, hash);
270
271
272         LuaScriptInfoPtr lsi (new LuaScriptInfo (type, name, fn, hash));
273
274         for (luabridge::Iterator i(nfo); !i.isNil (); ++i) {
275                 if (!i.key().isString() || !i.value().isString()) {
276                         return LuaScriptInfoPtr();
277                 }
278                 std::string key = i.key().tostring();
279                 std::string val = i.value().tostring();
280
281                 if (key == "author") { lsi->author = val; }
282                 if (key == "license") { lsi->license = val; }
283                 if (key == "description") { lsi->description = val; }
284                 if (key == "category") { lsi->category = val; }
285         }
286
287
288         if (type == LuaScriptInfo::EditorAction) {
289
290                 luabridge::LuaRef lua_rs = luabridge::getGlobal (L, "route_setup");
291                 if (lua_rs.isFunction ()) {
292                         lsi->subtype |= LuaScriptInfo::RouteSetup;
293                 }
294
295                 luabridge::LuaRef lua_ss = luabridge::getGlobal (L, "session_setup");
296                 if (lua_ss.isFunction ()) {
297                         try {
298                                 if (lua_ss () == true) {
299                                         lsi->subtype |= LuaScriptInfo::SessionSetup;
300                                 }
301                         } catch (...) { }
302                 }
303
304         }
305
306         return lsi;
307 }
308
309 LuaScriptList &
310 LuaScripting::scripts (LuaScriptInfo::ScriptType type) {
311
312         if (!_sl_dsp || !_sl_session || !_sl_hook || !_sl_action || !_sl_snippet || ! _sl_setup || ! _sl_tracks) {
313                 scan ();
314         }
315
316         switch (type) {
317                 case LuaScriptInfo::DSP:
318                         return *_sl_dsp;
319                         break;
320                 case LuaScriptInfo::Session:
321                         return *_sl_session;
322                         break;
323                 case LuaScriptInfo::EditorHook:
324                         return *_sl_hook;
325                         break;
326                 case LuaScriptInfo::EditorAction:
327                         return *_sl_action;
328                         break;
329                 case LuaScriptInfo::Snippet:
330                         return *_sl_snippet;
331                         break;
332                 case LuaScriptInfo::SessionInit:
333                         return *_sl_setup;
334                         break;
335                 default:
336                         break;
337         }
338         return _empty_script_info; // make some compilers happy
339 }
340
341
342 std::string
343 LuaScriptInfo::type2str (const ScriptType t) {
344         switch (t) {
345                 case LuaScriptInfo::DSP: return "DSP";
346                 case LuaScriptInfo::Session: return "Session";
347                 case LuaScriptInfo::EditorHook: return "EditorHook";
348                 case LuaScriptInfo::EditorAction: return "EditorAction";
349                 case LuaScriptInfo::Snippet: return "Snippet";
350                 case LuaScriptInfo::SessionInit: return "SessionInit";
351                 default: return "Invalid";
352         }
353 }
354
355 LuaScriptInfo::ScriptType
356 LuaScriptInfo::str2type (const std::string& str) {
357         const char* type = str.c_str();
358         if (!strcasecmp (type, "DSP")) {return LuaScriptInfo::DSP;}
359         if (!strcasecmp (type, "Session")) {return LuaScriptInfo::Session;}
360         if (!strcasecmp (type, "EditorHook")) {return LuaScriptInfo::EditorHook;}
361         if (!strcasecmp (type, "EditorAction")) {return LuaScriptInfo::EditorAction;}
362         if (!strcasecmp (type, "Snippet")) {return LuaScriptInfo::Snippet;}
363         if (!strcasecmp (type, "SessionInit")) {return LuaScriptInfo::SessionInit;}
364         return LuaScriptInfo::Invalid;
365 }
366
367 LuaScriptParamList
368 LuaScriptParams::script_params (const LuaScriptInfoPtr& lsi, const std::string &pname)
369 {
370         assert (lsi);
371         return LuaScriptParams::script_params (lsi->path, pname);
372 }
373
374 LuaScriptParamList
375 LuaScriptParams::script_params (const std::string& s, const std::string &pname, bool file)
376 {
377         LuaState lua;
378         return LuaScriptParams::script_params (lua, s, pname, file);
379 }
380
381 LuaScriptParamList
382 LuaScriptParams::script_params (LuaState& lua, const std::string& s, const std::string &pname, bool file)
383 {
384         LuaScriptParamList rv;
385
386         lua_State* L = lua.getState();
387         lua.sandbox (true);
388         lua.do_command ("function ardour () end");
389
390         try {
391                 if (file) {
392                         lua.do_file (s);
393                 } else {
394                         lua.do_command (s);
395                 }
396         } catch (...) {
397                 return rv;
398         }
399
400         luabridge::LuaRef lua_params = luabridge::getGlobal (L, pname.c_str());
401         if (lua_params.isFunction ()) {
402                 luabridge::LuaRef params = lua_params ();
403                 if (params.isTable ()) {
404                         for (luabridge::Iterator i (params); !i.isNil (); ++i) {
405                                 if (!i.key ().isString ())            { continue; }
406                                 if (!i.value ().isTable ())           { continue; }
407                                 if (!i.value ()["title"].isString ()) { continue; }
408
409                                 std::string name = i.key ().cast<std::string> ();
410                                 std::string title = i.value ()["title"].cast<std::string> ();
411                                 std::string dflt;
412                                 bool optional = false;
413                                 bool preseeded = false;
414
415                                 if (i.value ()["default"].isString ()) {
416                                         dflt = i.value ()["default"].cast<std::string> ();
417                                 }
418                                 if (i.value ()["optional"].isBoolean ()) {
419                                         optional = i.value ()["optional"].cast<bool> ();
420                                 }
421                                 if (i.value ()["preseeded"].isBoolean ()) {
422                                         preseeded = i.value ()["preseeded"].cast<bool> ();
423                                 }
424                                 LuaScriptParamPtr lsspp (new LuaScriptParam(name, title, dflt, optional, preseeded));
425                                 rv.push_back (lsspp);
426                         }
427                 }
428         }
429         return rv;
430 }
431
432 void
433 LuaScriptParams::params_to_ref (luabridge::LuaRef *tbl_args, const LuaScriptParamList& args)
434 {
435         assert (tbl_args &&  (*tbl_args).isTable ());
436         for (LuaScriptParamList::const_iterator i = args.begin(); i != args.end(); ++i) {
437                 if ((*i)->optional && !(*i)->is_set) { continue; }
438                 (*tbl_args)[(*i)->name] = (*i)->value;
439         }
440 }
441
442 void
443 LuaScriptParams::ref_to_params (LuaScriptParamList& args, luabridge::LuaRef *tbl_ref)
444 {
445         assert (tbl_ref &&  (*tbl_ref).isTable ());
446         for (luabridge::Iterator i (*tbl_ref); !i.isNil (); ++i) {
447                 if (!i.key ().isString ()) { assert(0); continue; }
448                 std::string name = i.key ().cast<std::string> ();
449                 std::string value = i.value ().cast<std::string> ();
450                 for (LuaScriptParamList::const_iterator ii = args.begin(); ii != args.end(); ++ii) {
451                         if ((*ii)->name == name) {
452                                 (*ii)->value = value;
453                                 break;
454                         }
455                 }
456         }
457 }
458
459 bool
460 LuaScripting::try_compile (const std::string& script, const LuaScriptParamList& args)
461 {
462         const std::string& bytecode = get_factory_bytecode (script);
463         if (bytecode.empty()) {
464                 return false;
465         }
466         LuaState l;
467         l.Print.connect (&LuaScripting::lua_print);
468         l.sandbox (true);
469         lua_State* L = l.getState();
470
471         l.do_command (""
472                         " function checkfactory (b, a)"
473                         "  assert(type(b) == 'string', 'ByteCode must be string')"
474                         "  load(b)()" // assigns f
475                         "  assert(type(f) == 'string', 'Assigned ByteCode must be string')"
476                         "  local factory = load(f)"
477                         "  assert(type(factory) == 'function', 'Factory is a not a function')"
478                         "  local env = _ENV; env.f = nil env.os = nil env.io = nil"
479                         "  load (string.dump(factory, true), nil, nil, env)(a)"
480                         " end"
481                         );
482
483         try {
484                 luabridge::LuaRef lua_test = luabridge::getGlobal (L, "checkfactory");
485                 l.do_command ("checkfactory = nil"); // hide it.
486                 l.do_command ("collectgarbage()");
487
488                 luabridge::LuaRef tbl_arg (luabridge::newTable(L));
489                 LuaScriptParams::params_to_ref (&tbl_arg, args);
490                 lua_test (bytecode, tbl_arg);
491                 return true; // OK
492         } catch (luabridge::LuaException const& e) {
493 #ifndef NDEBUG
494                 cerr << e.what() << "\n";
495 #endif
496                 lua_print (e.what());
497         } catch (...) { }
498
499         return false;
500 }
501
502 std::string
503 LuaScripting::get_factory_bytecode (const std::string& script, const std::string& ffn, const std::string& fp)
504 {
505         LuaState l;
506         l.Print.connect (&LuaScripting::lua_print);
507         l.sandbox (true);
508         lua_State* L = l.getState();
509
510         l.do_command (
511                         " function ardour () end"
512                         ""
513                         " function dump_function (f)"
514                         "  assert(type(f) == 'function', 'Factory is a not a function')"
515                         "  return string.format(\"" + fp + " = %q\", string.dump(f, true))"
516                         " end"
517                         );
518
519         try {
520                 luabridge::LuaRef lua_dump = luabridge::getGlobal (L, "dump_function");
521                 l.do_command ("dump_function = nil"); // hide it
522                 l.do_command (script); // register "factory"
523                 luabridge::LuaRef lua_factory = luabridge::getGlobal (L, ffn.c_str());
524
525                 if (lua_factory.isFunction()) {
526                         return (lua_dump(lua_factory)).cast<std::string> ();
527                 }
528         } catch (...) { }
529         return "";
530 }
531
532 std::string
533 LuaScripting::user_script_dir ()
534 {
535         std::string dir = Glib::build_filename (user_config_directory(), lua_dir_name);
536         g_mkdir_with_parents (dir.c_str(), 0744);
537         return dir;
538 }