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.

1666 lines
46KB

  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_zeroChar(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. leakDetector_CarlaPipeCommon()
  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. CarlaString base64atom(CarlaString::asBase64(atom, lv2_atom_total_size(atom)));
  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", atom->size);
  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 == 1 && c != '\n')
  816. {
  817. if (c == '\r')
  818. c = '\n';
  819. *ptr++ = c;
  820. if (i+1 == 0xff)
  821. {
  822. i = 0;
  823. ptr = pData->tmpBuf;
  824. pData->tmpStr += pData->tmpBuf;
  825. }
  826. continue;
  827. }
  828. if (pData->tmpStr.isNotEmpty() || ptr != pData->tmpBuf || ret == 1)
  829. {
  830. if (ptr != pData->tmpBuf)
  831. {
  832. *ptr = '\0';
  833. pData->tmpStr += pData->tmpBuf;
  834. }
  835. try {
  836. return pData->tmpStr.dup();
  837. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  838. }
  839. break;
  840. }
  841. return 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. leakDetector_CarlaPipeServer()
  882. {
  883. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  884. }
  885. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  886. {
  887. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  888. stopPipeServer(5*1000);
  889. }
  890. uintptr_t CarlaPipeServer::getPID() const noexcept
  891. {
  892. #ifndef CARLA_OS_WIN
  893. return static_cast<uintptr_t>(pData->pid);
  894. #else
  895. return 0;
  896. #endif
  897. }
  898. // -----------------------------------------------------------------------
  899. bool CarlaPipeServer::startPipeServer(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  900. {
  901. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  902. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  903. #ifdef CARLA_OS_WIN
  904. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  905. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  906. #else
  907. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  908. #endif
  909. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  910. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  911. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  912. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  913. const CarlaMutexLocker cml(pData->writeLock);
  914. //----------------------------------------------------------------
  915. // create pipes
  916. #ifdef CARLA_OS_WIN
  917. HANDLE pipe1[2]; // read by server, written by client
  918. HANDLE pipe2[2]; // read by client, written by server
  919. SECURITY_ATTRIBUTES sa;
  920. carla_zeroStruct(sa);
  921. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  922. sa.bInheritHandle = TRUE;
  923. std::srand(static_cast<uint>(std::time(nullptr)));
  924. char strBuf[0xff+1];
  925. strBuf[0xff] = '\0';
  926. static ulong sCounter = 0;
  927. ++sCounter;
  928. const int randint = std::rand();
  929. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  930. pipe1[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 300, &sa);
  931. pipe1[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  932. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  933. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 300, &sa);
  934. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  935. #if 0
  936. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  937. pipe1[1] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE|PIPE_NOWAIT, 1, 4096, 4096, 120*1000, &sa);
  938. pipe1[0] = ::CreateFileA(strBuf, GENERIC_READ, 0x0, &sa, OPEN_EXISTING, 0x0, nullptr);
  939. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  940. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE|PIPE_NOWAIT, 1, 4096, 4096, 120*1000, &sa); // NB
  941. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, 0x0, nullptr);
  942. #endif
  943. if (pipe1[0] == INVALID_HANDLE_VALUE || pipe1[1] == INVALID_HANDLE_VALUE || pipe2[0] == INVALID_HANDLE_VALUE || pipe2[1] == INVALID_HANDLE_VALUE)
  944. {
  945. if (pipe1[0] != INVALID_HANDLE_VALUE) {
  946. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  947. }
  948. if (pipe1[1] != INVALID_HANDLE_VALUE) {
  949. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  950. }
  951. if (pipe2[0] != INVALID_HANDLE_VALUE) {
  952. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  953. }
  954. if (pipe2[1] != INVALID_HANDLE_VALUE) {
  955. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  956. }
  957. fail("pipe creation failed");
  958. return false;
  959. }
  960. HANDLE pipeRecvServer = pipe1[0];
  961. HANDLE pipeRecvClient = pipe2[0];
  962. HANDLE pipeSendClient = pipe1[1];
  963. HANDLE pipeSendServer = pipe2[1];
  964. #else
  965. int pipe1[2]; // read by server, written by client
  966. int pipe2[2]; // read by client, written by server
  967. if (::pipe(pipe1) != 0)
  968. {
  969. fail("pipe1 creation failed");
  970. return false;
  971. }
  972. if (::pipe(pipe2) != 0)
  973. {
  974. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  975. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  976. fail("pipe2 creation failed");
  977. return false;
  978. }
  979. int pipeRecvServer = pipe1[0];
  980. int pipeRecvClient = pipe2[0];
  981. int pipeSendClient = pipe1[1];
  982. int pipeSendServer = pipe2[1];
  983. #endif
  984. //----------------------------------------------------------------
  985. // set arguments
  986. const char* argv[8];
  987. //----------------------------------------------------------------
  988. // argv[0] => filename
  989. argv[0] = filename;
  990. //----------------------------------------------------------------
  991. // argv[1-2] => args
  992. argv[1] = arg1;
  993. argv[2] = arg2;
  994. //----------------------------------------------------------------
  995. // argv[3-6] => pipes
  996. char pipeRecvServerStr[100+1];
  997. char pipeRecvClientStr[100+1];
  998. char pipeSendServerStr[100+1];
  999. char pipeSendClientStr[100+1];
  1000. std::snprintf(pipeRecvServerStr, 100, P_INTPTR, (intptr_t)pipeRecvServer); // pipe1[0]
  1001. std::snprintf(pipeRecvClientStr, 100, P_INTPTR, (intptr_t)pipeRecvClient); // pipe2[0]
  1002. std::snprintf(pipeSendServerStr, 100, P_INTPTR, (intptr_t)pipeSendServer); // pipe2[1]
  1003. std::snprintf(pipeSendClientStr, 100, P_INTPTR, (intptr_t)pipeSendClient); // pipe1[1]
  1004. pipeRecvServerStr[100] = '\0';
  1005. pipeRecvClientStr[100] = '\0';
  1006. pipeSendServerStr[100] = '\0';
  1007. pipeSendClientStr[100] = '\0';
  1008. argv[3] = pipeRecvServerStr; // pipe1[0] close READ
  1009. argv[4] = pipeRecvClientStr; // pipe2[0] READ
  1010. argv[5] = pipeSendServerStr; // pipe2[1] close SEND
  1011. argv[6] = pipeSendClientStr; // pipe1[1] SEND
  1012. //----------------------------------------------------------------
  1013. // argv[7] => null
  1014. argv[7] = nullptr;
  1015. //----------------------------------------------------------------
  1016. // start process
  1017. #ifdef CARLA_OS_WIN
  1018. if (! startProcess(argv, &pData->processInfo))
  1019. {
  1020. carla_zeroStruct(pData->processInfo);
  1021. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1022. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1023. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  1024. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  1025. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  1026. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  1027. fail("startProcess() failed");
  1028. return false;
  1029. }
  1030. // just to make sure
  1031. CARLA_SAFE_ASSERT(pData->processInfo.hThread != nullptr);
  1032. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != nullptr);
  1033. #else
  1034. if (! startProcess(argv, pData->pid))
  1035. {
  1036. pData->pid = -1;
  1037. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1038. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1039. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1040. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1041. fail("startProcess() failed");
  1042. return false;
  1043. }
  1044. #endif
  1045. //----------------------------------------------------------------
  1046. // close duplicated handles used by the client
  1047. #ifdef CARLA_OS_WIN
  1048. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  1049. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  1050. #else
  1051. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1052. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1053. #endif
  1054. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  1055. #ifndef CARLA_OS_WIN
  1056. //----------------------------------------------------------------
  1057. // set non-block reading
  1058. int ret = 0;
  1059. try {
  1060. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  1061. } catch (...) {
  1062. ret = -1;
  1063. fail("failed to set pipe as non-block");
  1064. }
  1065. #endif
  1066. //----------------------------------------------------------------
  1067. // wait for client to say something
  1068. #ifdef CARLA_OS_WIN
  1069. struct { HANDLE handle; HANDLE cancel; } pipe;
  1070. pipe.handle = pipeRecvClient;
  1071. pipe.cancel = pData->cancelEvent;
  1072. if ( waitForClientFirstMessage(pipe, 10*1000 /* 10 secs */))
  1073. #else
  1074. if (ret != -1 && waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  1075. #endif
  1076. {
  1077. pData->pipeRecv = pipeRecvClient;
  1078. pData->pipeSend = pipeSendClient;
  1079. carla_stdout("ALL OK!");
  1080. return true;
  1081. }
  1082. //----------------------------------------------------------------
  1083. // failed to set non-block or get first child message, cannot continue
  1084. #ifdef CARLA_OS_WIN
  1085. if (TerminateProcess(pData->processInfo.hProcess, 0) != FALSE)
  1086. {
  1087. // wait for process to stop
  1088. waitForProcessToStop(pData->processInfo, 2*1000);
  1089. }
  1090. // clear pData->processInfo
  1091. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1092. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1093. carla_zeroStruct(pData->processInfo);
  1094. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1095. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1096. #else
  1097. if (::kill(pData->pid, SIGKILL) != -1)
  1098. {
  1099. // wait for killing to take place
  1100. waitForChildToStop(pData->pid, 2*1000, false);
  1101. }
  1102. pData->pid = -1;
  1103. #endif
  1104. //----------------------------------------------------------------
  1105. // close pipes
  1106. #ifdef CARLA_OS_WIN
  1107. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  1108. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  1109. #else
  1110. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1111. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1112. #endif
  1113. return false;
  1114. }
  1115. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1116. {
  1117. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1118. #ifdef CARLA_OS_WIN
  1119. if (pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1120. {
  1121. const CarlaMutexLocker cml(pData->writeLock);
  1122. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1123. _writeMsgBuffer("quit\n", 5);
  1124. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  1125. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1126. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1127. carla_zeroStruct(pData->processInfo);
  1128. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1129. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1130. }
  1131. #else
  1132. if (pData->pid != -1)
  1133. {
  1134. const CarlaMutexLocker cml(pData->writeLock);
  1135. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1136. _writeMsgBuffer("quit\n", 5);
  1137. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1138. pData->pid = -1;
  1139. }
  1140. #endif
  1141. closePipeServer();
  1142. }
  1143. void CarlaPipeServer::closePipeServer() noexcept
  1144. {
  1145. carla_debug("CarlaPipeServer::closePipeServer()");
  1146. const CarlaMutexLocker cml(pData->writeLock);
  1147. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1148. {
  1149. #ifdef CARLA_OS_WIN
  1150. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1151. #else
  1152. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1153. #endif
  1154. pData->pipeRecv = INVALID_PIPE_VALUE;
  1155. }
  1156. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1157. {
  1158. #ifdef CARLA_OS_WIN
  1159. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1160. #else
  1161. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1162. #endif
  1163. pData->pipeSend = INVALID_PIPE_VALUE;
  1164. }
  1165. }
  1166. void CarlaPipeServer::writeShowMessage() const noexcept
  1167. {
  1168. const CarlaMutexLocker cml(pData->writeLock);
  1169. _writeMsgBuffer("show\n", 5);
  1170. flushMessages();
  1171. }
  1172. void CarlaPipeServer::writeFocusMessage() const noexcept
  1173. {
  1174. const CarlaMutexLocker cml(pData->writeLock);
  1175. _writeMsgBuffer("focus\n", 6);
  1176. flushMessages();
  1177. }
  1178. void CarlaPipeServer::writeHideMessage() const noexcept
  1179. {
  1180. const CarlaMutexLocker cml(pData->writeLock);
  1181. _writeMsgBuffer("show\n", 5);
  1182. flushMessages();
  1183. }
  1184. // -----------------------------------------------------------------------
  1185. CarlaPipeClient::CarlaPipeClient() noexcept
  1186. : CarlaPipeCommon(),
  1187. leakDetector_CarlaPipeClient()
  1188. {
  1189. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1190. }
  1191. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1192. {
  1193. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1194. closePipeClient();
  1195. }
  1196. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1197. {
  1198. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1199. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1200. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1201. const CarlaMutexLocker cml(pData->writeLock);
  1202. //----------------------------------------------------------------
  1203. // read arguments
  1204. #ifdef CARLA_OS_WIN
  1205. HANDLE pipeRecvServer = (HANDLE)std::atoll(argv[3]); // READ
  1206. HANDLE pipeRecvClient = (HANDLE)std::atoll(argv[4]);
  1207. HANDLE pipeSendServer = (HANDLE)std::atoll(argv[5]); // SEND
  1208. HANDLE pipeSendClient = (HANDLE)std::atoll(argv[6]);
  1209. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1210. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient != INVALID_HANDLE_VALUE, false);
  1211. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1212. CARLA_SAFE_ASSERT_RETURN(pipeSendClient != INVALID_HANDLE_VALUE, false);
  1213. #else
  1214. int pipeRecvServer = std::atoi(argv[3]); // READ
  1215. int pipeRecvClient = std::atoi(argv[4]);
  1216. int pipeSendServer = std::atoi(argv[5]); // SEND
  1217. int pipeSendClient = std::atoi(argv[6]);
  1218. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1219. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1220. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1221. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1222. #endif
  1223. //----------------------------------------------------------------
  1224. // close duplicated handles used by the client
  1225. #ifdef CARLA_OS_WIN
  1226. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1227. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1228. #else
  1229. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1230. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1231. #endif
  1232. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  1233. #ifndef CARLA_OS_WIN
  1234. //----------------------------------------------------------------
  1235. // set non-block reading
  1236. int ret = 0;
  1237. try {
  1238. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  1239. } catch (...) {
  1240. ret = -1;
  1241. }
  1242. CARLA_SAFE_ASSERT_RETURN(ret != -1, false);
  1243. #endif
  1244. //----------------------------------------------------------------
  1245. // done
  1246. pData->pipeRecv = pipeRecvServer;
  1247. pData->pipeSend = pipeSendServer;
  1248. writeMessage("\n", 1);
  1249. flushMessages();
  1250. return true;
  1251. }
  1252. void CarlaPipeClient::closePipeClient() noexcept
  1253. {
  1254. carla_debug("CarlaPipeClient::closePipeClient()");
  1255. const CarlaMutexLocker cml(pData->writeLock);
  1256. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1257. {
  1258. #ifdef CARLA_OS_WIN
  1259. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1260. #else
  1261. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1262. #endif
  1263. pData->pipeRecv = INVALID_PIPE_VALUE;
  1264. }
  1265. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1266. {
  1267. #ifdef CARLA_OS_WIN
  1268. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1269. #else
  1270. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1271. #endif
  1272. pData->pipeSend = INVALID_PIPE_VALUE;
  1273. }
  1274. }
  1275. // -----------------------------------------------------------------------
  1276. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1277. : fKey(nullptr),
  1278. fOrigValue(nullptr)
  1279. {
  1280. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1281. fKey = carla_strdup_safe(key);
  1282. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1283. if (const char* const origValue = std::getenv(key))
  1284. {
  1285. fOrigValue = carla_strdup_safe(origValue);
  1286. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1287. }
  1288. if (value != nullptr)
  1289. carla_setenv(key, value);
  1290. else if (fOrigValue != nullptr)
  1291. carla_unsetenv(key);
  1292. }
  1293. ScopedEnvVar::~ScopedEnvVar() noexcept
  1294. {
  1295. bool hasOrigValue = false;
  1296. if (fOrigValue != nullptr)
  1297. {
  1298. hasOrigValue = true;
  1299. carla_setenv(fKey, fOrigValue);
  1300. delete[] fOrigValue;
  1301. fOrigValue = nullptr;
  1302. }
  1303. if (fKey != nullptr)
  1304. {
  1305. if (! hasOrigValue)
  1306. carla_unsetenv(fKey);
  1307. delete[] fKey;
  1308. fKey = nullptr;
  1309. }
  1310. }
  1311. // -----------------------------------------------------------------------
  1312. ScopedLocale::ScopedLocale() noexcept
  1313. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1314. {
  1315. ::setlocale(LC_NUMERIC, "C");
  1316. }
  1317. ScopedLocale::~ScopedLocale() noexcept
  1318. {
  1319. if (fLocale != nullptr)
  1320. {
  1321. ::setlocale(LC_NUMERIC, fLocale);
  1322. delete[] fLocale;
  1323. }
  1324. }
  1325. // -----------------------------------------------------------------------
  1326. #undef INVALID_PIPE_VALUE