Audio plugin host https://kx.studio/carla
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.

381 lines
9.9KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2022 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #include "ChildProcess.h"
  21. #include "../files/File.h"
  22. #include "../misc/Time.h"
  23. #ifdef CARLA_OS_MAC
  24. # include <crt_externs.h>
  25. # include <spawn.h>
  26. #endif
  27. #ifndef CARLA_OS_WIN
  28. # include <signal.h>
  29. # include <sys/wait.h>
  30. #endif
  31. #include "CarlaProcessUtils.hpp"
  32. namespace water {
  33. #ifdef CARLA_OS_WIN
  34. //=====================================================================================================================
  35. class ChildProcess::ActiveProcess
  36. {
  37. public:
  38. ActiveProcess (const String& command)
  39. : ok (false)
  40. {
  41. STARTUPINFOA startupInfo;
  42. carla_zeroStruct(startupInfo);
  43. startupInfo.cb = sizeof (startupInfo);
  44. ok = CreateProcessA (nullptr, const_cast<LPSTR>(command.toRawUTF8()),
  45. nullptr, nullptr, TRUE, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
  46. nullptr, nullptr, &startupInfo, &processInfo) != FALSE;
  47. }
  48. ~ActiveProcess()
  49. {
  50. closeProcessInfo();
  51. }
  52. void closeProcessInfo() noexcept
  53. {
  54. if (ok)
  55. {
  56. ok = false;
  57. CloseHandle (processInfo.hThread);
  58. CloseHandle (processInfo.hProcess);
  59. }
  60. }
  61. bool isRunning() const noexcept
  62. {
  63. return WaitForSingleObject (processInfo.hProcess, 0) != WAIT_OBJECT_0;
  64. }
  65. bool checkRunningAndUnsetPID() noexcept
  66. {
  67. if (isRunning())
  68. return true;
  69. ok = false;
  70. CloseHandle (processInfo.hThread);
  71. CloseHandle (processInfo.hProcess);
  72. return false;
  73. }
  74. bool killProcess() const noexcept
  75. {
  76. return TerminateProcess (processInfo.hProcess, 0) != FALSE;
  77. }
  78. bool terminateProcess() const noexcept
  79. {
  80. return TerminateProcess (processInfo.hProcess, 0) != FALSE;
  81. }
  82. uint32 getExitCodeAndClearPID() noexcept
  83. {
  84. DWORD exitCode = 0;
  85. GetExitCodeProcess (processInfo.hProcess, &exitCode);
  86. closeProcessInfo();
  87. return (uint32) exitCode;
  88. }
  89. int getPID() const noexcept
  90. {
  91. return 0;
  92. }
  93. bool ok;
  94. private:
  95. PROCESS_INFORMATION processInfo;
  96. CARLA_DECLARE_NON_COPYABLE (ActiveProcess)
  97. };
  98. #else
  99. class ChildProcess::ActiveProcess
  100. {
  101. public:
  102. ActiveProcess (const StringArray& arguments, const Type type)
  103. : childPID (0)
  104. {
  105. String exe (arguments[0].unquoted());
  106. // Looks like you're trying to launch a non-existent exe or a folder (perhaps on OSX
  107. // you're trying to launch the .app folder rather than the actual binary inside it?)
  108. wassert (File::getCurrentWorkingDirectory().getChildFile (exe).existsAsFile()
  109. || ! exe.containsChar (File::separator));
  110. Array<char*> argv;
  111. for (int i = 0; i < arguments.size(); ++i)
  112. if (arguments[i].isNotEmpty())
  113. argv.add (const_cast<char*> (arguments[i].toRawUTF8()));
  114. argv.add (nullptr);
  115. #ifdef CARLA_OS_MAC
  116. cpu_type_t pref;
  117. pid_t result = -1;
  118. switch (type)
  119. {
  120. # ifdef __MAC_10_12
  121. case TypeARM:
  122. pref = CPU_TYPE_ARM64;
  123. break;
  124. # endif
  125. case TypeIntel:
  126. pref = CPU_TYPE_X86_64;
  127. break;
  128. default:
  129. pref = CPU_TYPE_ANY;
  130. break;
  131. }
  132. posix_spawnattr_t attr;
  133. posix_spawnattr_init(&attr);
  134. // posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
  135. CARLA_SAFE_ASSERT_RETURN(posix_spawnattr_setbinpref_np(&attr, 1, &pref, nullptr) == 0,);
  136. char*** const environptr = _NSGetEnviron();
  137. CARLA_SAFE_ASSERT_RETURN(posix_spawn(&result, exe.toRawUTF8(), nullptr, &attr,
  138. argv.getRawDataPointer(), environptr != nullptr ? *environptr : nullptr) == 0,);
  139. posix_spawnattr_destroy(&attr);
  140. #else
  141. const pid_t result = vfork();
  142. #endif
  143. if (result < 0)
  144. {
  145. // error
  146. }
  147. #ifndef CARLA_OS_MAC
  148. else if (result == 0)
  149. {
  150. // child process
  151. carla_terminateProcessOnParentExit(true);
  152. if (execvp (exe.toRawUTF8(), argv.getRawDataPointer()))
  153. _exit (-1);
  154. }
  155. #endif
  156. else
  157. {
  158. // we're the parent process..
  159. childPID = result;
  160. }
  161. #ifndef CARLA_OS_MAC
  162. // unused
  163. (void)type;
  164. #endif
  165. }
  166. ~ActiveProcess()
  167. {
  168. CARLA_SAFE_ASSERT_INT(childPID == 0, childPID);
  169. }
  170. bool isRunning() const noexcept
  171. {
  172. if (childPID != 0)
  173. {
  174. int childState = 0;
  175. const int pid = waitpid (childPID, &childState, WNOHANG|WUNTRACED);
  176. return pid == 0 || ! (WIFEXITED (childState) || WIFSIGNALED (childState) || WIFSTOPPED (childState));
  177. }
  178. return false;
  179. }
  180. bool checkRunningAndUnsetPID() noexcept
  181. {
  182. if (childPID != 0)
  183. {
  184. int childState = 0;
  185. const int pid = waitpid (childPID, &childState, WNOHANG|WUNTRACED);
  186. if (pid == 0)
  187. return true;
  188. if ( ! (WIFEXITED (childState) || WIFSIGNALED (childState) || WIFSTOPPED (childState)))
  189. return true;
  190. childPID = 0;
  191. return false;
  192. }
  193. return false;
  194. }
  195. bool killProcess() noexcept
  196. {
  197. if (::kill (childPID, SIGKILL) == 0)
  198. {
  199. childPID = 0;
  200. return true;
  201. }
  202. return false;
  203. }
  204. bool terminateProcess() const noexcept
  205. {
  206. return ::kill (childPID, SIGTERM) == 0;
  207. }
  208. uint32 getExitCodeAndClearPID() noexcept
  209. {
  210. if (childPID != 0)
  211. {
  212. int childState = 0;
  213. const int pid = waitpid (childPID, &childState, WNOHANG);
  214. childPID = 0;
  215. if (pid >= 0 && WIFEXITED (childState))
  216. return WEXITSTATUS (childState);
  217. }
  218. return 0;
  219. }
  220. int getPID() const noexcept
  221. {
  222. return childPID;
  223. }
  224. int childPID;
  225. private:
  226. CARLA_DECLARE_NON_COPYABLE (ActiveProcess)
  227. };
  228. #endif
  229. //=====================================================================================================================
  230. ChildProcess::ChildProcess() {}
  231. ChildProcess::~ChildProcess() {}
  232. bool ChildProcess::isRunning() const
  233. {
  234. return activeProcess != nullptr && activeProcess->isRunning();
  235. }
  236. bool ChildProcess::kill()
  237. {
  238. return activeProcess == nullptr || activeProcess->killProcess();
  239. }
  240. bool ChildProcess::terminate()
  241. {
  242. return activeProcess == nullptr || activeProcess->terminateProcess();
  243. }
  244. uint32 ChildProcess::getExitCodeAndClearPID()
  245. {
  246. return activeProcess != nullptr ? activeProcess->getExitCodeAndClearPID() : 0;
  247. }
  248. bool ChildProcess::waitForProcessToFinish (const int timeoutMs)
  249. {
  250. const uint32 timeoutTime = Time::getMillisecondCounter() + (uint32) timeoutMs;
  251. do
  252. {
  253. if (activeProcess == nullptr)
  254. return true;
  255. if (! activeProcess->checkRunningAndUnsetPID())
  256. return true;
  257. carla_msleep(5);
  258. }
  259. while (timeoutMs < 0 || Time::getMillisecondCounter() < timeoutTime);
  260. return false;
  261. }
  262. uint32 ChildProcess::getPID() const noexcept
  263. {
  264. return activeProcess != nullptr ? activeProcess->getPID() : 0;
  265. }
  266. //=====================================================================================================================
  267. #ifdef CARLA_OS_WIN
  268. bool ChildProcess::start (const String& command, Type)
  269. {
  270. activeProcess = new ActiveProcess (command);
  271. if (! activeProcess->ok)
  272. activeProcess = nullptr;
  273. return activeProcess != nullptr;
  274. }
  275. bool ChildProcess::start (const StringArray& args, const Type type)
  276. {
  277. String escaped;
  278. for (int i = 0, size = args.size(); i < size; ++i)
  279. {
  280. String arg (args[i]);
  281. // If there are spaces, surround it with quotes. If there are quotes,
  282. // replace them with \" so that CommandLineToArgv will correctly parse them.
  283. if (arg.containsAnyOf ("\" "))
  284. arg = arg.replace ("\"", "\\\"").quoted();
  285. escaped << arg;
  286. if (i+1 < size)
  287. escaped << ' ';
  288. }
  289. return start (escaped.trim(), type);
  290. }
  291. #else
  292. bool ChildProcess::start (const String& command, const Type type)
  293. {
  294. return start (StringArray::fromTokens (command, true), type);
  295. }
  296. bool ChildProcess::start (const StringArray& args, const Type type)
  297. {
  298. if (args.size() == 0)
  299. return false;
  300. activeProcess = new ActiveProcess (args, type);
  301. if (activeProcess->childPID == 0)
  302. activeProcess = nullptr;
  303. return activeProcess != nullptr;
  304. }
  305. #endif
  306. }