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.

1579 lines
42KB

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