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.

379 lines
9.9KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2020 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. STARTUPINFO startupInfo;
  42. carla_zeroStruct(startupInfo);
  43. startupInfo.cb = sizeof (startupInfo);
  44. ok = CreateProcess (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_COPY_CLASS (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. case TypeARM:
  121. pref = CPU_TYPE_ARM64;
  122. break;
  123. case TypeIntel:
  124. pref = CPU_TYPE_X86_64;
  125. break;
  126. default:
  127. pref = CPU_TYPE_ANY;
  128. break;
  129. }
  130. posix_spawnattr_t attr;
  131. posix_spawnattr_init(&attr);
  132. // posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
  133. CARLA_SAFE_ASSERT_RETURN(posix_spawnattr_setbinpref_np(&attr, 1, &pref, nullptr) == 0,);
  134. char*** const environptr = _NSGetEnviron();
  135. CARLA_SAFE_ASSERT_RETURN(posix_spawn(&result, exe.toRawUTF8(), nullptr, &attr,
  136. argv.getRawDataPointer(), environptr != nullptr ? *environptr : nullptr) == 0,);
  137. posix_spawnattr_destroy(&attr);
  138. #else
  139. const pid_t result = vfork();
  140. #endif
  141. if (result < 0)
  142. {
  143. // error
  144. }
  145. #ifndef CARLA_OS_MAC
  146. else if (result == 0)
  147. {
  148. // child process
  149. carla_terminateProcessOnParentExit(true);
  150. if (execvp (exe.toRawUTF8(), argv.getRawDataPointer()))
  151. _exit (-1);
  152. }
  153. #endif
  154. else
  155. {
  156. // we're the parent process..
  157. childPID = result;
  158. }
  159. #ifndef CARLA_OS_MAC
  160. // unused
  161. (void)type;
  162. #endif
  163. }
  164. ~ActiveProcess()
  165. {
  166. CARLA_SAFE_ASSERT_INT(childPID == 0, childPID);
  167. }
  168. bool isRunning() const noexcept
  169. {
  170. if (childPID != 0)
  171. {
  172. int childState = 0;
  173. const int pid = waitpid (childPID, &childState, WNOHANG|WUNTRACED);
  174. return pid == 0 || ! (WIFEXITED (childState) || WIFSIGNALED (childState) || WIFSTOPPED (childState));
  175. }
  176. return false;
  177. }
  178. bool checkRunningAndUnsetPID() noexcept
  179. {
  180. if (childPID != 0)
  181. {
  182. int childState = 0;
  183. const int pid = waitpid (childPID, &childState, WNOHANG|WUNTRACED);
  184. if (pid == 0)
  185. return true;
  186. if ( ! (WIFEXITED (childState) || WIFSIGNALED (childState) || WIFSTOPPED (childState)))
  187. return true;
  188. childPID = 0;
  189. return false;
  190. }
  191. return false;
  192. }
  193. bool killProcess() noexcept
  194. {
  195. if (::kill (childPID, SIGKILL) == 0)
  196. {
  197. childPID = 0;
  198. return true;
  199. }
  200. return false;
  201. }
  202. bool terminateProcess() const noexcept
  203. {
  204. return ::kill (childPID, SIGTERM) == 0;
  205. }
  206. uint32 getExitCodeAndClearPID() noexcept
  207. {
  208. if (childPID != 0)
  209. {
  210. int childState = 0;
  211. const int pid = waitpid (childPID, &childState, WNOHANG);
  212. childPID = 0;
  213. if (pid >= 0 && WIFEXITED (childState))
  214. return WEXITSTATUS (childState);
  215. }
  216. return 0;
  217. }
  218. int getPID() const noexcept
  219. {
  220. return childPID;
  221. }
  222. int childPID;
  223. private:
  224. CARLA_DECLARE_NON_COPY_CLASS (ActiveProcess)
  225. };
  226. #endif
  227. //=====================================================================================================================
  228. ChildProcess::ChildProcess() {}
  229. ChildProcess::~ChildProcess() {}
  230. bool ChildProcess::isRunning() const
  231. {
  232. return activeProcess != nullptr && activeProcess->isRunning();
  233. }
  234. bool ChildProcess::kill()
  235. {
  236. return activeProcess == nullptr || activeProcess->killProcess();
  237. }
  238. bool ChildProcess::terminate()
  239. {
  240. return activeProcess == nullptr || activeProcess->terminateProcess();
  241. }
  242. uint32 ChildProcess::getExitCodeAndClearPID()
  243. {
  244. return activeProcess != nullptr ? activeProcess->getExitCodeAndClearPID() : 0;
  245. }
  246. bool ChildProcess::waitForProcessToFinish (const int timeoutMs)
  247. {
  248. const uint32 timeoutTime = Time::getMillisecondCounter() + (uint32) timeoutMs;
  249. do
  250. {
  251. if (activeProcess == nullptr)
  252. return true;
  253. if (! activeProcess->checkRunningAndUnsetPID())
  254. return true;
  255. carla_msleep(5);
  256. }
  257. while (timeoutMs < 0 || Time::getMillisecondCounter() < timeoutTime);
  258. return false;
  259. }
  260. uint32 ChildProcess::getPID() const noexcept
  261. {
  262. return activeProcess != nullptr ? activeProcess->getPID() : 0;
  263. }
  264. //=====================================================================================================================
  265. #ifdef CARLA_OS_WIN
  266. bool ChildProcess::start (const String& command, Type)
  267. {
  268. activeProcess = new ActiveProcess (command);
  269. if (! activeProcess->ok)
  270. activeProcess = nullptr;
  271. return activeProcess != nullptr;
  272. }
  273. bool ChildProcess::start (const StringArray& args, const Type type)
  274. {
  275. String escaped;
  276. for (int i = 0, size = args.size(); i < size; ++i)
  277. {
  278. String arg (args[i]);
  279. // If there are spaces, surround it with quotes. If there are quotes,
  280. // replace them with \" so that CommandLineToArgv will correctly parse them.
  281. if (arg.containsAnyOf ("\" "))
  282. arg = arg.replace ("\"", "\\\"").quoted();
  283. escaped << arg;
  284. if (i+1 < size)
  285. escaped << ' ';
  286. }
  287. return start (escaped.trim(), type);
  288. }
  289. #else
  290. bool ChildProcess::start (const String& command, const Type type)
  291. {
  292. return start (StringArray::fromTokens (command, true), type);
  293. }
  294. bool ChildProcess::start (const StringArray& args, const Type type)
  295. {
  296. if (args.size() == 0)
  297. return false;
  298. activeProcess = new ActiveProcess (args, type);
  299. if (activeProcess->childPID == 0)
  300. activeProcess = nullptr;
  301. return activeProcess != nullptr;
  302. }
  303. #endif
  304. }