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.

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