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.

1614 lines
43KB

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