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.

1576 lines
42KB

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