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.

1613 lines
43KB

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