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.

1586 lines
42KB

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