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.

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