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.

1601 lines
43KB

  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. // print error only once
  374. bool lastMessageFailed;
  375. // common write lock
  376. CarlaMutex writeLock;
  377. // temporary buffers for _readline()
  378. mutable char tmpBuf[0xff+1];
  379. mutable CarlaString tmpStr;
  380. PrivateData() noexcept
  381. #ifdef CARLA_OS_WIN
  382. : processInfo(),
  383. #else
  384. : pid(-1),
  385. #endif
  386. pipeRecv(INVALID_PIPE_VALUE),
  387. pipeSend(INVALID_PIPE_VALUE),
  388. isReading(false),
  389. lastMessageFailed(false),
  390. writeLock(),
  391. tmpBuf(),
  392. tmpStr()
  393. {
  394. #ifdef CARLA_OS_WIN
  395. carla_zeroStruct(processInfo);
  396. processInfo.hProcess = INVALID_HANDLE_VALUE;
  397. processInfo.hThread = INVALID_HANDLE_VALUE;
  398. #endif
  399. carla_zeroChars(tmpBuf, 0xff+1);
  400. }
  401. CARLA_DECLARE_NON_COPY_STRUCT(PrivateData)
  402. };
  403. // -----------------------------------------------------------------------
  404. CarlaPipeCommon::CarlaPipeCommon() noexcept
  405. : pData(new PrivateData())
  406. {
  407. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  408. }
  409. CarlaPipeCommon::~CarlaPipeCommon() /*noexcept*/
  410. {
  411. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  412. delete pData;
  413. }
  414. // -------------------------------------------------------------------
  415. bool CarlaPipeCommon::isPipeRunning() const noexcept
  416. {
  417. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE);
  418. }
  419. void CarlaPipeCommon::idlePipe(const bool onlyOnce) noexcept
  420. {
  421. const char* locale = nullptr;
  422. for (;;)
  423. {
  424. const char* const msg(_readline());
  425. if (msg == nullptr)
  426. break;
  427. if (locale == nullptr && ! onlyOnce)
  428. {
  429. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  430. ::setlocale(LC_NUMERIC, "C");
  431. }
  432. pData->isReading = true;
  433. try {
  434. msgReceived(msg);
  435. } CARLA_SAFE_EXCEPTION("msgReceived");
  436. pData->isReading = false;
  437. delete[] msg;
  438. if (onlyOnce)
  439. break;
  440. }
  441. if (locale != nullptr)
  442. {
  443. ::setlocale(LC_NUMERIC, locale);
  444. delete[] locale;
  445. }
  446. }
  447. // -------------------------------------------------------------------
  448. void CarlaPipeCommon::lockPipe() const noexcept
  449. {
  450. pData->writeLock.lock();
  451. }
  452. bool CarlaPipeCommon::tryLockPipe() const noexcept
  453. {
  454. return pData->writeLock.tryLock();
  455. }
  456. void CarlaPipeCommon::unlockPipe() const noexcept
  457. {
  458. pData->writeLock.unlock();
  459. }
  460. CarlaMutex& CarlaPipeCommon::getPipeLock() const noexcept
  461. {
  462. return pData->writeLock;
  463. }
  464. // -------------------------------------------------------------------
  465. bool CarlaPipeCommon::readNextLineAsBool(bool& value) const noexcept
  466. {
  467. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  468. if (const char* const msg = _readlineblock())
  469. {
  470. value = (std::strcmp(msg, "true") == 0);
  471. delete[] msg;
  472. return true;
  473. }
  474. return false;
  475. }
  476. bool CarlaPipeCommon::readNextLineAsByte(uint8_t& value) const noexcept
  477. {
  478. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  479. if (const char* const msg = _readlineblock())
  480. {
  481. int tmp = std::atoi(msg);
  482. delete[] msg;
  483. if (tmp >= 0 && tmp <= 0xFF)
  484. {
  485. value = static_cast<uint8_t>(tmp);
  486. return true;
  487. }
  488. }
  489. return false;
  490. }
  491. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) const noexcept
  492. {
  493. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  494. if (const char* const msg = _readlineblock())
  495. {
  496. value = std::atoi(msg);
  497. delete[] msg;
  498. return true;
  499. }
  500. return false;
  501. }
  502. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) const noexcept
  503. {
  504. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  505. if (const char* const msg = _readlineblock())
  506. {
  507. int32_t tmp = std::atoi(msg);
  508. delete[] msg;
  509. if (tmp >= 0)
  510. {
  511. value = static_cast<uint32_t>(tmp);
  512. return true;
  513. }
  514. }
  515. return false;
  516. }
  517. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) const noexcept
  518. {
  519. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  520. if (const char* const msg = _readlineblock())
  521. {
  522. value = std::atol(msg);
  523. delete[] msg;
  524. return true;
  525. }
  526. return false;
  527. }
  528. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) const noexcept
  529. {
  530. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  531. if (const char* const msg = _readlineblock())
  532. {
  533. int64_t tmp = std::atol(msg);
  534. delete[] msg;
  535. if (tmp >= 0)
  536. {
  537. value = static_cast<uint64_t>(tmp);
  538. return true;
  539. }
  540. }
  541. return false;
  542. }
  543. bool CarlaPipeCommon::readNextLineAsFloat(float& value) const noexcept
  544. {
  545. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  546. if (const char* const msg = _readlineblock())
  547. {
  548. value = static_cast<float>(std::atof(msg));
  549. delete[] msg;
  550. return true;
  551. }
  552. return false;
  553. }
  554. bool CarlaPipeCommon::readNextLineAsDouble(double& value) const noexcept
  555. {
  556. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  557. if (const char* const msg = _readlineblock())
  558. {
  559. value = std::atof(msg);
  560. delete[] msg;
  561. return true;
  562. }
  563. return false;
  564. }
  565. bool CarlaPipeCommon::readNextLineAsString(const char*& value) const noexcept
  566. {
  567. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  568. if (const char* const msg = _readlineblock())
  569. {
  570. value = msg;
  571. return true;
  572. }
  573. return false;
  574. }
  575. // -------------------------------------------------------------------
  576. // must be locked before calling
  577. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  578. {
  579. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  580. const std::size_t size(std::strlen(msg));
  581. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  582. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  583. return _writeMsgBuffer(msg, size);
  584. }
  585. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  586. {
  587. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  588. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  589. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  590. return _writeMsgBuffer(msg, size);
  591. }
  592. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  593. {
  594. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  595. const std::size_t size(std::strlen(msg));
  596. char fixedMsg[size+2];
  597. if (size > 0)
  598. {
  599. std::strcpy(fixedMsg, msg);
  600. for (std::size_t i=0; i<size; ++i)
  601. {
  602. if (fixedMsg[i] == '\n')
  603. fixedMsg[i] = '\r';
  604. }
  605. if (fixedMsg[size-1] == '\r')
  606. {
  607. fixedMsg[size-1] = '\n';
  608. fixedMsg[size ] = '\0';
  609. fixedMsg[size+1] = '\0';
  610. }
  611. else
  612. {
  613. fixedMsg[size ] = '\n';
  614. fixedMsg[size+1] = '\0';
  615. }
  616. }
  617. else
  618. {
  619. fixedMsg[0] = '\n';
  620. fixedMsg[1] = '\0';
  621. }
  622. return _writeMsgBuffer(fixedMsg, size+1);
  623. }
  624. bool CarlaPipeCommon::flushMessages() const noexcept
  625. {
  626. #ifdef CARLA_OS_WIN
  627. // TESTING remove later
  628. const CarlaMutexTryLocker cmtl(pData->writeLock);
  629. CARLA_SAFE_ASSERT_RETURN(cmtl.wasNotLocked(), false);
  630. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  631. try {
  632. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  633. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  634. #else
  635. // nothing to do
  636. return true;
  637. #endif
  638. }
  639. // -------------------------------------------------------------------
  640. void CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  641. {
  642. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0',);
  643. const CarlaMutexLocker cml(pData->writeLock);
  644. _writeMsgBuffer("error\n", 6);
  645. writeAndFixMessage(error);
  646. flushMessages();
  647. }
  648. void CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value) const noexcept
  649. {
  650. char tmpBuf[0xff+1];
  651. tmpBuf[0xff] = '\0';
  652. const CarlaMutexLocker cml(pData->writeLock);
  653. const ScopedLocale csl;
  654. _writeMsgBuffer("control\n", 8);
  655. {
  656. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  657. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  658. std::snprintf(tmpBuf, 0xff, "%f\n", value);
  659. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  660. }
  661. flushMessages();
  662. }
  663. void CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  664. {
  665. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  666. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  667. const CarlaMutexLocker cml(pData->writeLock);
  668. _writeMsgBuffer("configure\n", 10);
  669. {
  670. writeAndFixMessage(key);
  671. writeAndFixMessage(value);
  672. }
  673. flushMessages();
  674. }
  675. void CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  676. {
  677. char tmpBuf[0xff+1];
  678. tmpBuf[0xff] = '\0';
  679. const CarlaMutexLocker cml(pData->writeLock);
  680. _writeMsgBuffer("program\n", 8);
  681. {
  682. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  683. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  684. }
  685. flushMessages();
  686. }
  687. void CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  688. {
  689. char tmpBuf[0xff+1];
  690. tmpBuf[0xff] = '\0';
  691. const CarlaMutexLocker cml(pData->writeLock);
  692. _writeMsgBuffer("midiprogram\n", 12);
  693. {
  694. std::snprintf(tmpBuf, 0xff, "%i\n", bank);
  695. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  696. std::snprintf(tmpBuf, 0xff, "%i\n", program);
  697. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  698. }
  699. flushMessages();
  700. }
  701. void CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  702. {
  703. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  704. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  705. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE,);
  706. char tmpBuf[0xff+1];
  707. tmpBuf[0xff] = '\0';
  708. const CarlaMutexLocker cml(pData->writeLock);
  709. _writeMsgBuffer("note\n", 5);
  710. {
  711. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(onOff));
  712. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  713. std::snprintf(tmpBuf, 0xff, "%i\n", channel);
  714. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  715. std::snprintf(tmpBuf, 0xff, "%i\n", note);
  716. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  717. std::snprintf(tmpBuf, 0xff, "%i\n", velocity);
  718. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  719. }
  720. flushMessages();
  721. }
  722. void CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  723. {
  724. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  725. char tmpBuf[0xff+1];
  726. tmpBuf[0xff] = '\0';
  727. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  728. CarlaString base64atom(CarlaString::asBase64(atom, atomTotalSize));
  729. const CarlaMutexLocker cml(pData->writeLock);
  730. _writeMsgBuffer("atom\n", 5);
  731. {
  732. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  733. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  734. std::snprintf(tmpBuf, 0xff, "%i\n", atomTotalSize);
  735. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  736. writeAndFixMessage(base64atom.buffer());
  737. }
  738. flushMessages();
  739. }
  740. void CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  741. {
  742. CARLA_SAFE_ASSERT_RETURN(urid != 0,);
  743. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  744. char tmpBuf[0xff+1];
  745. tmpBuf[0xff] = '\0';
  746. const CarlaMutexLocker cml(pData->writeLock);
  747. _writeMsgBuffer("urid\n", 5);
  748. {
  749. std::snprintf(tmpBuf, 0xff, "%i\n", urid);
  750. _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf));
  751. writeAndFixMessage(uri);
  752. }
  753. flushMessages();
  754. }
  755. // -------------------------------------------------------------------
  756. // internal
  757. const char* CarlaPipeCommon::_readline() const noexcept
  758. {
  759. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  760. char c;
  761. char* ptr = pData->tmpBuf;
  762. ssize_t ret;
  763. pData->tmpStr.clear();
  764. for (int i=0; i<0xff; ++i)
  765. {
  766. try {
  767. #ifdef CARLA_OS_WIN
  768. ret = ::ReadFileWin32(pData->pipeRecv, &c, 1);
  769. #else
  770. ret = ::read(pData->pipeRecv, &c, 1);
  771. #endif
  772. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  773. if (ret != 1 || c == '\n')
  774. break;
  775. if (c == '\r')
  776. c = '\n';
  777. *ptr++ = c;
  778. if (i+1 == 0xff)
  779. {
  780. i = 0;
  781. *ptr = '\0';
  782. pData->tmpStr += pData->tmpBuf;
  783. ptr = pData->tmpBuf;
  784. }
  785. }
  786. if (ptr != pData->tmpBuf)
  787. {
  788. *ptr = '\0';
  789. pData->tmpStr += pData->tmpBuf;
  790. }
  791. else if (pData->tmpStr.isEmpty() && ret != 1)
  792. {
  793. // some error
  794. return nullptr;
  795. }
  796. try {
  797. return pData->tmpStr.dup();
  798. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  799. }
  800. const char* CarlaPipeCommon::_readlineblock(const uint32_t timeOutMilliseconds) const noexcept
  801. {
  802. const uint32_t timeoutEnd(getMillisecondCounter() + timeOutMilliseconds);
  803. for (;;)
  804. {
  805. if (const char* const msg = _readline())
  806. return msg;
  807. if (getMillisecondCounter() >= timeoutEnd)
  808. break;
  809. carla_msleep(5);
  810. }
  811. carla_stderr("readlineblock timed out");
  812. return nullptr;
  813. }
  814. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  815. {
  816. // TESTING remove later
  817. const CarlaMutexTryLocker cmtl(pData->writeLock);
  818. CARLA_SAFE_ASSERT_RETURN(cmtl.wasNotLocked(), false);
  819. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  820. ssize_t ret;
  821. try {
  822. #ifdef CARLA_OS_WIN
  823. ret = ::WriteFileWin32(pData->pipeSend, msg, size);
  824. #else
  825. ret = ::write(pData->pipeSend, msg, size);
  826. #endif
  827. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  828. if (ret == static_cast<ssize_t>(size))
  829. {
  830. if (pData->lastMessageFailed)
  831. pData->lastMessageFailed = false;
  832. return true;
  833. }
  834. if (! pData->lastMessageFailed)
  835. {
  836. pData->lastMessageFailed = true;
  837. fprintf(stderr,
  838. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE ", message was:\n%s",
  839. size, ret, msg);
  840. }
  841. return false;
  842. }
  843. // -----------------------------------------------------------------------
  844. CarlaPipeServer::CarlaPipeServer() noexcept
  845. : CarlaPipeCommon()
  846. {
  847. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  848. }
  849. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  850. {
  851. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  852. stopPipeServer(5*1000);
  853. }
  854. uintptr_t CarlaPipeServer::getPID() const noexcept
  855. {
  856. #ifndef CARLA_OS_WIN
  857. return static_cast<uintptr_t>(pData->pid);
  858. #else
  859. return 0;
  860. #endif
  861. }
  862. // -----------------------------------------------------------------------
  863. bool CarlaPipeServer::startPipeServer(const char* const filename,
  864. const char* const arg1,
  865. const char* const arg2,
  866. const int size) noexcept
  867. {
  868. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  869. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  870. #ifdef CARLA_OS_WIN
  871. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  872. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  873. #else
  874. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  875. #endif
  876. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  877. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  878. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  879. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  880. char pipeRecvServerStr[100+1];
  881. char pipeSendServerStr[100+1];
  882. char pipeRecvClientStr[100+1];
  883. char pipeSendClientStr[100+1];
  884. pipeRecvServerStr[100] = '\0';
  885. pipeSendServerStr[100] = '\0';
  886. pipeRecvClientStr[100] = '\0';
  887. pipeSendClientStr[100] = '\0';
  888. const CarlaMutexLocker cml(pData->writeLock);
  889. //----------------------------------------------------------------
  890. // create pipes
  891. #ifdef CARLA_OS_WIN
  892. HANDLE pipe1, pipe2;
  893. std::srand(static_cast<uint>(std::time(nullptr)));
  894. static ulong sCounter = 0;
  895. ++sCounter;
  896. const int randint = std::rand();
  897. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  898. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  899. std::snprintf(pipeRecvClientStr, 100, "ignored");
  900. std::snprintf(pipeSendClientStr, 100, "ignored");
  901. pipe1 = ::CreateNamedPipeA(pipeRecvServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  902. if (pipe1 == INVALID_HANDLE_VALUE)
  903. {
  904. fail("pipe creation failed");
  905. return false;
  906. }
  907. pipe2 = ::CreateNamedPipeA(pipeSendServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  908. if (pipe2 == INVALID_HANDLE_VALUE)
  909. {
  910. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  911. fail("pipe creation failed");
  912. return false;
  913. }
  914. const HANDLE pipeRecvClient = pipe2;
  915. const HANDLE pipeSendClient = pipe1;
  916. #else
  917. int pipe1[2]; // read by server, written by client
  918. int pipe2[2]; // read by client, written by server
  919. if (::pipe(pipe1) != 0)
  920. {
  921. fail("pipe1 creation failed");
  922. return false;
  923. }
  924. if (::pipe(pipe2) != 0)
  925. {
  926. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  927. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  928. fail("pipe2 creation failed");
  929. return false;
  930. }
  931. /* */ int pipeRecvServer = pipe1[0];
  932. /* */ int pipeSendServer = pipe2[1];
  933. const int pipeRecvClient = pipe2[0];
  934. const int pipeSendClient = pipe1[1];
  935. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  936. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  937. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  938. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  939. //----------------------------------------------------------------
  940. // set size, non-fatal
  941. try {
  942. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  943. } CARLA_SAFE_EXCEPTION("Set pipe size");
  944. try {
  945. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  946. } CARLA_SAFE_EXCEPTION("Set pipe size");
  947. //----------------------------------------------------------------
  948. // set non-block
  949. int ret;
  950. try {
  951. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  952. } catch (...) {
  953. ret = -1;
  954. fail("failed to set pipe as non-block");
  955. }
  956. if (ret == 0)
  957. {
  958. try {
  959. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  960. } catch (...) {
  961. ret = -1;
  962. fail("failed to set pipe as non-block");
  963. }
  964. }
  965. if (ret < 0)
  966. {
  967. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  968. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  969. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  970. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  971. return false;
  972. }
  973. #endif
  974. //----------------------------------------------------------------
  975. // set arguments
  976. const char* argv[8];
  977. //----------------------------------------------------------------
  978. // argv[0] => filename
  979. argv[0] = filename;
  980. //----------------------------------------------------------------
  981. // argv[1-2] => args
  982. argv[1] = arg1;
  983. argv[2] = arg2;
  984. //----------------------------------------------------------------
  985. // argv[3-6] => pipes
  986. argv[3] = pipeRecvServerStr;
  987. argv[4] = pipeSendServerStr;
  988. argv[5] = pipeRecvClientStr;
  989. argv[6] = pipeSendClientStr;
  990. //----------------------------------------------------------------
  991. // argv[7] => null
  992. argv[7] = nullptr;
  993. //----------------------------------------------------------------
  994. // start process
  995. #ifdef CARLA_OS_WIN
  996. if (! startProcess(argv, &pData->processInfo))
  997. {
  998. carla_zeroStruct(pData->processInfo);
  999. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1000. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1001. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1002. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  1003. fail("startProcess() failed");
  1004. return false;
  1005. }
  1006. // just to make sure
  1007. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1008. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1009. #else
  1010. if (! startProcess(argv, pData->pid))
  1011. {
  1012. pData->pid = -1;
  1013. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1014. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1015. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1016. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1017. fail("startProcess() failed");
  1018. return false;
  1019. }
  1020. //----------------------------------------------------------------
  1021. // close duplicated handles used by the client
  1022. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1023. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1024. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  1025. #endif
  1026. //----------------------------------------------------------------
  1027. // wait for client to say something
  1028. if (waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  1029. {
  1030. #ifdef CARLA_OS_WIN
  1031. CARLA_SAFE_ASSERT(waitForClientConnect(pipeSendClient, 1000 /* 1 sec */));
  1032. #endif
  1033. pData->pipeRecv = pipeRecvClient;
  1034. pData->pipeSend = pipeSendClient;
  1035. carla_stdout("ALL OK!");
  1036. return true;
  1037. }
  1038. //----------------------------------------------------------------
  1039. // failed to set non-block or get first child message, cannot continue
  1040. #ifdef CARLA_OS_WIN
  1041. if (TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1042. {
  1043. // wait for process to stop
  1044. waitForProcessToStop(pData->processInfo, 2*1000);
  1045. }
  1046. // clear pData->processInfo
  1047. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1048. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1049. carla_zeroStruct(pData->processInfo);
  1050. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1051. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1052. #else
  1053. if (::kill(pData->pid, SIGKILL) != -1)
  1054. {
  1055. // wait for killing to take place
  1056. waitForChildToStop(pData->pid, 2*1000, false);
  1057. }
  1058. pData->pid = -1;
  1059. #endif
  1060. //----------------------------------------------------------------
  1061. // close pipes
  1062. #ifdef CARLA_OS_WIN
  1063. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1064. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1065. #else
  1066. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1067. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1068. #endif
  1069. return false;
  1070. }
  1071. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1072. {
  1073. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1074. #ifdef CARLA_OS_WIN
  1075. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1076. {
  1077. const CarlaMutexLocker cml(pData->writeLock);
  1078. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1079. {
  1080. _writeMsgBuffer("quit\n", 5);
  1081. flushMessages();
  1082. }
  1083. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  1084. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1085. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1086. carla_zeroStruct(pData->processInfo);
  1087. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1088. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1089. }
  1090. #else
  1091. if (pData->pid != -1)
  1092. {
  1093. const CarlaMutexLocker cml(pData->writeLock);
  1094. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1095. {
  1096. _writeMsgBuffer("quit\n", 5);
  1097. flushMessages();
  1098. }
  1099. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1100. pData->pid = -1;
  1101. }
  1102. #endif
  1103. closePipeServer();
  1104. }
  1105. void CarlaPipeServer::closePipeServer() noexcept
  1106. {
  1107. carla_debug("CarlaPipeServer::closePipeServer()");
  1108. const CarlaMutexLocker cml(pData->writeLock);
  1109. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1110. {
  1111. #ifdef CARLA_OS_WIN
  1112. DisconnectNamedPipe(pData->pipeRecv);
  1113. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1114. #else
  1115. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1116. #endif
  1117. pData->pipeRecv = INVALID_PIPE_VALUE;
  1118. }
  1119. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1120. {
  1121. #ifdef CARLA_OS_WIN
  1122. DisconnectNamedPipe(pData->pipeSend);
  1123. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1124. #else
  1125. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1126. #endif
  1127. pData->pipeSend = INVALID_PIPE_VALUE;
  1128. }
  1129. }
  1130. void CarlaPipeServer::writeShowMessage() const noexcept
  1131. {
  1132. const CarlaMutexLocker cml(pData->writeLock);
  1133. _writeMsgBuffer("show\n", 5);
  1134. flushMessages();
  1135. }
  1136. void CarlaPipeServer::writeFocusMessage() const noexcept
  1137. {
  1138. const CarlaMutexLocker cml(pData->writeLock);
  1139. _writeMsgBuffer("focus\n", 6);
  1140. flushMessages();
  1141. }
  1142. void CarlaPipeServer::writeHideMessage() const noexcept
  1143. {
  1144. const CarlaMutexLocker cml(pData->writeLock);
  1145. _writeMsgBuffer("show\n", 5);
  1146. flushMessages();
  1147. }
  1148. // -----------------------------------------------------------------------
  1149. CarlaPipeClient::CarlaPipeClient() noexcept
  1150. : CarlaPipeCommon()
  1151. {
  1152. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1153. }
  1154. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1155. {
  1156. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1157. closePipeClient();
  1158. }
  1159. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1160. {
  1161. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1162. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1163. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1164. const CarlaMutexLocker cml(pData->writeLock);
  1165. //----------------------------------------------------------------
  1166. // read arguments
  1167. #ifdef CARLA_OS_WIN
  1168. const char* const pipeRecvServerStr = argv[3];
  1169. const char* const pipeSendServerStr = argv[4];
  1170. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1171. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1172. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1173. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1174. #else
  1175. const int pipeRecvServer = std::atoi(argv[3]);
  1176. const int pipeSendServer = std::atoi(argv[4]);
  1177. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1178. /* */ int pipeSendClient = std::atoi(argv[6]);
  1179. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1180. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1181. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1182. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1183. //----------------------------------------------------------------
  1184. // close duplicated handles used by the client
  1185. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1186. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1187. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  1188. #endif
  1189. //----------------------------------------------------------------
  1190. // done
  1191. pData->pipeRecv = pipeRecvServer;
  1192. pData->pipeSend = pipeSendServer;
  1193. writeMessage("\n", 1);
  1194. flushMessages();
  1195. return true;
  1196. }
  1197. void CarlaPipeClient::closePipeClient() noexcept
  1198. {
  1199. carla_debug("CarlaPipeClient::closePipeClient()");
  1200. const CarlaMutexLocker cml(pData->writeLock);
  1201. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1202. {
  1203. #ifdef CARLA_OS_WIN
  1204. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1205. #else
  1206. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1207. #endif
  1208. pData->pipeRecv = INVALID_PIPE_VALUE;
  1209. }
  1210. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1211. {
  1212. #ifdef CARLA_OS_WIN
  1213. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1214. #else
  1215. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1216. #endif
  1217. pData->pipeSend = INVALID_PIPE_VALUE;
  1218. }
  1219. }
  1220. // -----------------------------------------------------------------------
  1221. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1222. : fKey(nullptr),
  1223. fOrigValue(nullptr)
  1224. {
  1225. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1226. fKey = carla_strdup_safe(key);
  1227. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1228. if (const char* const origValue = std::getenv(key))
  1229. {
  1230. fOrigValue = carla_strdup_safe(origValue);
  1231. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1232. }
  1233. if (value != nullptr)
  1234. carla_setenv(key, value);
  1235. else if (fOrigValue != nullptr)
  1236. carla_unsetenv(key);
  1237. }
  1238. ScopedEnvVar::~ScopedEnvVar() noexcept
  1239. {
  1240. bool hasOrigValue = false;
  1241. if (fOrigValue != nullptr)
  1242. {
  1243. hasOrigValue = true;
  1244. carla_setenv(fKey, fOrigValue);
  1245. delete[] fOrigValue;
  1246. fOrigValue = nullptr;
  1247. }
  1248. if (fKey != nullptr)
  1249. {
  1250. if (! hasOrigValue)
  1251. carla_unsetenv(fKey);
  1252. delete[] fKey;
  1253. fKey = nullptr;
  1254. }
  1255. }
  1256. // -----------------------------------------------------------------------
  1257. ScopedLocale::ScopedLocale() noexcept
  1258. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1259. {
  1260. ::setlocale(LC_NUMERIC, "C");
  1261. }
  1262. ScopedLocale::~ScopedLocale() noexcept
  1263. {
  1264. if (fLocale != nullptr)
  1265. {
  1266. ::setlocale(LC_NUMERIC, fLocale);
  1267. delete[] fLocale;
  1268. }
  1269. }
  1270. // -----------------------------------------------------------------------
  1271. #undef INVALID_PIPE_VALUE