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.

1624 lines
45KB

  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 "CarlaMIDI.h"
  20. #include "juce_core.h"
  21. // needed for atom-util
  22. #ifndef nullptr
  23. # undef NULL
  24. # define NULL nullptr
  25. #endif
  26. #include "lv2/atom-util.h"
  27. #include <clocale>
  28. #ifdef CARLA_OS_WIN
  29. # include <ctime>
  30. #else
  31. # include <cerrno>
  32. # include <fcntl.h>
  33. # include <signal.h>
  34. # include <sys/wait.h>
  35. #endif
  36. #ifdef CARLA_OS_WIN
  37. # define INVALID_PIPE_VALUE INVALID_HANDLE_VALUE
  38. #else
  39. # define INVALID_PIPE_VALUE -1
  40. #endif
  41. #ifdef CARLA_OS_WIN
  42. // -----------------------------------------------------------------------
  43. // win32 stuff
  44. struct OverlappedEvent {
  45. OVERLAPPED over;
  46. OverlappedEvent()
  47. : over()
  48. {
  49. carla_zeroStruct(over);
  50. over.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
  51. }
  52. ~OverlappedEvent()
  53. {
  54. ::CloseHandle(over.hEvent);
  55. }
  56. CARLA_DECLARE_NON_COPY_STRUCT(OverlappedEvent)
  57. };
  58. // -----------------------------------------------------------------------
  59. // ReadFile
  60. static inline
  61. ssize_t ReadFileBlock(const HANDLE pipeh, void* const buf, const std::size_t numBytes)
  62. {
  63. DWORD dsize;
  64. if (::ReadFile(pipeh, buf, numBytes, &dsize, nullptr) != FALSE)
  65. return static_cast<ssize_t>(dsize);
  66. return -1;
  67. }
  68. static inline
  69. ssize_t ReadFileNonBlock(const HANDLE pipeh, const HANDLE cancelh, void* const buf, const std::size_t numBytes)
  70. {
  71. DWORD dsize = numBytes;
  72. OverlappedEvent over;
  73. if (::ReadFile(pipeh, buf, numBytes, nullptr /*&dsize*/, &over.over) != FALSE)
  74. return static_cast<ssize_t>(dsize);
  75. if (::GetLastError() == ERROR_IO_PENDING)
  76. {
  77. HANDLE handles[] = { over.over.hEvent, cancelh };
  78. if (::WaitForMultipleObjects(2, handles, FALSE, 0) != WAIT_OBJECT_0)
  79. {
  80. ::CancelIo(pipeh);
  81. return -1;
  82. }
  83. if (::GetOverlappedResult(pipeh, &over.over, nullptr /*&dsize*/, FALSE) != FALSE)
  84. return static_cast<ssize_t>(dsize);
  85. }
  86. return -1;
  87. }
  88. // -----------------------------------------------------------------------
  89. // WriteFile
  90. static inline
  91. ssize_t WriteFileBlock(const HANDLE pipeh, const void* const buf, const std::size_t numBytes)
  92. {
  93. DWORD dsize;
  94. if (::WriteFile(pipeh, buf, numBytes, &dsize, nullptr) != FALSE)
  95. return static_cast<ssize_t>(dsize);
  96. return -1;
  97. }
  98. static inline
  99. ssize_t WriteFileNonBlock(const HANDLE pipeh, const HANDLE cancelh, const void* const buf, const std::size_t numBytes)
  100. {
  101. DWORD dsize = numBytes;
  102. OverlappedEvent over;
  103. if (::WriteFile(pipeh, buf, numBytes, nullptr /*&dsize*/, &over.over) != FALSE)
  104. return static_cast<ssize_t>(dsize);
  105. if (::GetLastError() == ERROR_IO_PENDING)
  106. {
  107. HANDLE handles[] = { over.over.hEvent, cancelh };
  108. if (::WaitForMultipleObjects(2, handles, FALSE, 0) != WAIT_OBJECT_0)
  109. {
  110. ::CancelIo(pipeh);
  111. return -1;
  112. }
  113. if (::GetOverlappedResult(pipeh, &over.over, &dsize, FALSE) != FALSE)
  114. return static_cast<ssize_t>(dsize);
  115. }
  116. return -1;
  117. }
  118. #endif // CARLA_OS_WIN
  119. // -----------------------------------------------------------------------
  120. // startProcess
  121. #ifdef CARLA_OS_WIN
  122. static inline
  123. bool startProcess(const char* const argv[], PROCESS_INFORMATION* const processInfo)
  124. {
  125. CARLA_SAFE_ASSERT_RETURN(processInfo != nullptr, false);
  126. using juce::String;
  127. String command;
  128. for (int i=0; argv[i] != nullptr; ++i)
  129. {
  130. String arg(argv[i]);
  131. // If there are spaces, surround it with quotes. If there are quotes,
  132. // replace them with \" so that CommandLineToArgv will correctly parse them.
  133. if (arg.containsAnyOf("\" "))
  134. arg = arg.replace("\"", "\\\"").quoted();
  135. command << arg << ' ';
  136. }
  137. command = command.trim();
  138. carla_stdout("startProcess() command:\n%s", command.toRawUTF8());
  139. STARTUPINFOW startupInfo;
  140. carla_zeroStruct(startupInfo);
  141. # if 0
  142. startupInfo.hStdInput = INVALID_HANDLE_VALUE;
  143. startupInfo.hStdOutput = INVALID_HANDLE_VALUE;
  144. startupInfo.hStdError = INVALID_HANDLE_VALUE;
  145. startupInfo.dwFlags = STARTF_USESTDHANDLES;
  146. # endif
  147. startupInfo.cb = sizeof(STARTUPINFOW);
  148. return CreateProcessW(nullptr, const_cast<LPWSTR>(command.toWideCharPointer()),
  149. nullptr, nullptr, TRUE, 0x0, nullptr, nullptr, &startupInfo, processInfo) != FALSE;
  150. }
  151. #else
  152. static inline
  153. bool startProcess(const char* const argv[], pid_t& pidinst) noexcept
  154. {
  155. const pid_t ret = pidinst = vfork();
  156. switch (ret)
  157. {
  158. case 0: { // child process
  159. execvp(argv[0], const_cast<char* const*>(argv));
  160. CarlaString error(std::strerror(errno));
  161. carla_stderr2("exec failed: %s", error.buffer());
  162. _exit(0); // this is not noexcept safe but doesn't matter anyway
  163. } break;
  164. case -1: { // error
  165. CarlaString error(std::strerror(errno));
  166. carla_stderr2("fork() failed: %s", error.buffer());
  167. } break;
  168. }
  169. return (ret > 0);
  170. }
  171. #endif
  172. // -----------------------------------------------------------------------
  173. // waitForClientFirstMessage
  174. template<typename P>
  175. static inline
  176. bool waitForClientFirstMessage(const P& pipe, const uint32_t timeOutMilliseconds) noexcept
  177. {
  178. #ifdef CARLA_OS_WIN
  179. CARLA_SAFE_ASSERT_RETURN(pipe.handle != INVALID_HANDLE_VALUE, false);
  180. CARLA_SAFE_ASSERT_RETURN(pipe.cancel != INVALID_HANDLE_VALUE, false);
  181. #else
  182. CARLA_SAFE_ASSERT_RETURN(pipe > 0, false);
  183. #endif
  184. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  185. char c;
  186. ssize_t ret;
  187. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  188. for (;;)
  189. {
  190. try {
  191. #ifdef CARLA_OS_WIN
  192. //ret = ::ReadFileBlock(pipe.handle, &c, 1);
  193. ret = ::ReadFileNonBlock(pipe.handle, pipe.cancel, &c, 1);
  194. #else
  195. ret = ::read(pipe, &c, 1);
  196. #endif
  197. } CARLA_SAFE_EXCEPTION_BREAK("read pipefd");
  198. switch (ret)
  199. {
  200. case -1: // failed to read
  201. #ifndef CARLA_OS_WIN
  202. if (errno == EAGAIN)
  203. #endif
  204. {
  205. if (juce::Time::getMillisecondCounter() < timeoutEnd)
  206. {
  207. carla_msleep(5);
  208. continue;
  209. }
  210. carla_stderr("waitForClientFirstMessage() - timed out");
  211. }
  212. #ifndef CARLA_OS_WIN
  213. else
  214. {
  215. carla_stderr("waitForClientFirstMessage() - read failed");
  216. CarlaString error(std::strerror(errno));
  217. carla_stderr("waitForClientFirstMessage() - read failed: %s", error.buffer());
  218. }
  219. #endif
  220. break;
  221. case 1: // read ok
  222. if (c == '\n')
  223. {
  224. // success
  225. return true;
  226. }
  227. else
  228. {
  229. carla_stderr("waitForClientFirstMessage() - read has wrong first char '%c'", c);
  230. }
  231. break;
  232. default: // ???
  233. carla_stderr("waitForClientFirstMessage() - read returned %i", int(ret));
  234. break;
  235. }
  236. break;
  237. }
  238. return false;
  239. }
  240. // -----------------------------------------------------------------------
  241. // waitForChildToStop / waitForProcessToStop
  242. #ifdef CARLA_OS_WIN
  243. static inline
  244. bool waitForProcessToStop(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  245. {
  246. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE, false);
  247. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  248. // TODO - this code is completly wrong...
  249. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  250. for (;;)
  251. {
  252. if (WaitForSingleObject(processInfo.hProcess, 0) == WAIT_OBJECT_0)
  253. return true;
  254. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  255. break;
  256. carla_msleep(5);
  257. }
  258. return false;
  259. }
  260. static inline
  261. void waitForProcessToStopOrKillIt(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  262. {
  263. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE,);
  264. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  265. if (! waitForProcessToStop(processInfo, timeOutMilliseconds))
  266. {
  267. carla_stderr("waitForProcessToStopOrKillIt() - process didn't stop, force termination");
  268. if (TerminateProcess(processInfo.hProcess, 0) != FALSE)
  269. {
  270. // wait for process to stop
  271. waitForProcessToStop(processInfo, timeOutMilliseconds);
  272. }
  273. }
  274. }
  275. #else
  276. static inline
  277. bool waitForChildToStop(const pid_t pid, const uint32_t timeOutMilliseconds) noexcept
  278. {
  279. CARLA_SAFE_ASSERT_RETURN(pid > 0, false);
  280. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  281. pid_t ret;
  282. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  283. for (;;)
  284. {
  285. try {
  286. ret = ::waitpid(pid, nullptr, WNOHANG);
  287. } CARLA_SAFE_EXCEPTION_BREAK("waitpid");
  288. switch (ret)
  289. {
  290. case -1:
  291. if (errno == ECHILD)
  292. {
  293. // success, child doesn't exist
  294. return true;
  295. }
  296. else
  297. {
  298. CarlaString error(std::strerror(errno));
  299. carla_stderr("waitForChildToStop() - waitpid failed: %s", error.buffer());
  300. return false;
  301. }
  302. break;
  303. case 0:
  304. if (juce::Time::getMillisecondCounter() < timeoutEnd)
  305. {
  306. carla_msleep(5);
  307. continue;
  308. }
  309. carla_stderr("waitForChildToStop() - timed out");
  310. break;
  311. default:
  312. if (ret == pid)
  313. {
  314. // success
  315. return true;
  316. }
  317. else
  318. {
  319. carla_stderr("waitForChildToStop() - got wrong pid %i (requested was %i)", int(ret), int(pid));
  320. return false;
  321. }
  322. }
  323. break;
  324. }
  325. return false;
  326. }
  327. static inline
  328. void waitForChildToStopOrKillIt(pid_t& pid, const uint32_t timeOutMilliseconds) noexcept
  329. {
  330. CARLA_SAFE_ASSERT_RETURN(pid > 0,);
  331. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  332. if (! waitForChildToStop(pid, timeOutMilliseconds))
  333. {
  334. carla_stderr("waitForChildToStopOrKillIt() - process didn't stop, force killing");
  335. if (::kill(pid, SIGKILL) != -1)
  336. {
  337. // wait for killing to take place
  338. waitForChildToStop(pid, timeOutMilliseconds);
  339. }
  340. else
  341. {
  342. CarlaString error(std::strerror(errno));
  343. carla_stderr("waitForChildToStopOrKillIt() - kill failed: %s", error.buffer());
  344. }
  345. }
  346. }
  347. #endif
  348. // -----------------------------------------------------------------------
  349. struct CarlaPipeCommon::PrivateData {
  350. // pipes
  351. #ifdef CARLA_OS_WIN
  352. PROCESS_INFORMATION processInfo;
  353. HANDLE cancelEvent;
  354. HANDLE pipeRecv;
  355. HANDLE pipeSend;
  356. #else
  357. pid_t pid;
  358. int pipeRecv;
  359. int pipeSend;
  360. #endif
  361. // read functions must only be called in context of idlePipe()
  362. bool isReading;
  363. // common write lock
  364. CarlaMutex writeLock;
  365. // temporary buffers for _readline()
  366. mutable char tmpBuf[0xff+1];
  367. mutable CarlaString tmpStr;
  368. PrivateData() noexcept
  369. #ifdef CARLA_OS_WIN
  370. : processInfo(),
  371. cancelEvent(INVALID_HANDLE_VALUE),
  372. #else
  373. : pid(-1),
  374. #endif
  375. pipeRecv(INVALID_PIPE_VALUE),
  376. pipeSend(INVALID_PIPE_VALUE),
  377. isReading(false),
  378. writeLock(),
  379. tmpBuf(),
  380. tmpStr()
  381. {
  382. #ifdef CARLA_OS_WIN
  383. carla_zeroStruct(processInfo);
  384. processInfo.hProcess = INVALID_HANDLE_VALUE;
  385. processInfo.hThread = INVALID_HANDLE_VALUE;
  386. try {
  387. cancelEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
  388. } CARLA_SAFE_EXCEPTION("CreateEvent");
  389. #endif
  390. carla_zeroChar(tmpBuf, 0xff+1);
  391. }
  392. ~PrivateData() noexcept
  393. {
  394. #ifdef CARLA_OS_WIN
  395. if (cancelEvent != INVALID_HANDLE_VALUE)
  396. {
  397. ::CloseHandle(cancelEvent);
  398. cancelEvent = INVALID_HANDLE_VALUE;
  399. }
  400. #endif
  401. }
  402. CARLA_DECLARE_NON_COPY_STRUCT(PrivateData)
  403. };
  404. // -----------------------------------------------------------------------
  405. CarlaPipeCommon::CarlaPipeCommon() noexcept
  406. : pData(new PrivateData()),
  407. leakDetector_CarlaPipeCommon()
  408. {
  409. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  410. }
  411. CarlaPipeCommon::~CarlaPipeCommon() /*noexcept*/
  412. {
  413. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  414. delete pData;
  415. }
  416. // -------------------------------------------------------------------
  417. bool CarlaPipeCommon::isPipeRunning() const noexcept
  418. {
  419. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE);
  420. }
  421. void CarlaPipeCommon::idlePipe(const bool onlyOnce) noexcept
  422. {
  423. const char* locale = nullptr;
  424. for (;;)
  425. {
  426. const char* const msg(_readline());
  427. if (msg == nullptr)
  428. break;
  429. if (locale == nullptr && ! onlyOnce)
  430. {
  431. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  432. ::setlocale(LC_NUMERIC, "C");
  433. }
  434. pData->isReading = true;
  435. try {
  436. msgReceived(msg);
  437. } CARLA_SAFE_EXCEPTION("msgReceived");
  438. pData->isReading = false;
  439. delete[] msg;
  440. if (onlyOnce)
  441. break;
  442. }
  443. if (locale != nullptr)
  444. {
  445. ::setlocale(LC_NUMERIC, locale);
  446. delete[] locale;
  447. }
  448. }
  449. // -------------------------------------------------------------------
  450. void CarlaPipeCommon::lockPipe() const noexcept
  451. {
  452. pData->writeLock.lock();
  453. }
  454. bool CarlaPipeCommon::tryLockPipe() const noexcept
  455. {
  456. return pData->writeLock.tryLock();
  457. }
  458. void CarlaPipeCommon::unlockPipe() const noexcept
  459. {
  460. pData->writeLock.unlock();
  461. }
  462. CarlaMutex& CarlaPipeCommon::getPipeLock() const noexcept
  463. {
  464. return pData->writeLock;
  465. }
  466. // -------------------------------------------------------------------
  467. bool CarlaPipeCommon::readNextLineAsBool(bool& value) const noexcept
  468. {
  469. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  470. if (const char* const msg = _readlineblock())
  471. {
  472. value = (std::strcmp(msg, "true") == 0);
  473. delete[] msg;
  474. return true;
  475. }
  476. return false;
  477. }
  478. bool CarlaPipeCommon::readNextLineAsByte(uint8_t& value) const noexcept
  479. {
  480. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  481. if (const char* const msg = _readlineblock())
  482. {
  483. int tmp = std::atoi(msg);
  484. delete[] msg;
  485. if (tmp >= 0 && tmp <= 0xFF)
  486. {
  487. value = static_cast<uint8_t>(tmp);
  488. return true;
  489. }
  490. }
  491. return false;
  492. }
  493. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) const noexcept
  494. {
  495. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  496. if (const char* const msg = _readlineblock())
  497. {
  498. value = std::atoi(msg);
  499. delete[] msg;
  500. return true;
  501. }
  502. return false;
  503. }
  504. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) const noexcept
  505. {
  506. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  507. if (const char* const msg = _readlineblock())
  508. {
  509. int32_t tmp = std::atoi(msg);
  510. delete[] msg;
  511. if (tmp >= 0)
  512. {
  513. value = static_cast<uint32_t>(tmp);
  514. return true;
  515. }
  516. }
  517. return false;
  518. }
  519. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) const noexcept
  520. {
  521. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  522. if (const char* const msg = _readlineblock())
  523. {
  524. value = std::atol(msg);
  525. delete[] msg;
  526. return true;
  527. }
  528. return false;
  529. }
  530. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) const noexcept
  531. {
  532. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  533. if (const char* const msg = _readlineblock())
  534. {
  535. int64_t tmp = std::atol(msg);
  536. delete[] msg;
  537. if (tmp >= 0)
  538. {
  539. value = static_cast<uint64_t>(tmp);
  540. return true;
  541. }
  542. }
  543. return false;
  544. }
  545. bool CarlaPipeCommon::readNextLineAsFloat(float& value) const noexcept
  546. {
  547. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  548. if (const char* const msg = _readlineblock())
  549. {
  550. value = static_cast<float>(std::atof(msg));
  551. delete[] msg;
  552. return true;
  553. }
  554. return false;
  555. }
  556. bool CarlaPipeCommon::readNextLineAsDouble(double& value) const noexcept
  557. {
  558. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  559. if (const char* const msg = _readlineblock())
  560. {
  561. value = std::atof(msg);
  562. delete[] msg;
  563. return true;
  564. }
  565. return false;
  566. }
  567. bool CarlaPipeCommon::readNextLineAsString(const char*& value) const noexcept
  568. {
  569. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  570. if (const char* const msg = _readlineblock())
  571. {
  572. value = msg;
  573. return true;
  574. }
  575. return false;
  576. }
  577. // -------------------------------------------------------------------
  578. // must be locked before calling
  579. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  580. {
  581. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  582. const std::size_t size(std::strlen(msg));
  583. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  584. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  585. return _writeMsgBuffer(msg, size);
  586. }
  587. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  588. {
  589. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  590. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  591. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  592. return _writeMsgBuffer(msg, size);
  593. }
  594. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  595. {
  596. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  597. const std::size_t size(std::strlen(msg));
  598. char fixedMsg[size+2];
  599. if (size > 0)
  600. {
  601. std::strcpy(fixedMsg, msg);
  602. for (std::size_t i=0; i<size; ++i)
  603. {
  604. if (fixedMsg[i] == '\n')
  605. fixedMsg[i] = '\r';
  606. }
  607. if (fixedMsg[size-1] == '\r')
  608. {
  609. fixedMsg[size-1] = '\n';
  610. fixedMsg[size] = '\0';
  611. fixedMsg[size+1] = '\0';
  612. }
  613. else
  614. {
  615. fixedMsg[size] = '\n';
  616. fixedMsg[size+1] = '\0';
  617. }
  618. }
  619. else
  620. {
  621. fixedMsg[0] = '\n';
  622. fixedMsg[1] = '\0';
  623. }
  624. return _writeMsgBuffer(fixedMsg, size+1);
  625. }
  626. bool CarlaPipeCommon::flushMessages() const noexcept
  627. {
  628. // TESTING remove later (replace with trylock scope)
  629. if (pData->writeLock.tryLock())
  630. {
  631. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  632. pData->writeLock.unlock();
  633. return false;
  634. }
  635. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  636. try {
  637. #ifdef CARLA_OS_WIN
  638. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  639. #else
  640. return (::fsync(pData->pipeSend) == 0);
  641. #endif
  642. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  643. }
  644. // -------------------------------------------------------------------
  645. void CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  646. {
  647. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0',);
  648. const CarlaMutexLocker cml(pData->writeLock);
  649. _writeMsgBuffer("error\n", 6);
  650. writeAndFixMessage(error);
  651. flushMessages();
  652. }
  653. void CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value) const noexcept
  654. {
  655. char tmpBuf[0xff+1];
  656. tmpBuf[0xff] = '\0';
  657. const CarlaMutexLocker cml(pData->writeLock);
  658. const ScopedLocale csl;
  659. _writeMsgBuffer("control\n", 8);
  660. {
  661. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  662. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  663. std::snprintf(tmpBuf, 0xff, "%f\n", value);
  664. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  665. }
  666. flushMessages();
  667. }
  668. void CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  669. {
  670. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  671. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  672. const CarlaMutexLocker cml(pData->writeLock);
  673. _writeMsgBuffer("configure\n", 10);
  674. {
  675. writeAndFixMessage(key);
  676. writeAndFixMessage(value);
  677. }
  678. flushMessages();
  679. }
  680. void CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  681. {
  682. char tmpBuf[0xff+1];
  683. tmpBuf[0xff] = '\0';
  684. const CarlaMutexLocker cml(pData->writeLock);
  685. _writeMsgBuffer("program\n", 8);
  686. {
  687. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  688. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  689. }
  690. flushMessages();
  691. }
  692. void CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  693. {
  694. char tmpBuf[0xff+1];
  695. tmpBuf[0xff] = '\0';
  696. const CarlaMutexLocker cml(pData->writeLock);
  697. _writeMsgBuffer("midiprogram\n", 8);
  698. {
  699. std::snprintf(tmpBuf, 0xff, "%i\n", bank);
  700. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  701. std::snprintf(tmpBuf, 0xff, "%i\n", program);
  702. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  703. }
  704. flushMessages();
  705. }
  706. void CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  707. {
  708. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  709. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  710. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE,);
  711. char tmpBuf[0xff+1];
  712. tmpBuf[0xff] = '\0';
  713. const CarlaMutexLocker cml(pData->writeLock);
  714. _writeMsgBuffer("note\n", 5);
  715. {
  716. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(onOff));
  717. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  718. std::snprintf(tmpBuf, 0xff, "%i\n", channel);
  719. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  720. std::snprintf(tmpBuf, 0xff, "%i\n", note);
  721. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  722. std::snprintf(tmpBuf, 0xff, "%i\n", velocity);
  723. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  724. }
  725. flushMessages();
  726. }
  727. void CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  728. {
  729. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  730. char tmpBuf[0xff+1];
  731. tmpBuf[0xff] = '\0';
  732. CarlaString base64atom(CarlaString::asBase64(atom, lv2_atom_total_size(atom)));
  733. const CarlaMutexLocker cml(pData->writeLock);
  734. _writeMsgBuffer("atom\n", 5);
  735. {
  736. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  737. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  738. std::snprintf(tmpBuf, 0xff, "%i\n", atom->size);
  739. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  740. writeAndFixMessage(base64atom.buffer());
  741. }
  742. flushMessages();
  743. }
  744. void CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  745. {
  746. CARLA_SAFE_ASSERT_RETURN(urid != 0,);
  747. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  748. char tmpBuf[0xff+1];
  749. tmpBuf[0xff] = '\0';
  750. const CarlaMutexLocker cml(pData->writeLock);
  751. _writeMsgBuffer("urid\n", 5);
  752. {
  753. std::snprintf(tmpBuf, 0xff, "%i\n", urid);
  754. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  755. writeAndFixMessage(uri);
  756. }
  757. flushMessages();
  758. }
  759. // -------------------------------------------------------------------
  760. // internal
  761. const char* CarlaPipeCommon::_readline() const noexcept
  762. {
  763. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  764. char c;
  765. char* ptr = pData->tmpBuf;
  766. ssize_t ret;
  767. pData->tmpStr.clear();
  768. for (int i=0; i < 0xff; ++i)
  769. {
  770. try {
  771. #ifdef CARLA_OS_WIN
  772. //ret = ::ReadFileBlock(pData->pipeRecv, &c, 1);
  773. ret = ::ReadFileNonBlock(pData->pipeRecv, pData->cancelEvent, &c, 1);
  774. #else
  775. ret = ::read(pData->pipeRecv, &c, 1);
  776. #endif
  777. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  778. if (ret == 1 && c != '\n')
  779. {
  780. if (c == '\r')
  781. c = '\n';
  782. *ptr++ = c;
  783. if (i+1 == 0xff)
  784. {
  785. i = 0;
  786. ptr = pData->tmpBuf;
  787. pData->tmpStr += pData->tmpBuf;
  788. }
  789. continue;
  790. }
  791. if (pData->tmpStr.isNotEmpty() || ptr != pData->tmpBuf || ret == 1)
  792. {
  793. if (ptr != pData->tmpBuf)
  794. {
  795. *ptr = '\0';
  796. pData->tmpStr += pData->tmpBuf;
  797. }
  798. try {
  799. return pData->tmpStr.dup();
  800. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  801. }
  802. break;
  803. }
  804. return nullptr;
  805. }
  806. const char* CarlaPipeCommon::_readlineblock(const uint32_t timeOutMilliseconds) const noexcept
  807. {
  808. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  809. for (;;)
  810. {
  811. if (const char* const msg = _readline())
  812. return msg;
  813. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  814. break;
  815. carla_msleep(5);
  816. }
  817. carla_stderr("readlineblock timed out");
  818. return nullptr;
  819. }
  820. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  821. {
  822. // TESTING remove later (replace with trylock scope)
  823. if (pData->writeLock.tryLock())
  824. {
  825. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  826. pData->writeLock.unlock();
  827. return false;
  828. }
  829. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  830. ssize_t ret;
  831. try {
  832. #ifdef CARLA_OS_WIN
  833. //ret = ::WriteFileBlock(pData->pipeSend, msg, size);
  834. ret = ::WriteFileNonBlock(pData->pipeSend, pData->cancelEvent, msg, size);
  835. #else
  836. ret = ::write(pData->pipeSend, msg, size);
  837. #endif
  838. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  839. return (ret == static_cast<ssize_t>(size));
  840. }
  841. // -----------------------------------------------------------------------
  842. CarlaPipeServer::CarlaPipeServer() noexcept
  843. : CarlaPipeCommon(),
  844. leakDetector_CarlaPipeServer()
  845. {
  846. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  847. }
  848. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  849. {
  850. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  851. stopPipeServer(5*1000);
  852. }
  853. uintptr_t CarlaPipeServer::getPID() const noexcept
  854. {
  855. #ifndef CARLA_OS_WIN
  856. return static_cast<uintptr_t>(pData->pid);
  857. #else
  858. return 0;
  859. #endif
  860. }
  861. // -----------------------------------------------------------------------
  862. bool CarlaPipeServer::startPipeServer(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  863. {
  864. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  865. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  866. #ifdef CARLA_OS_WIN
  867. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  868. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  869. #else
  870. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  871. #endif
  872. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  873. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  874. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  875. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  876. const CarlaMutexLocker cml(pData->writeLock);
  877. //----------------------------------------------------------------
  878. // create pipes
  879. #ifdef CARLA_OS_WIN
  880. HANDLE pipe1[2]; // read by server, written by client
  881. HANDLE pipe2[2]; // read by client, written by server
  882. SECURITY_ATTRIBUTES sa;
  883. carla_zeroStruct(sa);
  884. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  885. sa.bInheritHandle = TRUE;
  886. std::srand(static_cast<uint>(std::time(nullptr)));
  887. char strBuf[0xff+1];
  888. strBuf[0xff] = '\0';
  889. static ulong sCounter = 0;
  890. ++sCounter;
  891. const int randint = std::rand();
  892. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  893. pipe1[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 300, &sa);
  894. pipe1[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  895. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  896. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 300, &sa);
  897. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  898. #if 0
  899. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  900. pipe1[1] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE|PIPE_NOWAIT, 1, 4096, 4096, 120*1000, &sa);
  901. pipe1[0] = ::CreateFileA(strBuf, GENERIC_READ, 0x0, &sa, OPEN_EXISTING, 0x0, nullptr);
  902. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  903. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE|PIPE_NOWAIT, 1, 4096, 4096, 120*1000, &sa); // NB
  904. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, 0x0, nullptr);
  905. #endif
  906. if (pipe1[0] == INVALID_HANDLE_VALUE || pipe1[1] == INVALID_HANDLE_VALUE || pipe2[0] == INVALID_HANDLE_VALUE || pipe2[1] == INVALID_HANDLE_VALUE)
  907. {
  908. if (pipe1[0] != INVALID_HANDLE_VALUE) {
  909. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  910. }
  911. if (pipe1[1] != INVALID_HANDLE_VALUE) {
  912. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  913. }
  914. if (pipe2[0] != INVALID_HANDLE_VALUE) {
  915. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  916. }
  917. if (pipe2[1] != INVALID_HANDLE_VALUE) {
  918. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  919. }
  920. fail("pipe creation failed");
  921. return false;
  922. }
  923. HANDLE pipeRecvServer = pipe1[0];
  924. HANDLE pipeRecvClient = pipe2[0];
  925. HANDLE pipeSendClient = pipe1[1];
  926. HANDLE pipeSendServer = pipe2[1];
  927. #else
  928. int pipe1[2]; // read by server, written by client
  929. int pipe2[2]; // read by client, written by server
  930. if (::pipe(pipe1) != 0)
  931. {
  932. fail("pipe1 creation failed");
  933. return false;
  934. }
  935. if (::pipe(pipe2) != 0)
  936. {
  937. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  938. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  939. fail("pipe2 creation failed");
  940. return false;
  941. }
  942. int pipeRecvServer = pipe1[0];
  943. int pipeRecvClient = pipe2[0];
  944. int pipeSendClient = pipe1[1];
  945. int pipeSendServer = pipe2[1];
  946. #endif
  947. //----------------------------------------------------------------
  948. // set arguments
  949. const char* argv[8];
  950. //----------------------------------------------------------------
  951. // argv[0] => filename
  952. argv[0] = filename;
  953. //----------------------------------------------------------------
  954. // argv[1-2] => args
  955. argv[1] = arg1;
  956. argv[2] = arg2;
  957. //----------------------------------------------------------------
  958. // argv[3-6] => pipes
  959. char pipeRecvServerStr[100+1];
  960. char pipeRecvClientStr[100+1];
  961. char pipeSendServerStr[100+1];
  962. char pipeSendClientStr[100+1];
  963. std::snprintf(pipeRecvServerStr, 100, P_INTPTR, (intptr_t)pipeRecvServer); // pipe1[0]
  964. std::snprintf(pipeRecvClientStr, 100, P_INTPTR, (intptr_t)pipeRecvClient); // pipe2[0]
  965. std::snprintf(pipeSendServerStr, 100, P_INTPTR, (intptr_t)pipeSendServer); // pipe2[1]
  966. std::snprintf(pipeSendClientStr, 100, P_INTPTR, (intptr_t)pipeSendClient); // pipe1[1]
  967. pipeRecvServerStr[100] = '\0';
  968. pipeRecvClientStr[100] = '\0';
  969. pipeSendServerStr[100] = '\0';
  970. pipeSendClientStr[100] = '\0';
  971. argv[3] = pipeRecvServerStr; // pipe1[0] close READ
  972. argv[4] = pipeRecvClientStr; // pipe2[0] READ
  973. argv[5] = pipeSendServerStr; // pipe2[1] close SEND
  974. argv[6] = pipeSendClientStr; // pipe1[1] SEND
  975. //----------------------------------------------------------------
  976. // argv[7] => null
  977. argv[7] = nullptr;
  978. //----------------------------------------------------------------
  979. // start process
  980. #ifdef CARLA_OS_WIN
  981. if (! startProcess(argv, &pData->processInfo))
  982. {
  983. carla_zeroStruct(pData->processInfo);
  984. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  985. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  986. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  987. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  988. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  989. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  990. fail("startProcess() failed");
  991. return false;
  992. }
  993. // just to make sure
  994. CARLA_SAFE_ASSERT(pData->processInfo.hThread != nullptr);
  995. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != nullptr);
  996. #else
  997. if (! startProcess(argv, pData->pid))
  998. {
  999. pData->pid = -1;
  1000. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1001. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1002. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1003. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1004. fail("startProcess() failed");
  1005. return false;
  1006. }
  1007. #endif
  1008. //----------------------------------------------------------------
  1009. // close duplicated handles used by the client
  1010. #ifdef CARLA_OS_WIN
  1011. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  1012. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  1013. #else
  1014. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1015. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1016. #endif
  1017. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  1018. #ifndef CARLA_OS_WIN
  1019. //----------------------------------------------------------------
  1020. // set non-block reading
  1021. int ret = 0;
  1022. try {
  1023. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  1024. } catch (...) {
  1025. ret = -1;
  1026. fail("failed to set pipe as non-block");
  1027. }
  1028. #endif
  1029. //----------------------------------------------------------------
  1030. // wait for client to say something
  1031. #ifdef CARLA_OS_WIN
  1032. struct { HANDLE handle; HANDLE cancel; } pipe;
  1033. pipe.handle = pipeRecvClient;
  1034. pipe.cancel = pData->cancelEvent;
  1035. if ( waitForClientFirstMessage(pipe, 10*1000 /* 10 secs */))
  1036. #else
  1037. if (ret != -1 && waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  1038. #endif
  1039. {
  1040. pData->pipeRecv = pipeRecvClient;
  1041. pData->pipeSend = pipeSendClient;
  1042. carla_stdout("ALL OK!");
  1043. return true;
  1044. }
  1045. //----------------------------------------------------------------
  1046. // failed to set non-block or get first child message, cannot continue
  1047. #ifdef CARLA_OS_WIN
  1048. if (TerminateProcess(pData->processInfo.hProcess, 0) != FALSE)
  1049. {
  1050. // wait for process to stop
  1051. waitForProcessToStop(pData->processInfo, 2*1000);
  1052. }
  1053. // clear pData->processInfo
  1054. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1055. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1056. carla_zeroStruct(pData->processInfo);
  1057. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1058. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1059. #else
  1060. if (::kill(pData->pid, SIGKILL) != -1)
  1061. {
  1062. // wait for killing to take place
  1063. waitForChildToStop(pData->pid, 2*1000);
  1064. }
  1065. pData->pid = -1;
  1066. #endif
  1067. //----------------------------------------------------------------
  1068. // close pipes
  1069. #ifdef CARLA_OS_WIN
  1070. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  1071. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  1072. #else
  1073. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1074. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1075. #endif
  1076. return false;
  1077. }
  1078. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1079. {
  1080. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1081. #ifdef CARLA_OS_WIN
  1082. if (pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1083. {
  1084. const CarlaMutexLocker cml(pData->writeLock);
  1085. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1086. _writeMsgBuffer("quit\n", 5);
  1087. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  1088. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1089. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1090. carla_zeroStruct(pData->processInfo);
  1091. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1092. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1093. }
  1094. #else
  1095. if (pData->pid != -1)
  1096. {
  1097. const CarlaMutexLocker cml(pData->writeLock);
  1098. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1099. _writeMsgBuffer("quit\n", 5);
  1100. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1101. pData->pid = -1;
  1102. }
  1103. #endif
  1104. closePipeServer();
  1105. }
  1106. void CarlaPipeServer::closePipeServer() noexcept
  1107. {
  1108. carla_debug("CarlaPipeServer::closePipeServer()");
  1109. const CarlaMutexLocker cml(pData->writeLock);
  1110. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1111. {
  1112. #ifdef CARLA_OS_WIN
  1113. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1114. #else
  1115. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1116. #endif
  1117. pData->pipeRecv = INVALID_PIPE_VALUE;
  1118. }
  1119. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1120. {
  1121. #ifdef CARLA_OS_WIN
  1122. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1123. #else
  1124. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1125. #endif
  1126. pData->pipeSend = INVALID_PIPE_VALUE;
  1127. }
  1128. }
  1129. void CarlaPipeServer::writeShowMessage() const noexcept
  1130. {
  1131. const CarlaMutexLocker cml(pData->writeLock);
  1132. _writeMsgBuffer("show\n", 5);
  1133. flushMessages();
  1134. }
  1135. void CarlaPipeServer::writeFocusMessage() const noexcept
  1136. {
  1137. const CarlaMutexLocker cml(pData->writeLock);
  1138. _writeMsgBuffer("focus\n", 6);
  1139. flushMessages();
  1140. }
  1141. void CarlaPipeServer::writeHideMessage() const noexcept
  1142. {
  1143. const CarlaMutexLocker cml(pData->writeLock);
  1144. _writeMsgBuffer("show\n", 5);
  1145. flushMessages();
  1146. }
  1147. // -----------------------------------------------------------------------
  1148. CarlaPipeClient::CarlaPipeClient() noexcept
  1149. : CarlaPipeCommon(),
  1150. leakDetector_CarlaPipeClient()
  1151. {
  1152. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1153. }
  1154. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1155. {
  1156. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1157. closePipeClient();
  1158. }
  1159. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1160. {
  1161. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1162. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1163. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1164. const CarlaMutexLocker cml(pData->writeLock);
  1165. //----------------------------------------------------------------
  1166. // read arguments
  1167. #ifdef CARLA_OS_WIN
  1168. HANDLE pipeRecvServer = (HANDLE)std::atoll(argv[3]); // READ
  1169. HANDLE pipeRecvClient = (HANDLE)std::atoll(argv[4]);
  1170. HANDLE pipeSendServer = (HANDLE)std::atoll(argv[5]); // SEND
  1171. HANDLE pipeSendClient = (HANDLE)std::atoll(argv[6]);
  1172. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1173. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient != INVALID_HANDLE_VALUE, false);
  1174. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1175. CARLA_SAFE_ASSERT_RETURN(pipeSendClient != INVALID_HANDLE_VALUE, false);
  1176. #else
  1177. int pipeRecvServer = std::atoi(argv[3]); // READ
  1178. int pipeRecvClient = std::atoi(argv[4]);
  1179. int pipeSendServer = std::atoi(argv[5]); // SEND
  1180. int pipeSendClient = std::atoi(argv[6]);
  1181. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1182. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1183. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1184. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1185. #endif
  1186. //----------------------------------------------------------------
  1187. // close duplicated handles used by the client
  1188. #ifdef CARLA_OS_WIN
  1189. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1190. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1191. #else
  1192. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1193. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1194. #endif
  1195. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  1196. #ifndef CARLA_OS_WIN
  1197. //----------------------------------------------------------------
  1198. // set non-block reading
  1199. int ret = 0;
  1200. try {
  1201. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  1202. } catch (...) {
  1203. ret = -1;
  1204. }
  1205. CARLA_SAFE_ASSERT_RETURN(ret != -1, false);
  1206. #endif
  1207. //----------------------------------------------------------------
  1208. // done
  1209. pData->pipeRecv = pipeRecvServer;
  1210. pData->pipeSend = pipeSendServer;
  1211. writeMessage("\n", 1);
  1212. flushMessages();
  1213. return true;
  1214. }
  1215. void CarlaPipeClient::closePipeClient() noexcept
  1216. {
  1217. carla_debug("CarlaPipeClient::closePipeClient()");
  1218. const CarlaMutexLocker cml(pData->writeLock);
  1219. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1220. {
  1221. #ifdef CARLA_OS_WIN
  1222. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1223. #else
  1224. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1225. #endif
  1226. pData->pipeRecv = INVALID_PIPE_VALUE;
  1227. }
  1228. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1229. {
  1230. #ifdef CARLA_OS_WIN
  1231. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1232. #else
  1233. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1234. #endif
  1235. pData->pipeSend = INVALID_PIPE_VALUE;
  1236. }
  1237. }
  1238. // -----------------------------------------------------------------------
  1239. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1240. : fKey(nullptr),
  1241. fOrigValue(nullptr)
  1242. {
  1243. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1244. fKey = carla_strdup_safe(key);
  1245. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1246. if (const char* const origValue = std::getenv(key))
  1247. {
  1248. fOrigValue = carla_strdup_safe(origValue);
  1249. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1250. }
  1251. if (value != nullptr)
  1252. carla_setenv(key, value);
  1253. else if (fOrigValue != nullptr)
  1254. carla_unsetenv(key);
  1255. }
  1256. ScopedEnvVar::~ScopedEnvVar() noexcept
  1257. {
  1258. bool hasOrigValue = false;
  1259. if (fOrigValue != nullptr)
  1260. {
  1261. hasOrigValue = true;
  1262. carla_setenv(fKey, fOrigValue);
  1263. delete[] fOrigValue;
  1264. fOrigValue = nullptr;
  1265. }
  1266. if (fKey != nullptr)
  1267. {
  1268. if (! hasOrigValue)
  1269. carla_unsetenv(fKey);
  1270. delete[] fKey;
  1271. fKey = nullptr;
  1272. }
  1273. }
  1274. // -----------------------------------------------------------------------
  1275. ScopedLocale::ScopedLocale() noexcept
  1276. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1277. {
  1278. ::setlocale(LC_NUMERIC, "C");
  1279. }
  1280. ScopedLocale::~ScopedLocale() noexcept
  1281. {
  1282. if (fLocale != nullptr)
  1283. {
  1284. ::setlocale(LC_NUMERIC, fLocale);
  1285. delete[] fLocale;
  1286. }
  1287. }
  1288. // -----------------------------------------------------------------------
  1289. #undef INVALID_PIPE_VALUE