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.

1576 lines
42KB

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