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.

1617 lines
43KB

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