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.

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