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.

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