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