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.

1612 lines
43KB

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