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.

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