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.

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