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.

1227 lines
34KB

  1. /*
  2. * Carla Utility Tests
  3. * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPipeUtils.hpp"
  18. #include "CarlaString.hpp"
  19. #include "juce_core.h"
  20. #include <clocale>
  21. #ifdef CARLA_OS_WIN
  22. # include <ctime>
  23. #else
  24. # include <cerrno>
  25. # include <fcntl.h>
  26. # include <signal.h>
  27. # include <sys/wait.h>
  28. #endif
  29. #ifdef CARLA_OS_WIN
  30. # define INVALID_PIPE_VALUE INVALID_HANDLE_VALUE
  31. #else
  32. # define INVALID_PIPE_VALUE -1
  33. #endif
  34. #ifdef CARLA_OS_WIN
  35. // -----------------------------------------------------------------------
  36. // win32 stuff
  37. struct OverlappedEvent {
  38. OVERLAPPED over;
  39. OverlappedEvent()
  40. : over()
  41. {
  42. carla_zeroStruct(over);
  43. over.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
  44. }
  45. ~OverlappedEvent()
  46. {
  47. ::CloseHandle(over.hEvent);
  48. }
  49. CARLA_DECLARE_NON_COPY_STRUCT(OverlappedEvent)
  50. };
  51. static inline
  52. ssize_t ReadFileNonBlock(const HANDLE pipeh, const HANDLE cancelh, void* buf, size_t numBytes)
  53. {
  54. DWORD dsize;
  55. OverlappedEvent over;
  56. if (::ReadFile(pipeh, buf, numBytes, &dsize, &over.over) != FALSE)
  57. return static_cast<ssize_t>(dsize);
  58. if (GetLastError() == ERROR_IO_PENDING)
  59. {
  60. HANDLE handles[] = { over.over.hEvent, cancelh };
  61. if (WaitForMultipleObjects(2, handles, FALSE, 0) != WAIT_OBJECT_0)
  62. {
  63. CancelIo(pipeh);
  64. return -1;
  65. }
  66. if (GetOverlappedResult(pipeh, &over.over, &dsize, FALSE) != FALSE)
  67. return static_cast<ssize_t>(dsize);
  68. }
  69. return -1;
  70. }
  71. #endif // CARLA_OS_WIN
  72. // -----------------------------------------------------------------------
  73. // startProcess
  74. #ifdef CARLA_OS_WIN
  75. static inline
  76. bool startProcess(const char* const argv[], PROCESS_INFORMATION& processInfo)
  77. {
  78. using juce::String;
  79. String command;
  80. for (int i=0; argv[i] != nullptr; ++i)
  81. {
  82. String arg(argv[i]);
  83. // If there are spaces, surround it with quotes. If there are quotes,
  84. // replace them with \" so that CommandLineToArgv will correctly parse them.
  85. if (arg.containsAnyOf("\" "))
  86. arg = arg.replace("\"", "\\\"").quoted();
  87. command << arg << ' ';
  88. }
  89. command = command.trim();
  90. STARTUPINFOW startupInfo;
  91. carla_zeroStruct(startupInfo);
  92. //# if 1
  93. startupInfo.hStdInput = INVALID_HANDLE_VALUE;
  94. startupInfo.hStdOutput = INVALID_HANDLE_VALUE;
  95. startupInfo.hStdError = INVALID_HANDLE_VALUE;
  96. startupInfo.dwFlags = STARTF_USESTDHANDLES;
  97. //# endif
  98. startupInfo.cb = sizeof(STARTUPINFOW);
  99. return CreateProcessW(nullptr, const_cast<LPWSTR>(command.toWideCharPointer()),
  100. nullptr, nullptr, TRUE, 0x0, nullptr, nullptr, &startupInfo, &processInfo) != FALSE;
  101. }
  102. #else
  103. static inline
  104. bool startProcess(const char* const argv[], pid_t& pidinst) noexcept
  105. {
  106. const pid_t ret = pidinst = vfork();
  107. switch (ret)
  108. {
  109. case 0: { // child process
  110. execvp(argv[0], const_cast<char* const*>(argv));
  111. CarlaString error(std::strerror(errno));
  112. carla_stderr2("exec failed: %s", error.buffer());
  113. _exit(0); // this is not noexcept safe but doesn't matter anyway
  114. } break;
  115. case -1: { // error
  116. CarlaString error(std::strerror(errno));
  117. carla_stderr2("fork() failed: %s", error.buffer());
  118. _exit(0); // this is not noexcept safe but doesn't matter anyway
  119. } break;
  120. }
  121. return (ret > 0);
  122. }
  123. #endif
  124. // -----------------------------------------------------------------------
  125. // waitForClientFirstMessage
  126. template<typename P>
  127. static inline
  128. bool waitForClientFirstMessage(const P& pipe, const uint32_t timeOutMilliseconds) noexcept
  129. {
  130. #ifdef CARLA_OS_WIN
  131. CARLA_SAFE_ASSERT_RETURN(pipe.handle != INVALID_HANDLE_VALUE, false);
  132. CARLA_SAFE_ASSERT_RETURN(pipe.cancel != INVALID_HANDLE_VALUE, false);
  133. #else
  134. CARLA_SAFE_ASSERT_RETURN(pipe > 0, false);
  135. #endif
  136. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  137. char c;
  138. ssize_t ret;
  139. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  140. for (;;)
  141. {
  142. try {
  143. #ifdef CARLA_OS_WIN
  144. ret = ::ReadFileNonBlock(pipe.handle, pipe.cancel, &c, 1);
  145. #else
  146. ret = ::read(pipe, &c, 1);
  147. #endif
  148. } CARLA_SAFE_EXCEPTION_BREAK("read pipefd");
  149. switch (ret)
  150. {
  151. case -1: // failed to read
  152. #ifndef CARLA_OS_WIN
  153. if (errno == EAGAIN)
  154. #endif
  155. {
  156. if (juce::Time::getMillisecondCounter() < timeoutEnd)
  157. {
  158. carla_msleep(5);
  159. continue;
  160. }
  161. carla_stderr("waitForClientFirstMessage() - timed out");
  162. }
  163. #ifndef CARLA_OS_WIN
  164. else
  165. {
  166. carla_stderr("waitForClientFirstMessage() - read failed");
  167. CarlaString error(std::strerror(errno));
  168. carla_stderr("waitForClientFirstMessage() - read failed: %s", error.buffer());
  169. }
  170. #endif
  171. break;
  172. case 1: // read ok
  173. if (c == '\n')
  174. {
  175. // success
  176. return true;
  177. }
  178. else
  179. {
  180. carla_stderr("waitForClientFirstMessage() - read has wrong first char '%c'", c);
  181. }
  182. break;
  183. default: // ???
  184. carla_stderr("waitForClientFirstMessage() - read returned %i", int(ret));
  185. break;
  186. }
  187. break;
  188. }
  189. return false;
  190. }
  191. // -----------------------------------------------------------------------
  192. // waitForChildToStop / waitForProcessToStop
  193. #ifdef CARLA_OS_WIN
  194. static inline
  195. bool waitForProcessToStop(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  196. {
  197. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE, false);
  198. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  199. // TODO - this code is completly wrong...
  200. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  201. for (;;)
  202. {
  203. if (WaitForSingleObject(processInfo.hProcess, 0) == WAIT_OBJECT_0)
  204. return true;
  205. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  206. break;
  207. carla_msleep(5);
  208. }
  209. return false;
  210. }
  211. static inline
  212. void waitForProcessToStopOrKillIt(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  213. {
  214. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE,);
  215. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  216. if (! waitForProcessToStop(processInfo, timeOutMilliseconds))
  217. {
  218. carla_stderr("waitForProcessToStopOrKillIt() - process didn't stop, force termination");
  219. if (TerminateProcess(processInfo.hProcess, 0) != FALSE)
  220. {
  221. // wait for process to stop
  222. waitForProcessToStop(processInfo, timeOutMilliseconds);
  223. }
  224. }
  225. }
  226. #else
  227. static inline
  228. bool waitForChildToStop(const pid_t pid, const uint32_t timeOutMilliseconds) noexcept
  229. {
  230. CARLA_SAFE_ASSERT_RETURN(pid > 0, false);
  231. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  232. pid_t ret;
  233. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  234. for (;;)
  235. {
  236. try {
  237. ret = ::waitpid(pid, nullptr, WNOHANG);
  238. } CARLA_SAFE_EXCEPTION_BREAK("waitpid");
  239. switch (ret)
  240. {
  241. case -1:
  242. if (errno == ECHILD)
  243. {
  244. // success, child doesn't exist
  245. return true;
  246. }
  247. else
  248. {
  249. CarlaString error(std::strerror(errno));
  250. carla_stderr("waitForChildToStop() - waitpid failed: %s", error.buffer());
  251. return false;
  252. }
  253. break;
  254. case 0:
  255. if (juce::Time::getMillisecondCounter() < timeoutEnd)
  256. {
  257. carla_msleep(5);
  258. continue;
  259. }
  260. carla_stderr("waitForChildToStop() - timed out");
  261. break;
  262. default:
  263. if (ret == pid)
  264. {
  265. // success
  266. return true;
  267. }
  268. else
  269. {
  270. carla_stderr("waitForChildToStop() - got wrong pid %i (requested was %i)", int(ret), int(pid));
  271. return false;
  272. }
  273. }
  274. break;
  275. }
  276. return false;
  277. }
  278. static inline
  279. void waitForChildToStopOrKillIt(pid_t& pid, const uint32_t timeOutMilliseconds) noexcept
  280. {
  281. CARLA_SAFE_ASSERT_RETURN(pid > 0,);
  282. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  283. if (! waitForChildToStop(pid, timeOutMilliseconds))
  284. {
  285. carla_stderr("waitForChildToStopOrKillIt() - process didn't stop, force killing");
  286. if (::kill(pid, SIGKILL) != -1)
  287. {
  288. // wait for killing to take place
  289. waitForChildToStop(pid, timeOutMilliseconds);
  290. }
  291. else
  292. {
  293. CarlaString error(std::strerror(errno));
  294. carla_stderr("waitForChildToStopOrKillIt() - kill failed: %s", error.buffer());
  295. }
  296. }
  297. }
  298. #endif
  299. // -----------------------------------------------------------------------
  300. struct CarlaPipeCommon::PrivateData {
  301. // pipes
  302. #ifdef CARLA_OS_WIN
  303. PROCESS_INFORMATION processInfo;
  304. HANDLE cancelEvent;
  305. HANDLE pipeRecv;
  306. HANDLE pipeSend;
  307. #else
  308. pid_t pid;
  309. int pipeRecv;
  310. int pipeSend;
  311. #endif
  312. // read functions must only be called in context of idle()
  313. bool isReading;
  314. // common write lock
  315. CarlaMutex writeLock;
  316. // temporary buffers for readline()
  317. char tmpBuf[0xff+1];
  318. CarlaString tmpStr;
  319. PrivateData() noexcept
  320. #ifdef CARLA_OS_WIN
  321. : processInfo(),
  322. cancelEvent(INVALID_HANDLE_VALUE),
  323. #else
  324. : pid(-1),
  325. #endif
  326. pipeRecv(INVALID_PIPE_VALUE),
  327. pipeSend(INVALID_PIPE_VALUE),
  328. isReading(false),
  329. writeLock(),
  330. tmpBuf(),
  331. tmpStr()
  332. {
  333. #ifdef CARLA_OS_WIN
  334. carla_zeroStruct(processInfo);
  335. try {
  336. cancelEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
  337. } CARLA_SAFE_EXCEPTION("CreateEvent");
  338. #endif
  339. carla_zeroChar(tmpBuf, 0xff+1);
  340. }
  341. ~PrivateData() noexcept
  342. {
  343. #ifdef CARLA_OS_WIN
  344. if (cancelEvent != INVALID_HANDLE_VALUE)
  345. {
  346. ::CloseHandle(cancelEvent);
  347. cancelEvent = INVALID_HANDLE_VALUE;
  348. }
  349. #endif
  350. }
  351. CARLA_DECLARE_NON_COPY_STRUCT(PrivateData)
  352. };
  353. // -----------------------------------------------------------------------
  354. CarlaPipeCommon::CarlaPipeCommon() noexcept
  355. : pData(new PrivateData()),
  356. leakDetector_CarlaPipeCommon()
  357. {
  358. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  359. }
  360. CarlaPipeCommon::~CarlaPipeCommon() noexcept
  361. {
  362. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  363. delete pData;
  364. }
  365. // -------------------------------------------------------------------
  366. void CarlaPipeCommon::idle() noexcept
  367. {
  368. const char* locale = nullptr;
  369. for (;;)
  370. {
  371. const char* const msg(readline());
  372. if (msg == nullptr)
  373. break;
  374. if (locale == nullptr)
  375. {
  376. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  377. ::setlocale(LC_NUMERIC, "C");
  378. }
  379. pData->isReading = true;
  380. try {
  381. msgReceived(msg);
  382. } CARLA_SAFE_EXCEPTION("msgReceived");
  383. pData->isReading = false;
  384. delete[] msg;
  385. }
  386. if (locale != nullptr)
  387. {
  388. ::setlocale(LC_NUMERIC, locale);
  389. delete[] locale;
  390. }
  391. }
  392. bool CarlaPipeCommon::isRunning() const noexcept
  393. {
  394. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE);
  395. }
  396. // -------------------------------------------------------------------
  397. void CarlaPipeCommon::lock() const noexcept
  398. {
  399. pData->writeLock.lock();
  400. }
  401. bool CarlaPipeCommon::tryLock() const noexcept
  402. {
  403. return pData->writeLock.tryLock();
  404. }
  405. void CarlaPipeCommon::unlock() const noexcept
  406. {
  407. pData->writeLock.unlock();
  408. }
  409. CarlaMutex& CarlaPipeCommon::getLock() noexcept
  410. {
  411. return pData->writeLock;
  412. }
  413. // -------------------------------------------------------------------
  414. bool CarlaPipeCommon::readNextLineAsBool(bool& value) noexcept
  415. {
  416. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  417. if (const char* const msg = readline())
  418. {
  419. value = (std::strcmp(msg, "true") == 0);
  420. delete[] msg;
  421. return true;
  422. }
  423. return false;
  424. }
  425. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) noexcept
  426. {
  427. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  428. if (const char* const msg = readline())
  429. {
  430. value = std::atoi(msg);
  431. delete[] msg;
  432. return true;
  433. }
  434. return false;
  435. }
  436. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) noexcept
  437. {
  438. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  439. if (const char* const msg = readline())
  440. {
  441. int32_t tmp = std::atoi(msg);
  442. delete[] msg;
  443. if (tmp >= 0)
  444. {
  445. value = static_cast<uint32_t>(tmp);
  446. return true;
  447. }
  448. }
  449. return false;
  450. }
  451. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) noexcept
  452. {
  453. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  454. if (const char* const msg = readline())
  455. {
  456. value = std::atol(msg);
  457. delete[] msg;
  458. return true;
  459. }
  460. return false;
  461. }
  462. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) noexcept
  463. {
  464. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  465. if (const char* const msg = readline())
  466. {
  467. int64_t tmp = std::atol(msg);
  468. delete[] msg;
  469. if (tmp >= 0)
  470. {
  471. value = static_cast<uint64_t>(tmp);
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. bool CarlaPipeCommon::readNextLineAsFloat(float& value) noexcept
  478. {
  479. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  480. if (const char* const msg = readline())
  481. {
  482. value = static_cast<float>(std::atof(msg));
  483. delete[] msg;
  484. return true;
  485. }
  486. return false;
  487. }
  488. bool CarlaPipeCommon::readNextLineAsDouble(double& value) noexcept
  489. {
  490. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  491. if (const char* const msg = readline())
  492. {
  493. value = std::atof(msg);
  494. delete[] msg;
  495. return true;
  496. }
  497. return false;
  498. }
  499. bool CarlaPipeCommon::readNextLineAsString(const char*& value) noexcept
  500. {
  501. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  502. if (const char* const msg = readline())
  503. {
  504. value = msg;
  505. return true;
  506. }
  507. return false;
  508. }
  509. // -------------------------------------------------------------------
  510. // must be locked before calling
  511. bool CarlaPipeCommon::writeMsg(const char* const msg) const noexcept
  512. {
  513. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  514. const std::size_t size(std::strlen(msg));
  515. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  516. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  517. return writeMsgBuffer(msg, size);
  518. }
  519. bool CarlaPipeCommon::writeMsg(const char* const msg, std::size_t size) const noexcept
  520. {
  521. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  522. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  523. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  524. return writeMsgBuffer(msg, size);
  525. }
  526. bool CarlaPipeCommon::writeAndFixMsg(const char* const msg) noexcept
  527. {
  528. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  529. const std::size_t size(std::strlen(msg));
  530. char fixedMsg[size+2];
  531. if (size > 0)
  532. {
  533. std::strcpy(fixedMsg, msg);
  534. for (size_t i=0; i < size; ++i)
  535. {
  536. if (fixedMsg[i] == '\n')
  537. fixedMsg[i] = '\r';
  538. }
  539. if (fixedMsg[size-1] == '\r')
  540. {
  541. fixedMsg[size-1] = '\n';
  542. fixedMsg[size] = '\0';
  543. fixedMsg[size+1] = '\0';
  544. }
  545. else
  546. {
  547. fixedMsg[size] = '\n';
  548. fixedMsg[size+1] = '\0';
  549. }
  550. }
  551. else
  552. {
  553. fixedMsg[0] = '\n';
  554. fixedMsg[1] = '\0';
  555. }
  556. return writeMsgBuffer(fixedMsg, size+1);
  557. }
  558. // -------------------------------------------------------------------
  559. // internal
  560. const char* CarlaPipeCommon::readline() noexcept
  561. {
  562. char c;
  563. char* ptr = pData->tmpBuf;
  564. ssize_t ret;
  565. pData->tmpStr.clear();
  566. for (int i=0; i < 0xff; ++i)
  567. {
  568. try {
  569. #ifdef CARLA_OS_WIN
  570. ret = ::ReadFileNonBlock(pData->pipeRecv, pData->cancelEvent, &c, 1);
  571. #else
  572. ret = ::read(pData->pipeRecv, &c, 1);
  573. #endif
  574. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  575. if (ret == 1 && c != '\n')
  576. {
  577. if (c == '\r')
  578. c = '\n';
  579. *ptr++ = c;
  580. if (i+1 == 0xff)
  581. {
  582. i = 0;
  583. ptr = pData->tmpBuf;
  584. pData->tmpStr += pData->tmpBuf;
  585. }
  586. continue;
  587. }
  588. if (pData->tmpStr.isNotEmpty() || ptr != pData->tmpBuf)
  589. {
  590. if (ptr != pData->tmpBuf)
  591. {
  592. *ptr = '\0';
  593. pData->tmpStr += pData->tmpBuf;
  594. }
  595. try {
  596. return pData->tmpStr.dup();
  597. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  598. }
  599. break;
  600. }
  601. return nullptr;
  602. }
  603. bool CarlaPipeCommon::writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  604. {
  605. // TESTING remove later (replace with trylock scope)
  606. if (pData->writeLock.tryLock())
  607. {
  608. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  609. pData->writeLock.unlock();
  610. return false;
  611. }
  612. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  613. try {
  614. #ifdef CARLA_OS_WIN
  615. return (::WriteFile(pData->pipeSend, msg, size, nullptr, nullptr) != FALSE);
  616. #else
  617. return (::write(pData->pipeSend, msg, size) == static_cast<ssize_t>(size));
  618. #endif
  619. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  620. }
  621. // -----------------------------------------------------------------------
  622. CarlaPipeServer::CarlaPipeServer() noexcept
  623. : CarlaPipeCommon(),
  624. leakDetector_CarlaPipeServer()
  625. {
  626. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  627. }
  628. CarlaPipeServer::~CarlaPipeServer() noexcept
  629. {
  630. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  631. stop(5*1000);
  632. }
  633. // -----------------------------------------------------------------------
  634. bool CarlaPipeServer::start(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  635. {
  636. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  637. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  638. #ifdef CARLA_OS_WIN
  639. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == nullptr, false);
  640. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == nullptr, false);
  641. #else
  642. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  643. #endif
  644. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  645. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  646. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  647. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  648. const CarlaMutexLocker cml(pData->writeLock);
  649. //----------------------------------------------------------------
  650. // create pipes
  651. #ifdef CARLA_OS_WIN
  652. HANDLE pipe1[2]; // read by server, written by client
  653. HANDLE pipe2[2]; // read by client, written by server
  654. SECURITY_ATTRIBUTES sa;
  655. carla_zeroStruct(sa);
  656. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  657. sa.bInheritHandle = TRUE;
  658. std::srand(static_cast<uint>(std::time(nullptr)));
  659. char strBuf[0xff+1];
  660. strBuf[0xff] = '\0';
  661. static ulong sCounter = 0;
  662. ++sCounter;
  663. const int randint = std::rand();
  664. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  665. pipe1[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  666. pipe1[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  667. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  668. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  669. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  670. if (pipe1[0] == INVALID_HANDLE_VALUE || pipe1[1] == INVALID_HANDLE_VALUE || pipe2[0] == INVALID_HANDLE_VALUE || pipe2[1] == INVALID_HANDLE_VALUE)
  671. {
  672. if (pipe1[0] != INVALID_HANDLE_VALUE) {
  673. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  674. }
  675. if (pipe1[1] != INVALID_HANDLE_VALUE) {
  676. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  677. }
  678. if (pipe2[0] != INVALID_HANDLE_VALUE) {
  679. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  680. }
  681. if (pipe2[1] != INVALID_HANDLE_VALUE) {
  682. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  683. }
  684. fail("pipe creation failed");
  685. return false;
  686. }
  687. HANDLE pipeRecvServer = pipe1[0];
  688. HANDLE pipeRecvClient = pipe2[0];
  689. HANDLE pipeSendClient = pipe1[1];
  690. HANDLE pipeSendServer = pipe2[1];
  691. #else
  692. int pipe1[2]; // read by server, written by client
  693. int pipe2[2]; // read by client, written by server
  694. if (::pipe(pipe1) != 0)
  695. {
  696. fail("pipe1 creation failed");
  697. return false;
  698. }
  699. if (::pipe(pipe2) != 0)
  700. {
  701. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  702. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  703. fail("pipe2 creation failed");
  704. return false;
  705. }
  706. int pipeRecvServer = pipe1[0];
  707. int pipeRecvClient = pipe2[0];
  708. int pipeSendClient = pipe1[1];
  709. int pipeSendServer = pipe2[1];
  710. #endif
  711. //----------------------------------------------------------------
  712. // set arguments
  713. const char* argv[8];
  714. //----------------------------------------------------------------
  715. // argv[0] => filename
  716. argv[0] = filename;
  717. //----------------------------------------------------------------
  718. // argv[1-2] => args
  719. argv[1] = arg1;
  720. argv[2] = arg2;
  721. //----------------------------------------------------------------
  722. // argv[3-6] => pipes
  723. char pipeRecvServerStr[100+1];
  724. char pipeRecvClientStr[100+1];
  725. char pipeSendServerStr[100+1];
  726. char pipeSendClientStr[100+1];
  727. std::snprintf(pipeRecvServerStr, 100, P_INTPTR, (intptr_t)pipeRecvServer); // pipe1[0]
  728. std::snprintf(pipeRecvClientStr, 100, P_INTPTR, (intptr_t)pipeRecvClient); // pipe2[0]
  729. std::snprintf(pipeSendServerStr, 100, P_INTPTR, (intptr_t)pipeSendServer); // pipe2[1]
  730. std::snprintf(pipeSendClientStr, 100, P_INTPTR, (intptr_t)pipeSendClient); // pipe1[1]
  731. pipeRecvServerStr[100] = '\0';
  732. pipeRecvClientStr[100] = '\0';
  733. pipeSendServerStr[100] = '\0';
  734. pipeSendClientStr[100] = '\0';
  735. argv[3] = pipeRecvServerStr; // pipe1[0] close READ
  736. argv[4] = pipeRecvClientStr; // pipe2[0] READ
  737. argv[5] = pipeSendServerStr; // pipe2[1] close SEND
  738. argv[6] = pipeSendClientStr; // pipe1[1] SEND
  739. //----------------------------------------------------------------
  740. // argv[7] => null
  741. argv[7] = nullptr;
  742. //----------------------------------------------------------------
  743. // start process
  744. #ifdef CARLA_OS_WIN
  745. if (! startProcess(argv, pData->processInfo))
  746. {
  747. carla_zeroStruct(pData->processInfo);
  748. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  749. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  750. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  751. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  752. fail("startProcess() failed");
  753. return false;
  754. }
  755. // just to make sure
  756. CARLA_SAFE_ASSERT(pData->processInfo.hThread != nullptr);
  757. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != nullptr);
  758. #else
  759. if (! startProcess(argv, pData->pid))
  760. {
  761. pData->pid = -1;
  762. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  763. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  764. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  765. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  766. fail("startProcess() failed");
  767. return false;
  768. }
  769. #endif
  770. //----------------------------------------------------------------
  771. // close duplicated handles used by the client
  772. #ifdef CARLA_OS_WIN
  773. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  774. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  775. #else
  776. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  777. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  778. #endif
  779. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  780. #ifndef CARLA_OS_WIN
  781. //----------------------------------------------------------------
  782. // set non-block reading
  783. int ret = 0;
  784. try {
  785. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  786. } catch (...) {
  787. ret = -1;
  788. fail("failed to set pipe as non-block");
  789. }
  790. #endif
  791. //----------------------------------------------------------------
  792. // wait for client to say something
  793. #ifdef CARLA_OS_WIN
  794. struct { HANDLE handle; HANDLE cancel; } pipe;
  795. pipe.handle = pipeRecvClient;
  796. pipe.cancel = pData->cancelEvent;
  797. if ( waitForClientFirstMessage(pipe, 10*1000 /* 10 secs */))
  798. #else
  799. if (ret != -1 && waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  800. #endif
  801. {
  802. pData->pipeRecv = pipeRecvClient;
  803. pData->pipeSend = pipeSendClient;
  804. carla_stdout("ALL OK!");
  805. return true;
  806. }
  807. //----------------------------------------------------------------
  808. // failed to set non-block or get first child message, cannot continue
  809. #ifdef CARLA_OS_WIN
  810. if (TerminateProcess(pData->processInfo.hProcess, 0) != FALSE)
  811. {
  812. // wait for process to stop
  813. waitForProcessToStop(pData->processInfo, 2*1000);
  814. }
  815. // clear pData->processInfo
  816. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  817. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  818. carla_zeroStruct(pData->processInfo);
  819. #else
  820. if (::kill(pData->pid, SIGKILL) != -1)
  821. {
  822. // wait for killing to take place
  823. waitForChildToStop(pData->pid, 2*1000);
  824. }
  825. pData->pid = -1;
  826. #endif
  827. //----------------------------------------------------------------
  828. // close pipes
  829. #ifdef CARLA_OS_WIN
  830. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  831. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  832. #else
  833. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  834. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  835. #endif
  836. return false;
  837. }
  838. void CarlaPipeServer::stop(const uint32_t timeOutMilliseconds) noexcept
  839. {
  840. carla_debug("CarlaPipeServer::stop(%i)", timeOutMilliseconds);
  841. #ifdef CARLA_OS_WIN
  842. if (pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  843. {
  844. const CarlaMutexLocker cml(pData->writeLock);
  845. if (pData->pipeSend != INVALID_PIPE_VALUE)
  846. writeMsgBuffer("quit\n", 5);
  847. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  848. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  849. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  850. carla_zeroStruct(pData->processInfo);
  851. }
  852. #else
  853. if (pData->pid != -1)
  854. {
  855. const CarlaMutexLocker cml(pData->writeLock);
  856. if (pData->pipeSend != INVALID_PIPE_VALUE)
  857. writeMsgBuffer("quit\n", 5);
  858. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  859. pData->pid = -1;
  860. }
  861. #endif
  862. close();
  863. }
  864. void CarlaPipeServer::close() noexcept
  865. {
  866. carla_debug("CarlaPipeServer::close()");
  867. const CarlaMutexLocker cml(pData->writeLock);
  868. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  869. {
  870. #ifdef CARLA_OS_WIN
  871. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  872. #else
  873. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  874. #endif
  875. pData->pipeRecv = INVALID_PIPE_VALUE;
  876. }
  877. if (pData->pipeSend != INVALID_PIPE_VALUE)
  878. {
  879. #ifdef CARLA_OS_WIN
  880. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  881. #else
  882. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  883. #endif
  884. pData->pipeSend = INVALID_PIPE_VALUE;
  885. }
  886. }
  887. // -----------------------------------------------------------------------
  888. CarlaPipeClient::CarlaPipeClient() noexcept
  889. : CarlaPipeCommon(),
  890. leakDetector_CarlaPipeClient()
  891. {
  892. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  893. }
  894. CarlaPipeClient::~CarlaPipeClient() noexcept
  895. {
  896. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  897. close();
  898. }
  899. bool CarlaPipeClient::init(char* argv[]) noexcept
  900. {
  901. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  902. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  903. const CarlaMutexLocker cml(pData->writeLock);
  904. //----------------------------------------------------------------
  905. // read arguments
  906. #ifdef CARLA_OS_WIN
  907. HANDLE pipeRecvServer = (HANDLE)std::atol(argv[3]); // READ
  908. HANDLE pipeRecvClient = (HANDLE)std::atol(argv[4]);
  909. HANDLE pipeSendServer = (HANDLE)std::atol(argv[5]); // SEND
  910. HANDLE pipeSendClient = (HANDLE)std::atol(argv[6]);
  911. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  912. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient != INVALID_HANDLE_VALUE, false);
  913. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  914. CARLA_SAFE_ASSERT_RETURN(pipeSendClient != INVALID_HANDLE_VALUE, false);
  915. #else
  916. int pipeRecvServer = std::atoi(argv[3]); // READ
  917. int pipeRecvClient = std::atoi(argv[4]);
  918. int pipeSendServer = std::atoi(argv[5]); // SEND
  919. int pipeSendClient = std::atoi(argv[6]);
  920. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  921. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  922. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  923. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  924. #endif
  925. //----------------------------------------------------------------
  926. // close duplicated handles used by the client
  927. #ifdef CARLA_OS_WIN
  928. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  929. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  930. #else
  931. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  932. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  933. #endif
  934. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  935. #ifndef CARLA_OS_WIN
  936. //----------------------------------------------------------------
  937. // set non-block reading
  938. int ret = 0;
  939. try {
  940. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  941. } catch (...) {
  942. ret = -1;
  943. }
  944. CARLA_SAFE_ASSERT_RETURN(ret != -1, false);
  945. #endif
  946. //----------------------------------------------------------------
  947. // done
  948. pData->pipeRecv = pipeRecvServer;
  949. pData->pipeSend = pipeSendServer;
  950. writeMsg("\n");
  951. return true;
  952. }
  953. void CarlaPipeClient::close() noexcept
  954. {
  955. carla_debug("CarlaPipeClient::close()");
  956. const CarlaMutexLocker cml(pData->writeLock);
  957. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  958. {
  959. #ifdef CARLA_OS_WIN
  960. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  961. #else
  962. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  963. #endif
  964. pData->pipeRecv = INVALID_PIPE_VALUE;
  965. }
  966. if (pData->pipeSend != INVALID_PIPE_VALUE)
  967. {
  968. #ifdef CARLA_OS_WIN
  969. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  970. #else
  971. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  972. #endif
  973. pData->pipeSend = INVALID_PIPE_VALUE;
  974. }
  975. }
  976. // -----------------------------------------------------------------------
  977. ScopedLocale::ScopedLocale() noexcept
  978. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  979. {
  980. ::setlocale(LC_NUMERIC, "C");
  981. }
  982. ScopedLocale::~ScopedLocale() noexcept
  983. {
  984. if (fLocale != nullptr)
  985. {
  986. ::setlocale(LC_NUMERIC, fLocale);
  987. delete[] fLocale;
  988. }
  989. }
  990. // -----------------------------------------------------------------------
  991. #undef INVALID_PIPE_VALUE