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.

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