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.

1663 lines
45KB

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