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.

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