You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

485 lines
12KB

  1. #include <thread>
  2. #include <map>
  3. #include <stdexcept>
  4. #include <tuple>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8. #include <sys/param.h> // for MAXPATHLEN
  9. #include <fcntl.h>
  10. #if defined ARCH_WIN
  11. #include <windows.h>
  12. #include <direct.h>
  13. #else
  14. #include <dlfcn.h> // for dlopen
  15. #endif
  16. #include <dirent.h>
  17. #include <osdialog.h>
  18. #include <jansson.h>
  19. #include <plugin.hpp>
  20. #include <system.hpp>
  21. #include <asset.hpp>
  22. #include <string.hpp>
  23. #include <context.hpp>
  24. #include <plugin/callbacks.hpp>
  25. #include <settings.hpp>
  26. namespace rack {
  27. namespace core {
  28. void init(rack::plugin::Plugin* plugin);
  29. } // namespace core
  30. namespace plugin {
  31. ////////////////////
  32. // private API
  33. ////////////////////
  34. static void* getSymbol(void* handle, const char* name) {
  35. if (!handle)
  36. return NULL;
  37. #if defined ARCH_WIN
  38. return (void*) GetProcAddress((HMODULE) handle, name);
  39. #else
  40. return dlsym(handle, name);
  41. #endif
  42. }
  43. /** Returns library handle */
  44. static void* loadLibrary(std::string libraryPath) {
  45. #if defined ARCH_WIN
  46. SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  47. std::wstring libraryFilenameW = string::UTF8toUTF16(libraryPath);
  48. HINSTANCE handle = LoadLibraryW(libraryFilenameW.c_str());
  49. SetErrorMode(0);
  50. if (!handle) {
  51. int error = GetLastError();
  52. throw Exception("Failed to load library %s: code %d", libraryPath.c_str(), error);
  53. }
  54. #else
  55. // Since Rack 2, plugins on Linux/Mac link to the absolute path /tmp/Rack2/libRack.<ext>
  56. // Create a symlink at /tmp/Rack2 to the system dir containting libRack.
  57. std::string systemDir = system::getAbsolute(asset::systemDir);
  58. std::string linkPath = "/tmp/Rack2";
  59. if (!settings::devMode) {
  60. // Clean up old symbolic link in case a different edition was run earlier
  61. system::remove(linkPath);
  62. system::createSymbolicLink(systemDir, linkPath);
  63. }
  64. // Load library with dlopen
  65. void* handle = NULL;
  66. #if defined ARCH_LIN
  67. handle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_LOCAL);
  68. #elif defined ARCH_MAC
  69. handle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_LOCAL);
  70. #endif
  71. if (!settings::devMode) {
  72. system::remove(linkPath);
  73. }
  74. if (!handle)
  75. throw Exception("Failed to load library %s: %s", libraryPath.c_str(), dlerror());
  76. #endif
  77. return handle;
  78. }
  79. typedef void (*InitCallback)(Plugin*);
  80. static InitCallback loadPluginCallback(Plugin* plugin) {
  81. // Load plugin library
  82. std::string libraryExt;
  83. #if defined ARCH_LIN
  84. libraryExt = "so";
  85. #elif defined ARCH_WIN
  86. libraryExt = "dll";
  87. #elif ARCH_MAC
  88. libraryExt = "dylib";
  89. #endif
  90. std::string libraryPath = system::join(plugin->path, "plugin." + libraryExt);
  91. // Check file existence
  92. if (!system::isFile(libraryPath))
  93. throw Exception("Plugin binary not found at %s", libraryPath.c_str());
  94. // Load dynamic/shared library
  95. plugin->handle = loadLibrary(libraryPath);
  96. // Get plugin's init() function
  97. InitCallback initCallback = (InitCallback) getSymbol(plugin->handle, "init");
  98. if (!initCallback)
  99. throw Exception("Failed to read init() symbol in %s", libraryPath.c_str());
  100. return initCallback;
  101. }
  102. /** If path is blank, loads Core */
  103. static Plugin* loadPlugin(std::string path) {
  104. if (path == "")
  105. INFO("Loading Core plugin");
  106. else
  107. INFO("Loading plugin from %s", path.c_str());
  108. Plugin* plugin = new Plugin;
  109. try {
  110. // Set plugin path
  111. plugin->path = (path == "") ? asset::systemDir : path;
  112. // Get modified timestamp
  113. if (path != "") {
  114. struct stat statbuf;
  115. if (!stat(path.c_str(), &statbuf)) {
  116. #if defined ARCH_MAC
  117. plugin->modifiedTimestamp = (double) statbuf.st_mtimespec.tv_sec + statbuf.st_mtimespec.tv_nsec * 1e-9;
  118. #elif defined ARCH_WIN
  119. plugin->modifiedTimestamp = (double) statbuf.st_mtime;
  120. #elif defined ARCH_LIN
  121. plugin->modifiedTimestamp = (double) statbuf.st_mtim.tv_sec + statbuf.st_mtim.tv_nsec * 1e-9;
  122. #endif
  123. }
  124. }
  125. // Load plugin.json
  126. std::string manifestFilename = (path == "") ? asset::system("Core.json") : system::join(path, "plugin.json");
  127. FILE* file = std::fopen(manifestFilename.c_str(), "r");
  128. if (!file)
  129. throw Exception("Manifest file %s does not exist", manifestFilename.c_str());
  130. DEFER({std::fclose(file);});
  131. json_error_t error;
  132. json_t* rootJ = json_loadf(file, 0, &error);
  133. if (!rootJ)
  134. throw Exception("JSON parsing error at %s %d:%d %s", manifestFilename.c_str(), error.line, error.column, error.text);
  135. DEFER({json_decref(rootJ);});
  136. // Load manifest
  137. plugin->fromJson(rootJ);
  138. // Reject plugin if slug already exists
  139. Plugin* existingPlugin = getPlugin(plugin->slug);
  140. if (existingPlugin)
  141. throw Exception("Plugin %s is already loaded, not attempting to load it again", plugin->slug.c_str());
  142. // Call init callback
  143. InitCallback initCallback;
  144. if (path == "") {
  145. initCallback = core::init;
  146. }
  147. else {
  148. initCallback = loadPluginCallback(plugin);
  149. }
  150. initCallback(plugin);
  151. // Load modules manifest
  152. json_t* modulesJ = json_object_get(rootJ, "modules");
  153. plugin->modulesFromJson(modulesJ);
  154. // Call settingsFromJson() if exists
  155. // Returns NULL for Core.
  156. auto settingsFromJson = (decltype(&::settingsFromJson)) getSymbol(plugin->handle, "settingsFromJson");
  157. if (settingsFromJson) {
  158. json_t* settingsJ = json_object_get(settings::pluginSettingsJ, plugin->slug.c_str());
  159. if (settingsJ)
  160. settingsFromJson(settingsJ);
  161. }
  162. }
  163. catch (Exception& e) {
  164. WARN("Could not load plugin %s: %s", path.c_str(), e.what());
  165. delete plugin;
  166. return NULL;
  167. }
  168. INFO("Loaded %s v%s", plugin->slug.c_str(), plugin->version.c_str());
  169. plugins.push_back(plugin);
  170. return plugin;
  171. }
  172. static void loadPlugins(std::string path) {
  173. for (std::string pluginPath : system::getEntries(path)) {
  174. if (!system::isDirectory(pluginPath))
  175. continue;
  176. if (!loadPlugin(pluginPath)) {
  177. // Ignore bad plugins. They are reported in the log.
  178. }
  179. }
  180. }
  181. static void extractPackages(std::string path) {
  182. std::string message;
  183. for (std::string packagePath : system::getEntries(path)) {
  184. if (!system::isFile(packagePath))
  185. continue;
  186. if (system::getExtension(packagePath) != ".vcvplugin")
  187. continue;
  188. // Extract package
  189. INFO("Extracting package %s", packagePath.c_str());
  190. try {
  191. system::unarchiveToDirectory(packagePath, path);
  192. }
  193. catch (Exception& e) {
  194. WARN("Plugin package %s failed to extract: %s", packagePath.c_str(), e.what());
  195. message += string::f("Could not extract plugin package %s\n", packagePath.c_str());
  196. continue;
  197. }
  198. // Remove package
  199. system::remove(packagePath.c_str());
  200. }
  201. if (!message.empty()) {
  202. osdialog_message(OSDIALOG_WARNING, OSDIALOG_OK, message.c_str());
  203. }
  204. }
  205. ////////////////////
  206. // public API
  207. ////////////////////
  208. void init() {
  209. // Don't re-initialize
  210. assert(plugins.empty());
  211. // Load Core
  212. loadPlugin("");
  213. pluginsPath = asset::user("plugins");
  214. // Get user plugins directory
  215. system::createDirectory(pluginsPath);
  216. // Don't load plugins if safe mode is enabled
  217. if (settings::safeMode)
  218. return;
  219. // Extract packages and load plugins
  220. extractPackages(pluginsPath);
  221. loadPlugins(pluginsPath);
  222. // If Fundamental wasn't loaded, copy the bundled Fundamental package and load it
  223. if (!settings::devMode && !getPlugin("Fundamental")) {
  224. std::string fundamentalSrc = asset::system("Fundamental.vcvplugin");
  225. std::string fundamentalDir = system::join(pluginsPath, "Fundamental");
  226. if (system::isFile(fundamentalSrc)) {
  227. INFO("Extracting bundled Fundamental package");
  228. try {
  229. system::unarchiveToDirectory(fundamentalSrc.c_str(), pluginsPath.c_str());
  230. loadPlugin(fundamentalDir);
  231. }
  232. catch (Exception& e) {
  233. WARN("Could not extract Fundamental package: %s", e.what());
  234. }
  235. }
  236. }
  237. }
  238. static void destroyPlugin(Plugin* plugin) {
  239. void* handle = plugin->handle;
  240. // Call destroy() if defined in the plugin library
  241. typedef void (*DestroyCallback)();
  242. DestroyCallback destroyCallback = NULL;
  243. if (handle) {
  244. destroyCallback = (DestroyCallback) getSymbol(handle, "destroy");
  245. }
  246. if (destroyCallback) {
  247. try {
  248. destroyCallback();
  249. }
  250. catch (Exception& e) {
  251. WARN("Could not destroy plugin %s", plugin->slug.c_str());
  252. }
  253. }
  254. // We must delete the Plugin instance *before* freeing the library, because the vtables of Model subclasses are defined in the library, which are needed in the Plugin destructor.
  255. delete plugin;
  256. // Free library handle
  257. if (handle) {
  258. #if defined ARCH_WIN
  259. FreeLibrary((HINSTANCE) handle);
  260. #else
  261. dlclose(handle);
  262. #endif
  263. }
  264. }
  265. void destroy() {
  266. for (Plugin* plugin : plugins) {
  267. INFO("Destroying plugin %s", plugin->name.c_str());
  268. destroyPlugin(plugin);
  269. }
  270. plugins.clear();
  271. }
  272. void settingsMergeJson(json_t* rootJ) {
  273. for (Plugin* plugin : plugins) {
  274. auto settingsToJson = (decltype(&::settingsToJson)) getSymbol(plugin->handle, "settingsToJson");
  275. if (settingsToJson) {
  276. json_t* settingsJ = settingsToJson();
  277. json_object_set_new(rootJ, plugin->slug.c_str(), settingsJ);
  278. }
  279. else {
  280. json_object_del(rootJ, plugin->slug.c_str());
  281. }
  282. }
  283. }
  284. /** Given slug => fallback slug.
  285. Correctly handles bidirectional fallbacks.
  286. To request fallback slugs to be added to this list, open a GitHub issue.
  287. */
  288. static const std::map<std::string, std::string> pluginSlugFallbacks = {
  289. {"VultModulesFree", "VultModules"},
  290. {"VultModules", "VultModulesFree"},
  291. {"AudibleInstrumentsPreview", "AudibleInstruments"},
  292. {"SequelSequencers", "DanielDavies"},
  293. // {"", ""},
  294. };
  295. Plugin* getPlugin(const std::string& pluginSlug) {
  296. if (pluginSlug.empty())
  297. return NULL;
  298. auto it = std::find_if(plugins.begin(), plugins.end(), [=](Plugin* p) {
  299. return p->slug == pluginSlug;
  300. });
  301. if (it != plugins.end())
  302. return *it;
  303. return NULL;
  304. }
  305. Plugin* getPluginFallback(const std::string& pluginSlug) {
  306. if (pluginSlug.empty())
  307. return NULL;
  308. // Attempt example plugin
  309. Plugin* p = getPlugin(pluginSlug);
  310. if (p)
  311. return p;
  312. // Attempt fallback plugin slug
  313. auto it = pluginSlugFallbacks.find(pluginSlug);
  314. if (it != pluginSlugFallbacks.end())
  315. return getPlugin(it->second);
  316. return NULL;
  317. }
  318. /** Given slug => fallback slug.
  319. Correctly handles bidirectional fallbacks.
  320. To request fallback slugs to be added to this list, open a GitHub issue.
  321. */
  322. using PluginModuleSlug = std::tuple<std::string, std::string>;
  323. static const std::map<PluginModuleSlug, PluginModuleSlug> moduleSlugFallbacks = {
  324. {{"MindMeld-ShapeMasterPro", "ShapeMasterPro"}, {"MindMeldModular", "ShapeMaster"}},
  325. {{"MindMeldModular", "ShapeMaster"}, {"MindMeld-ShapeMasterPro", "ShapeMasterPro"}},
  326. // {{"", ""}, {"", ""}},
  327. };
  328. Model* getModel(const std::string& pluginSlug, const std::string& modelSlug) {
  329. if (pluginSlug.empty() || modelSlug.empty())
  330. return NULL;
  331. Plugin* p = getPlugin(pluginSlug);
  332. if (!p)
  333. return NULL;
  334. return p->getModel(modelSlug);
  335. }
  336. Model* getModelFallback(const std::string& pluginSlug, const std::string& modelSlug) {
  337. if (pluginSlug.empty() || modelSlug.empty())
  338. return NULL;
  339. // Attempt exact plugin and model
  340. Model* m = getModel(pluginSlug, modelSlug);
  341. if (m)
  342. return m;
  343. // Attempt fallback module
  344. auto it = moduleSlugFallbacks.find(std::make_tuple(pluginSlug, modelSlug));
  345. if (it != moduleSlugFallbacks.end()) {
  346. Model* m = getModel(std::get<0>(it->second), std::get<1>(it->second));
  347. if (m)
  348. return m;
  349. }
  350. // Attempt fallback plugin
  351. auto it2 = pluginSlugFallbacks.find(pluginSlug);
  352. if (it2 != pluginSlugFallbacks.end()) {
  353. Model* m = getModel(it2->second, modelSlug);
  354. if (m)
  355. return m;
  356. }
  357. return NULL;
  358. }
  359. Model* modelFromJson(json_t* moduleJ) {
  360. // Get slugs
  361. json_t* pluginSlugJ = json_object_get(moduleJ, "plugin");
  362. if (!pluginSlugJ)
  363. throw Exception("\"plugin\" property not found in module JSON");
  364. std::string pluginSlug = json_string_value(pluginSlugJ);
  365. pluginSlug = normalizeSlug(pluginSlug);
  366. json_t* modelSlugJ = json_object_get(moduleJ, "model");
  367. if (!modelSlugJ)
  368. throw Exception("\"model\" property not found in module JSON");
  369. std::string modelSlug = json_string_value(modelSlugJ);
  370. modelSlug = normalizeSlug(modelSlug);
  371. // Get Model
  372. Model* model = getModelFallback(pluginSlug, modelSlug);
  373. if (!model)
  374. throw Exception("Could not find module %s/%s", pluginSlug.c_str(), modelSlug.c_str());
  375. return model;
  376. }
  377. bool isSlugValid(const std::string& slug) {
  378. for (char c : slug) {
  379. if (!(std::isalnum(c) || c == '-' || c == '_'))
  380. return false;
  381. }
  382. return true;
  383. }
  384. std::string normalizeSlug(const std::string& slug) {
  385. std::string s;
  386. for (char c : slug) {
  387. if (!(std::isalnum(c) || c == '-' || c == '_'))
  388. continue;
  389. s += c;
  390. }
  391. return s;
  392. }
  393. std::string pluginsPath;
  394. std::vector<Plugin*> plugins;
  395. } // namespace plugin
  396. } // namespace rack