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.

404 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2018 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. #include "../streams/MemoryOutputStream.h"
  24. #ifndef CARLA_OS_WIN
  25. # include <signal.h>
  26. # include <sys/wait.h>
  27. #endif
  28. namespace water {
  29. #ifdef CARLA_OS_WIN
  30. //=====================================================================================================================
  31. class ChildProcess::ActiveProcess
  32. {
  33. public:
  34. ActiveProcess (const String& command, int streamFlags)
  35. : ok (false), readPipe (0), writePipe (0)
  36. {
  37. SECURITY_ATTRIBUTES securityAtts;
  38. carla_zeroStruct(securityAtts);
  39. securityAtts.nLength = sizeof (securityAtts);
  40. securityAtts.bInheritHandle = TRUE;
  41. if (CreatePipe (&readPipe, &writePipe, &securityAtts, 0)
  42. && SetHandleInformation (readPipe, HANDLE_FLAG_INHERIT, 0))
  43. {
  44. STARTUPINFO startupInfo;
  45. carla_zeroStruct(startupInfo);
  46. startupInfo.cb = sizeof (startupInfo);
  47. startupInfo.hStdOutput = (streamFlags & wantStdOut) != 0 ? writePipe : 0;
  48. startupInfo.hStdError = (streamFlags & wantStdErr) != 0 ? writePipe : 0;
  49. startupInfo.dwFlags = STARTF_USESTDHANDLES;
  50. ok = CreateProcess (nullptr, const_cast<LPSTR>(command.toRawUTF8()),
  51. nullptr, nullptr, TRUE, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
  52. nullptr, nullptr, &startupInfo, &processInfo) != FALSE;
  53. }
  54. }
  55. ~ActiveProcess()
  56. {
  57. if (ok)
  58. {
  59. CloseHandle (processInfo.hThread);
  60. CloseHandle (processInfo.hProcess);
  61. }
  62. if (readPipe != 0)
  63. CloseHandle (readPipe);
  64. if (writePipe != 0)
  65. CloseHandle (writePipe);
  66. }
  67. bool isRunning() const noexcept
  68. {
  69. return WaitForSingleObject (processInfo.hProcess, 0) != WAIT_OBJECT_0;
  70. }
  71. int read (void* dest, int numNeeded) const noexcept
  72. {
  73. int total = 0;
  74. while (ok && numNeeded > 0)
  75. {
  76. DWORD available = 0;
  77. if (! PeekNamedPipe ((HANDLE) readPipe, nullptr, 0, nullptr, &available, nullptr))
  78. break;
  79. const int numToDo = jmin ((int) available, numNeeded);
  80. if (available == 0)
  81. {
  82. if (! isRunning())
  83. break;
  84. Sleep(5);
  85. }
  86. else
  87. {
  88. DWORD numRead = 0;
  89. if (! ReadFile ((HANDLE) readPipe, dest, numToDo, &numRead, nullptr))
  90. break;
  91. total += numRead;
  92. dest = addBytesToPointer (dest, numRead);
  93. numNeeded -= numRead;
  94. }
  95. }
  96. return total;
  97. }
  98. bool killProcess() const noexcept
  99. {
  100. return TerminateProcess (processInfo.hProcess, 0) != FALSE;
  101. }
  102. bool terminateProcess() const noexcept
  103. {
  104. return TerminateProcess (processInfo.hProcess, 0) != FALSE;
  105. }
  106. uint32 getExitCode() const noexcept
  107. {
  108. DWORD exitCode = 0;
  109. GetExitCodeProcess (processInfo.hProcess, &exitCode);
  110. return (uint32) exitCode;
  111. }
  112. int getPID() const noexcept
  113. {
  114. return 0;
  115. }
  116. bool ok;
  117. private:
  118. HANDLE readPipe, writePipe;
  119. PROCESS_INFORMATION processInfo;
  120. CARLA_DECLARE_NON_COPY_CLASS (ActiveProcess)
  121. };
  122. #else
  123. class ChildProcess::ActiveProcess
  124. {
  125. public:
  126. ActiveProcess (const StringArray& arguments, int streamFlags)
  127. : childPID (0), pipeHandle (0), readHandle (0)
  128. {
  129. String exe (arguments[0].unquoted());
  130. // Looks like you're trying to launch a non-existent exe or a folder (perhaps on OSX
  131. // you're trying to launch the .app folder rather than the actual binary inside it?)
  132. wassert (File::getCurrentWorkingDirectory().getChildFile (exe).existsAsFile()
  133. || ! exe.containsChar (File::separator));
  134. int pipeHandles[2] = { 0 };
  135. if (pipe (pipeHandles) == 0)
  136. {
  137. Array<char*> argv;
  138. for (int i = 0; i < arguments.size(); ++i)
  139. if (arguments[i].isNotEmpty())
  140. argv.add (const_cast<char*> (arguments[i].toRawUTF8()));
  141. argv.add (nullptr);
  142. const pid_t result = vfork();
  143. if (result < 0)
  144. {
  145. close (pipeHandles[0]);
  146. close (pipeHandles[1]);
  147. }
  148. else if (result == 0)
  149. {
  150. if (execvp (exe.toRawUTF8(), argv.getRawDataPointer()))
  151. _exit (-1);
  152. }
  153. else
  154. {
  155. // we're the parent process..
  156. childPID = result;
  157. pipeHandle = pipeHandles[0];
  158. close (pipeHandles[1]); // close the write handle
  159. }
  160. // FIXME
  161. (void)streamFlags;
  162. }
  163. }
  164. ~ActiveProcess()
  165. {
  166. if (readHandle != 0)
  167. fclose (readHandle);
  168. if (pipeHandle != 0)
  169. close (pipeHandle);
  170. }
  171. bool isRunning() const noexcept
  172. {
  173. if (childPID != 0)
  174. {
  175. int childState = 0;
  176. const int pid = waitpid (childPID, &childState, WNOHANG|WUNTRACED);
  177. return pid == 0 || ! (WIFEXITED (childState) || WIFSIGNALED (childState) || WIFSTOPPED (childState));
  178. }
  179. return false;
  180. }
  181. int read (void* const dest, const int numBytes) noexcept
  182. {
  183. wassert (dest != nullptr);
  184. #ifdef fdopen
  185. #error // the zlib headers define this function as NULL!
  186. #endif
  187. if (readHandle == 0 && childPID != 0)
  188. readHandle = fdopen (pipeHandle, "r");
  189. if (readHandle != 0)
  190. return (int) fread (dest, 1, (size_t) numBytes, readHandle);
  191. return 0;
  192. }
  193. bool killProcess() const noexcept
  194. {
  195. return ::kill (childPID, SIGKILL) == 0;
  196. }
  197. bool terminateProcess() const noexcept
  198. {
  199. return ::kill (childPID, SIGTERM) == 0;
  200. }
  201. uint32 getExitCode() const noexcept
  202. {
  203. if (childPID != 0)
  204. {
  205. int childState = 0;
  206. const int pid = waitpid (childPID, &childState, WNOHANG);
  207. if (pid >= 0 && WIFEXITED (childState))
  208. return WEXITSTATUS (childState);
  209. }
  210. return 0;
  211. }
  212. int getPID() const noexcept
  213. {
  214. return childPID;
  215. }
  216. int childPID;
  217. private:
  218. int pipeHandle;
  219. FILE* readHandle;
  220. CARLA_DECLARE_NON_COPY_CLASS (ActiveProcess)
  221. };
  222. #endif
  223. //=====================================================================================================================
  224. ChildProcess::ChildProcess() {}
  225. ChildProcess::~ChildProcess() {}
  226. bool ChildProcess::isRunning() const
  227. {
  228. return activeProcess != nullptr && activeProcess->isRunning();
  229. }
  230. int ChildProcess::readProcessOutput (void* dest, int numBytes)
  231. {
  232. return activeProcess != nullptr ? activeProcess->read (dest, numBytes) : 0;
  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::getExitCode() const
  243. {
  244. return activeProcess != nullptr ? activeProcess->getExitCode() : 0;
  245. }
  246. bool ChildProcess::waitForProcessToFinish (const int timeoutMs) const
  247. {
  248. const uint32 timeoutTime = Time::getMillisecondCounter() + (uint32) timeoutMs;
  249. do
  250. {
  251. if (! isRunning())
  252. return true;
  253. carla_msleep(5);
  254. }
  255. while (timeoutMs < 0 || Time::getMillisecondCounter() < timeoutTime);
  256. return false;
  257. }
  258. String ChildProcess::readAllProcessOutput()
  259. {
  260. MemoryOutputStream result;
  261. for (;;)
  262. {
  263. char buffer [512];
  264. const int num = readProcessOutput (buffer, sizeof (buffer));
  265. if (num <= 0)
  266. break;
  267. result.write (buffer, (size_t) num);
  268. }
  269. return result.toString();
  270. }
  271. uint32 ChildProcess::getPID() const noexcept
  272. {
  273. return activeProcess != nullptr ? activeProcess->getPID() : 0;
  274. }
  275. //=====================================================================================================================
  276. #ifdef CARLA_OS_WIN
  277. bool ChildProcess::start (const String& command, int streamFlags)
  278. {
  279. activeProcess = new ActiveProcess (command, streamFlags);
  280. if (! activeProcess->ok)
  281. activeProcess = nullptr;
  282. return activeProcess != nullptr;
  283. }
  284. bool ChildProcess::start (const StringArray& args, int streamFlags)
  285. {
  286. String escaped;
  287. for (int i = 0, size = args.size(); i < size; ++i)
  288. {
  289. String arg (args[i]);
  290. // If there are spaces, surround it with quotes. If there are quotes,
  291. // replace them with \" so that CommandLineToArgv will correctly parse them.
  292. if (arg.containsAnyOf ("\" "))
  293. arg = arg.replace ("\"", "\\\"").quoted();
  294. escaped << arg;
  295. if (i+1 < size)
  296. escaped << ' ';
  297. }
  298. return start (escaped.trim(), streamFlags);
  299. }
  300. #else
  301. bool ChildProcess::start (const String& command, int streamFlags)
  302. {
  303. return start (StringArray::fromTokens (command, true), streamFlags);
  304. }
  305. bool ChildProcess::start (const StringArray& args, int streamFlags)
  306. {
  307. if (args.size() == 0)
  308. return false;
  309. activeProcess = new ActiveProcess (args, streamFlags);
  310. if (activeProcess->childPID == 0)
  311. activeProcess = nullptr;
  312. return activeProcess != nullptr;
  313. }
  314. #endif
  315. }