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.

365 lines
9.4KB

  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* loadLibrary(std::string libraryPath) {
  35. #if defined ARCH_WIN
  36. SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  37. std::wstring libraryFilenameW = string::UTF8toUTF16(libraryPath);
  38. HINSTANCE handle = LoadLibraryW(libraryFilenameW.c_str());
  39. SetErrorMode(0);
  40. if (!handle) {
  41. int error = GetLastError();
  42. throw Exception("Failed to load library %s: code %d", libraryPath.c_str(), error);
  43. }
  44. #else
  45. // As of Rack v2.0, plugins are linked with `-rpath=.` so change current directory so it can find libRack.
  46. std::string cwd = system::getWorkingDirectory();
  47. system::setWorkingDirectory(asset::systemDir);
  48. // Change it back when we're finished
  49. DEFER({system::setWorkingDirectory(cwd);});
  50. // Load library with dlopen
  51. void* handle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_LOCAL);
  52. if (!handle)
  53. throw Exception("Failed to load library %s: %s", libraryPath.c_str(), dlerror());
  54. #endif
  55. return handle;
  56. }
  57. typedef void (*InitCallback)(Plugin*);
  58. static InitCallback loadPluginCallback(Plugin* plugin) {
  59. // Load plugin library
  60. std::string libraryExt;
  61. #if defined ARCH_LIN
  62. libraryExt = "so";
  63. #elif defined ARCH_WIN
  64. libraryExt = "dll";
  65. #elif ARCH_MAC
  66. libraryExt = "dylib";
  67. #endif
  68. std::string libraryPath = system::join(plugin->path, "plugin." + libraryExt);
  69. // Check file existence
  70. if (!system::isFile(libraryPath))
  71. throw Exception("Plugin binary not found at %s", libraryPath.c_str());
  72. // Load dynamic/shared library
  73. plugin->handle = loadLibrary(libraryPath);
  74. // Get plugin's init() function
  75. InitCallback initCallback;
  76. #if defined ARCH_WIN
  77. initCallback = (InitCallback) GetProcAddress((HMODULE) plugin->handle, "init");
  78. #else
  79. initCallback = (InitCallback) dlsym(plugin->handle, "init");
  80. #endif
  81. if (!initCallback)
  82. throw Exception("Failed to read init() symbol in %s", libraryPath.c_str());
  83. return initCallback;
  84. }
  85. /** If path is blank, loads Core */
  86. static Plugin* loadPlugin(std::string path) {
  87. if (path == "")
  88. INFO("Loading Core plugin");
  89. else
  90. INFO("Loading plugin from %s", path.c_str());
  91. Plugin* plugin = new Plugin;
  92. try {
  93. // Set plugin path
  94. plugin->path = (path == "") ? asset::systemDir : path;
  95. // Get modified timestamp
  96. if (path != "") {
  97. struct stat statbuf;
  98. if (!stat(path.c_str(), &statbuf)) {
  99. #if defined ARCH_MAC
  100. plugin->modifiedTimestamp = (double) statbuf.st_mtimespec.tv_sec + statbuf.st_mtimespec.tv_nsec * 1e-9;
  101. #elif defined ARCH_WIN
  102. plugin->modifiedTimestamp = (double) statbuf.st_mtime;
  103. #elif defined ARCH_LIN
  104. plugin->modifiedTimestamp = (double) statbuf.st_mtim.tv_sec + statbuf.st_mtim.tv_nsec * 1e-9;
  105. #endif
  106. }
  107. }
  108. // Load plugin.json
  109. std::string manifestFilename = (path == "") ? asset::system("Core.json") : system::join(path, "plugin.json");
  110. FILE* file = std::fopen(manifestFilename.c_str(), "r");
  111. if (!file)
  112. throw Exception("Manifest file %s does not exist", manifestFilename.c_str());
  113. DEFER({std::fclose(file);});
  114. json_error_t error;
  115. json_t* rootJ = json_loadf(file, 0, &error);
  116. if (!rootJ)
  117. throw Exception("JSON parsing error at %s %d:%d %s", manifestFilename.c_str(), error.line, error.column, error.text);
  118. DEFER({json_decref(rootJ);});
  119. // Call init callback
  120. InitCallback initCallback;
  121. if (path == "") {
  122. initCallback = core::init;
  123. }
  124. else {
  125. initCallback = loadPluginCallback(plugin);
  126. }
  127. initCallback(plugin);
  128. // Load manifest
  129. plugin->fromJson(rootJ);
  130. // Reject plugin if slug already exists
  131. Plugin* existingPlugin = getPlugin(plugin->slug);
  132. if (existingPlugin)
  133. throw Exception("Plugin %s is already loaded, not attempting to load it again", plugin->slug.c_str());
  134. }
  135. catch (Exception& e) {
  136. WARN("Could not load plugin %s: %s", path.c_str(), e.what());
  137. delete plugin;
  138. return NULL;
  139. }
  140. INFO("Loaded %s v%s", plugin->slug.c_str(), plugin->version.c_str());
  141. plugins.push_back(plugin);
  142. return plugin;
  143. }
  144. static void loadPlugins(std::string path) {
  145. for (std::string pluginPath : system::getEntries(path)) {
  146. if (!system::isDirectory(pluginPath))
  147. continue;
  148. if (!loadPlugin(pluginPath)) {
  149. // Ignore bad plugins. They are reported in the log.
  150. }
  151. }
  152. }
  153. static void extractPackages(std::string path) {
  154. std::string message;
  155. for (std::string packagePath : system::getEntries(path)) {
  156. if (!system::isFile(packagePath))
  157. continue;
  158. if (system::getExtension(packagePath) != ".vcvplugin")
  159. continue;
  160. // Extract package
  161. INFO("Extracting package %s", packagePath.c_str());
  162. try {
  163. system::unarchiveToDirectory(packagePath, path);
  164. }
  165. catch (Exception& e) {
  166. WARN("Plugin package %s failed to extract: %s", packagePath.c_str(), e.what());
  167. message += string::f("Could not extract plugin package %s\n", packagePath.c_str());
  168. continue;
  169. }
  170. // Remove package
  171. system::remove(packagePath.c_str());
  172. }
  173. if (!message.empty()) {
  174. osdialog_message(OSDIALOG_WARNING, OSDIALOG_OK, message.c_str());
  175. }
  176. }
  177. ////////////////////
  178. // public API
  179. ////////////////////
  180. void init() {
  181. // Don't re-initialize
  182. assert(plugins.empty());
  183. // Load Core
  184. loadPlugin("");
  185. if (settings::devMode) {
  186. pluginsPath = asset::user("plugins");
  187. }
  188. else {
  189. pluginsPath = asset::user("plugins-v" + APP_VERSION_MAJOR);
  190. }
  191. // Get user plugins directory
  192. system::createDirectory(pluginsPath);
  193. // Extract packages and load plugins
  194. extractPackages(pluginsPath);
  195. loadPlugins(pluginsPath);
  196. // If Fundamental wasn't loaded, copy the bundled Fundamental package and load it
  197. if (!settings::devMode && !getPlugin("Fundamental")) {
  198. std::string fundamentalSrc = asset::system("Fundamental.vcvplugin");
  199. std::string fundamentalDir = system::join(pluginsPath, "Fundamental");
  200. if (system::isFile(fundamentalSrc)) {
  201. INFO("Extracting bundled Fundamental package");
  202. system::unarchiveToDirectory(fundamentalSrc.c_str(), pluginsPath.c_str());
  203. loadPlugin(fundamentalDir);
  204. }
  205. }
  206. }
  207. void destroy() {
  208. for (Plugin* plugin : plugins) {
  209. // We must delete the plugin *before* freeing the library, because the vtable of Model subclasses are static in the plugin, and we need it for the virtual destructor.
  210. void* handle = plugin->handle;
  211. delete plugin;
  212. // Free library handle
  213. if (handle) {
  214. #if defined ARCH_WIN
  215. FreeLibrary((HINSTANCE) handle);
  216. #else
  217. dlclose(handle);
  218. #endif
  219. }
  220. }
  221. plugins.clear();
  222. }
  223. // To request fallback slugs to be added to this list, open a GitHub issue.
  224. static const std::map<std::string, std::string> pluginSlugFallbacks = {
  225. // {"", ""},
  226. };
  227. Plugin* getPlugin(const std::string& pluginSlug) {
  228. if (pluginSlug.empty())
  229. return NULL;
  230. for (Plugin* plugin : plugins) {
  231. if (plugin->slug == pluginSlug) {
  232. return plugin;
  233. }
  234. }
  235. // Use fallback plugin slug
  236. auto it = pluginSlugFallbacks.find(pluginSlug);
  237. if (it != pluginSlugFallbacks.end()) {
  238. return getPlugin(it->second);
  239. }
  240. return NULL;
  241. }
  242. // To request fallback slugs to be added to this list, open a GitHub issue.
  243. using PluginModuleSlug = std::tuple<std::string, std::string>;
  244. static const std::map<PluginModuleSlug, PluginModuleSlug> moduleSlugFallbacks = {
  245. {{"AudibleInstrumentsPreview", "Plaits"}, {"AudibleInstruments", "Plaits"}},
  246. {{"AudibleInstrumentsPreview", "Marbles"}, {"AudibleInstruments", "Marbles"}},
  247. // {{"", ""}, {"", ""}},
  248. };
  249. Model* getModel(const std::string& pluginSlug, const std::string& modelSlug) {
  250. if (pluginSlug.empty() || modelSlug.empty())
  251. return NULL;
  252. Plugin* plugin = getPlugin(pluginSlug);
  253. if (plugin) {
  254. Model* model = plugin->getModel(modelSlug);
  255. if (model)
  256. return model;
  257. }
  258. // Use fallback (module slug, plugin slug)
  259. auto it = moduleSlugFallbacks.find(std::make_tuple(pluginSlug, modelSlug));
  260. if (it != moduleSlugFallbacks.end()) {
  261. return getModel(std::get<0>(it->second), std::get<1>(it->second));
  262. }
  263. return NULL;
  264. }
  265. Model* modelFromJson(json_t* moduleJ) {
  266. // Get slugs
  267. json_t* pluginSlugJ = json_object_get(moduleJ, "plugin");
  268. if (!pluginSlugJ)
  269. throw Exception("\"plugin\" property not found in module JSON");
  270. std::string pluginSlug = json_string_value(pluginSlugJ);
  271. pluginSlug = normalizeSlug(pluginSlug);
  272. json_t* modelSlugJ = json_object_get(moduleJ, "model");
  273. if (!modelSlugJ)
  274. throw Exception("\"model\" property not found in module JSON");
  275. std::string modelSlug = json_string_value(modelSlugJ);
  276. modelSlug = normalizeSlug(modelSlug);
  277. // Get Model
  278. Model* model = getModel(pluginSlug, modelSlug);
  279. if (!model)
  280. throw Exception("Could not find module \"%s\" \"%s\"", pluginSlug.c_str(), modelSlug.c_str());
  281. return model;
  282. }
  283. bool isSlugValid(const std::string& slug) {
  284. for (char c : slug) {
  285. if (!(std::isalnum(c) || c == '-' || c == '_'))
  286. return false;
  287. }
  288. return true;
  289. }
  290. std::string normalizeSlug(const std::string& slug) {
  291. std::string s;
  292. for (char c : slug) {
  293. if (!(std::isalnum(c) || c == '-' || c == '_'))
  294. continue;
  295. s += c;
  296. }
  297. return s;
  298. }
  299. std::string pluginsPath;
  300. std::vector<Plugin*> plugins;
  301. } // namespace plugin
  302. } // namespace rack