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.

1680 lines
44KB

  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. // the client side is closing down, only waiting for response from server
  344. bool clientClosingDown;
  345. // other side of pipe has closed
  346. bool pipeClosed;
  347. // print error only once
  348. bool lastMessageFailed;
  349. // for debugging
  350. bool isServer;
  351. // common write lock
  352. CarlaMutex writeLock;
  353. // temporary buffers for _readline()
  354. mutable char tmpBuf[0xff+1];
  355. mutable CarlaString tmpStr;
  356. PrivateData() noexcept
  357. #ifdef CARLA_OS_WIN
  358. : processInfo(),
  359. #else
  360. : pid(-1),
  361. #endif
  362. pipeRecv(INVALID_PIPE_VALUE),
  363. pipeSend(INVALID_PIPE_VALUE),
  364. isReading(false),
  365. clientClosingDown(false),
  366. pipeClosed(true),
  367. lastMessageFailed(false),
  368. isServer(false),
  369. writeLock(),
  370. tmpBuf(),
  371. tmpStr()
  372. {
  373. #ifdef CARLA_OS_WIN
  374. carla_zeroStruct(processInfo);
  375. processInfo.hProcess = INVALID_HANDLE_VALUE;
  376. processInfo.hThread = INVALID_HANDLE_VALUE;
  377. #endif
  378. carla_zeroChars(tmpBuf, 0xff+1);
  379. }
  380. CARLA_DECLARE_NON_COPY_STRUCT(PrivateData)
  381. };
  382. // -----------------------------------------------------------------------
  383. CarlaPipeCommon::CarlaPipeCommon() noexcept
  384. : pData(new PrivateData())
  385. {
  386. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  387. }
  388. CarlaPipeCommon::~CarlaPipeCommon() /*noexcept*/
  389. {
  390. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  391. delete pData;
  392. }
  393. // -------------------------------------------------------------------
  394. bool CarlaPipeCommon::isPipeRunning() const noexcept
  395. {
  396. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed);
  397. }
  398. void CarlaPipeCommon::idlePipe(const bool onlyOnce) noexcept
  399. {
  400. const char* locale = nullptr;
  401. for (;;)
  402. {
  403. const char* const msg(_readline());
  404. if (msg == nullptr)
  405. break;
  406. if (locale == nullptr && ! onlyOnce)
  407. {
  408. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  409. ::setlocale(LC_NUMERIC, "C");
  410. }
  411. pData->isReading = true;
  412. if (std::strcmp(msg, "__carla-quit__") == 0)
  413. {
  414. pData->pipeClosed = true;
  415. }
  416. else if (! pData->clientClosingDown)
  417. {
  418. try {
  419. msgReceived(msg);
  420. } CARLA_SAFE_EXCEPTION("msgReceived");
  421. }
  422. pData->isReading = false;
  423. delete[] msg;
  424. if (onlyOnce || pData->pipeRecv == INVALID_PIPE_VALUE)
  425. break;
  426. }
  427. if (locale != nullptr)
  428. {
  429. ::setlocale(LC_NUMERIC, locale);
  430. delete[] locale;
  431. }
  432. }
  433. // -------------------------------------------------------------------
  434. void CarlaPipeCommon::lockPipe() const noexcept
  435. {
  436. pData->writeLock.lock();
  437. }
  438. bool CarlaPipeCommon::tryLockPipe() const noexcept
  439. {
  440. return pData->writeLock.tryLock();
  441. }
  442. void CarlaPipeCommon::unlockPipe() const noexcept
  443. {
  444. pData->writeLock.unlock();
  445. }
  446. CarlaMutex& CarlaPipeCommon::getPipeLock() const noexcept
  447. {
  448. return pData->writeLock;
  449. }
  450. // -------------------------------------------------------------------
  451. bool CarlaPipeCommon::readNextLineAsBool(bool& value) const noexcept
  452. {
  453. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  454. if (const char* const msg = _readlineblock())
  455. {
  456. value = (std::strcmp(msg, "true") == 0);
  457. delete[] msg;
  458. return true;
  459. }
  460. return false;
  461. }
  462. bool CarlaPipeCommon::readNextLineAsByte(uint8_t& value) const noexcept
  463. {
  464. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  465. if (const char* const msg = _readlineblock())
  466. {
  467. int tmp = std::atoi(msg);
  468. delete[] msg;
  469. if (tmp >= 0 && tmp <= 0xFF)
  470. {
  471. value = static_cast<uint8_t>(tmp);
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) const noexcept
  478. {
  479. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  480. if (const char* const msg = _readlineblock())
  481. {
  482. value = std::atoi(msg);
  483. delete[] msg;
  484. return true;
  485. }
  486. return false;
  487. }
  488. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) const noexcept
  489. {
  490. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  491. if (const char* const msg = _readlineblock())
  492. {
  493. int32_t tmp = std::atoi(msg);
  494. delete[] msg;
  495. if (tmp >= 0)
  496. {
  497. value = static_cast<uint32_t>(tmp);
  498. return true;
  499. }
  500. }
  501. return false;
  502. }
  503. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) const noexcept
  504. {
  505. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  506. if (const char* const msg = _readlineblock())
  507. {
  508. value = std::atol(msg);
  509. delete[] msg;
  510. return true;
  511. }
  512. return false;
  513. }
  514. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) const noexcept
  515. {
  516. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  517. if (const char* const msg = _readlineblock())
  518. {
  519. int64_t tmp = std::atol(msg);
  520. delete[] msg;
  521. if (tmp >= 0)
  522. {
  523. value = static_cast<uint64_t>(tmp);
  524. return true;
  525. }
  526. }
  527. return false;
  528. }
  529. bool CarlaPipeCommon::readNextLineAsFloat(float& value) const noexcept
  530. {
  531. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  532. if (const char* const msg = _readlineblock())
  533. {
  534. value = static_cast<float>(std::atof(msg));
  535. delete[] msg;
  536. return true;
  537. }
  538. return false;
  539. }
  540. bool CarlaPipeCommon::readNextLineAsDouble(double& value) const noexcept
  541. {
  542. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  543. if (const char* const msg = _readlineblock())
  544. {
  545. value = std::atof(msg);
  546. delete[] msg;
  547. return true;
  548. }
  549. return false;
  550. }
  551. bool CarlaPipeCommon::readNextLineAsString(const char*& value) const noexcept
  552. {
  553. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  554. if (const char* const msg = _readlineblock())
  555. {
  556. value = msg;
  557. return true;
  558. }
  559. return false;
  560. }
  561. // -------------------------------------------------------------------
  562. // must be locked before calling
  563. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  564. {
  565. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  566. if (pData->pipeClosed)
  567. return false;
  568. const std::size_t size(std::strlen(msg));
  569. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  570. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  571. return _writeMsgBuffer(msg, size);
  572. }
  573. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  574. {
  575. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  576. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  577. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  578. if (pData->pipeClosed)
  579. return false;
  580. return _writeMsgBuffer(msg, size);
  581. }
  582. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  583. {
  584. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  585. if (pData->pipeClosed)
  586. return false;
  587. const std::size_t size(std::strlen(msg));
  588. char fixedMsg[size+2];
  589. if (size > 0)
  590. {
  591. std::strcpy(fixedMsg, msg);
  592. for (std::size_t i=0; i<size; ++i)
  593. {
  594. if (fixedMsg[i] == '\n')
  595. fixedMsg[i] = '\r';
  596. }
  597. if (fixedMsg[size-1] == '\r')
  598. {
  599. fixedMsg[size-1] = '\n';
  600. fixedMsg[size ] = '\0';
  601. fixedMsg[size+1] = '\0';
  602. }
  603. else
  604. {
  605. fixedMsg[size ] = '\n';
  606. fixedMsg[size+1] = '\0';
  607. }
  608. }
  609. else
  610. {
  611. fixedMsg[0] = '\n';
  612. fixedMsg[1] = '\0';
  613. }
  614. return _writeMsgBuffer(fixedMsg, size+1);
  615. }
  616. bool CarlaPipeCommon::flushMessages() const noexcept
  617. {
  618. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  619. #ifdef CARLA_OS_WIN
  620. try {
  621. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  622. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  623. #else
  624. // nothing to do
  625. return true;
  626. #endif
  627. }
  628. // -------------------------------------------------------------------
  629. void CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  630. {
  631. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0',);
  632. const CarlaMutexLocker cml(pData->writeLock);
  633. if (! _writeMsgBuffer("error\n", 6))
  634. return;
  635. if (! writeAndFixMessage(error))
  636. return;
  637. flushMessages();
  638. }
  639. void CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value) const noexcept
  640. {
  641. char tmpBuf[0xff+1];
  642. tmpBuf[0xff] = '\0';
  643. const CarlaMutexLocker cml(pData->writeLock);
  644. if (! _writeMsgBuffer("control\n", 8))
  645. return;
  646. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  647. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  648. return;
  649. {
  650. const ScopedLocale csl;
  651. std::snprintf(tmpBuf, 0xff, "%f\n", value);
  652. }
  653. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  654. return;
  655. flushMessages();
  656. }
  657. void CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  658. {
  659. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  660. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  661. const CarlaMutexLocker cml(pData->writeLock);
  662. if (! _writeMsgBuffer("configure\n", 10))
  663. return;
  664. if (! writeAndFixMessage(key))
  665. return;
  666. if (! writeAndFixMessage(value))
  667. return;
  668. flushMessages();
  669. }
  670. void CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  671. {
  672. char tmpBuf[0xff+1];
  673. tmpBuf[0xff] = '\0';
  674. const CarlaMutexLocker cml(pData->writeLock);
  675. if (! _writeMsgBuffer("program\n", 8))
  676. return;
  677. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  678. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  679. return;
  680. flushMessages();
  681. }
  682. void CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  683. {
  684. char tmpBuf[0xff+1];
  685. tmpBuf[0xff] = '\0';
  686. const CarlaMutexLocker cml(pData->writeLock);
  687. if (! _writeMsgBuffer("midiprogram\n", 12))
  688. return;
  689. std::snprintf(tmpBuf, 0xff, "%i\n", bank);
  690. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  691. return;
  692. std::snprintf(tmpBuf, 0xff, "%i\n", program);
  693. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  694. return;
  695. flushMessages();
  696. }
  697. void CarlaPipeCommon::writeReloadProgramsMessage(const int32_t index) const noexcept
  698. {
  699. char tmpBuf[0xff+1];
  700. tmpBuf[0xff] = '\0';
  701. const CarlaMutexLocker cml(pData->writeLock);
  702. if (! _writeMsgBuffer("reloadprograms\n", 15))
  703. return;
  704. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  705. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  706. return;
  707. flushMessages();
  708. }
  709. void CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  710. {
  711. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  712. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  713. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE,);
  714. char tmpBuf[0xff+1];
  715. tmpBuf[0xff] = '\0';
  716. const CarlaMutexLocker cml(pData->writeLock);
  717. if (! _writeMsgBuffer("note\n", 5))
  718. return;
  719. std::snprintf(tmpBuf, 0xff, "%s\n", bool2str(onOff));
  720. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  721. return;
  722. std::snprintf(tmpBuf, 0xff, "%i\n", channel);
  723. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  724. return;
  725. std::snprintf(tmpBuf, 0xff, "%i\n", note);
  726. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  727. return;
  728. std::snprintf(tmpBuf, 0xff, "%i\n", velocity);
  729. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  730. return;
  731. flushMessages();
  732. }
  733. void CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  734. {
  735. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  736. char tmpBuf[0xff+1];
  737. tmpBuf[0xff] = '\0';
  738. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  739. CarlaString base64atom(CarlaString::asBase64(atom, atomTotalSize));
  740. const CarlaMutexLocker cml(pData->writeLock);
  741. if (! _writeMsgBuffer("atom\n", 5))
  742. return;
  743. std::snprintf(tmpBuf, 0xff, "%i\n", index);
  744. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  745. return;
  746. std::snprintf(tmpBuf, 0xff, "%i\n", atomTotalSize);
  747. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  748. return;
  749. if (! writeAndFixMessage(base64atom.buffer()))
  750. return;
  751. flushMessages();
  752. }
  753. void CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  754. {
  755. CARLA_SAFE_ASSERT_RETURN(urid != 0,);
  756. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  757. char tmpBuf[0xff+1];
  758. tmpBuf[0xff] = '\0';
  759. const CarlaMutexLocker cml(pData->writeLock);
  760. if (! _writeMsgBuffer("urid\n", 5))
  761. return;
  762. std::snprintf(tmpBuf, 0xff, "%i\n", urid);
  763. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  764. return;
  765. if (! writeAndFixMessage(uri))
  766. return;
  767. flushMessages();
  768. }
  769. // -------------------------------------------------------------------
  770. // internal
  771. const char* CarlaPipeCommon::_readline() const noexcept
  772. {
  773. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  774. char c;
  775. char* ptr = pData->tmpBuf;
  776. ssize_t ret = -1;
  777. pData->tmpStr.clear();
  778. for (int i=0; i<0xff; ++i)
  779. {
  780. try {
  781. #ifdef CARLA_OS_WIN
  782. ret = ::ReadFileWin32(pData->pipeRecv, &c, 1);
  783. #else
  784. ret = ::read(pData->pipeRecv, &c, 1);
  785. #endif
  786. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  787. if (ret != 1 || c == '\n')
  788. break;
  789. if (c == '\r')
  790. c = '\n';
  791. *ptr++ = c;
  792. if (i+1 == 0xff)
  793. {
  794. i = 0;
  795. *ptr = '\0';
  796. pData->tmpStr += pData->tmpBuf;
  797. ptr = pData->tmpBuf;
  798. }
  799. }
  800. if (ptr != pData->tmpBuf)
  801. {
  802. *ptr = '\0';
  803. pData->tmpStr += pData->tmpBuf;
  804. }
  805. else if (pData->tmpStr.isEmpty() && ret != 1)
  806. {
  807. // some error
  808. return nullptr;
  809. }
  810. try {
  811. return pData->tmpStr.dup();
  812. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  813. }
  814. const char* CarlaPipeCommon::_readlineblock(const uint32_t timeOutMilliseconds) const noexcept
  815. {
  816. const uint32_t timeoutEnd(water::Time::getMillisecondCounter() + timeOutMilliseconds);
  817. for (;;)
  818. {
  819. if (const char* const msg = _readline())
  820. return msg;
  821. if (water::Time::getMillisecondCounter() >= timeoutEnd)
  822. break;
  823. carla_msleep(5);
  824. }
  825. carla_stderr("readlineblock timed out");
  826. return nullptr;
  827. }
  828. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  829. {
  830. if (pData->pipeClosed)
  831. return false;
  832. if (pData->pipeSend == INVALID_PIPE_VALUE)
  833. {
  834. carla_stderr2("CarlaPipe write error, isServer:%s, message was:\n%s", bool2str(pData->isServer), msg);
  835. return false;
  836. }
  837. ssize_t ret;
  838. try {
  839. #ifdef CARLA_OS_WIN
  840. ret = ::WriteFileWin32(pData->pipeSend, msg, size);
  841. #else
  842. ret = ::write(pData->pipeSend, msg, size);
  843. #endif
  844. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  845. if (ret == static_cast<ssize_t>(size))
  846. {
  847. if (pData->lastMessageFailed)
  848. pData->lastMessageFailed = false;
  849. return true;
  850. }
  851. #if 0
  852. // ignore errors if the other side of the pipe has closed
  853. if (pData->pipeClosed)
  854. return false;
  855. #endif
  856. if (! pData->lastMessageFailed)
  857. {
  858. pData->lastMessageFailed = true;
  859. fprintf(stderr,
  860. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE " (%s), message was:\n%s",
  861. size, ret, bool2str(pData->isServer), msg);
  862. }
  863. return false;
  864. }
  865. // -----------------------------------------------------------------------
  866. CarlaPipeServer::CarlaPipeServer() noexcept
  867. : CarlaPipeCommon()
  868. {
  869. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  870. pData->isServer = true;
  871. }
  872. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  873. {
  874. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  875. stopPipeServer(5*1000);
  876. }
  877. uintptr_t CarlaPipeServer::getPID() const noexcept
  878. {
  879. #ifndef CARLA_OS_WIN
  880. return static_cast<uintptr_t>(pData->pid);
  881. #else
  882. return 0;
  883. #endif
  884. }
  885. // -----------------------------------------------------------------------
  886. bool CarlaPipeServer::startPipeServer(const char* const filename,
  887. const char* const arg1,
  888. const char* const arg2,
  889. const int size) noexcept
  890. {
  891. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  892. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  893. #ifdef CARLA_OS_WIN
  894. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  895. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  896. #else
  897. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  898. #endif
  899. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  900. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  901. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  902. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  903. char pipeRecvServerStr[100+1];
  904. char pipeSendServerStr[100+1];
  905. char pipeRecvClientStr[100+1];
  906. char pipeSendClientStr[100+1];
  907. pipeRecvServerStr[100] = '\0';
  908. pipeSendServerStr[100] = '\0';
  909. pipeRecvClientStr[100] = '\0';
  910. pipeSendClientStr[100] = '\0';
  911. const CarlaMutexLocker cml(pData->writeLock);
  912. //----------------------------------------------------------------
  913. // create pipes
  914. #ifdef CARLA_OS_WIN
  915. HANDLE pipe1, pipe2;
  916. std::srand(static_cast<uint>(std::time(nullptr)));
  917. static ulong sCounter = 0;
  918. ++sCounter;
  919. const int randint = std::rand();
  920. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  921. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  922. std::snprintf(pipeRecvClientStr, 100, "ignored");
  923. std::snprintf(pipeSendClientStr, 100, "ignored");
  924. pipe1 = ::CreateNamedPipeA(pipeRecvServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  925. if (pipe1 == INVALID_HANDLE_VALUE)
  926. {
  927. fail("pipe creation failed");
  928. return false;
  929. }
  930. pipe2 = ::CreateNamedPipeA(pipeSendServerStr, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE|PIPE_NOWAIT, 2, size, size, 0, nullptr);
  931. if (pipe2 == INVALID_HANDLE_VALUE)
  932. {
  933. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  934. fail("pipe creation failed");
  935. return false;
  936. }
  937. const HANDLE pipeRecvClient = pipe2;
  938. const HANDLE pipeSendClient = pipe1;
  939. #else
  940. int pipe1[2]; // read by server, written by client
  941. int pipe2[2]; // read by client, written by server
  942. if (::pipe(pipe1) != 0)
  943. {
  944. fail("pipe1 creation failed");
  945. return false;
  946. }
  947. if (::pipe(pipe2) != 0)
  948. {
  949. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  950. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  951. fail("pipe2 creation failed");
  952. return false;
  953. }
  954. /* */ int pipeRecvServer = pipe1[0];
  955. /* */ int pipeSendServer = pipe2[1];
  956. const int pipeRecvClient = pipe2[0];
  957. const int pipeSendClient = pipe1[1];
  958. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  959. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  960. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  961. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  962. //----------------------------------------------------------------
  963. // set size, non-fatal
  964. #ifdef CARLA_OS_LINUX
  965. try {
  966. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  967. } CARLA_SAFE_EXCEPTION("Set pipe size");
  968. try {
  969. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  970. } CARLA_SAFE_EXCEPTION("Set pipe size");
  971. #endif
  972. //----------------------------------------------------------------
  973. // set non-block
  974. int ret;
  975. try {
  976. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  977. } catch (...) {
  978. ret = -1;
  979. fail("failed to set pipe as non-block");
  980. }
  981. if (ret == 0)
  982. {
  983. try {
  984. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  985. } catch (...) {
  986. ret = -1;
  987. fail("failed to set pipe as non-block");
  988. }
  989. }
  990. if (ret < 0)
  991. {
  992. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  993. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  994. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  995. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  996. return false;
  997. }
  998. #endif
  999. //----------------------------------------------------------------
  1000. // set arguments
  1001. const char* argv[8];
  1002. //----------------------------------------------------------------
  1003. // argv[0] => filename
  1004. argv[0] = filename;
  1005. //----------------------------------------------------------------
  1006. // argv[1-2] => args
  1007. argv[1] = arg1;
  1008. argv[2] = arg2;
  1009. //----------------------------------------------------------------
  1010. // argv[3-6] => pipes
  1011. argv[3] = pipeRecvServerStr;
  1012. argv[4] = pipeSendServerStr;
  1013. argv[5] = pipeRecvClientStr;
  1014. argv[6] = pipeSendClientStr;
  1015. //----------------------------------------------------------------
  1016. // argv[7] => null
  1017. argv[7] = nullptr;
  1018. //----------------------------------------------------------------
  1019. // start process
  1020. #ifdef CARLA_OS_WIN
  1021. if (! startProcess(argv, &pData->processInfo))
  1022. {
  1023. carla_zeroStruct(pData->processInfo);
  1024. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1025. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1026. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1027. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  1028. fail("startProcess() failed");
  1029. return false;
  1030. }
  1031. // just to make sure
  1032. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1033. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1034. #else
  1035. if (! startProcess(argv, pData->pid))
  1036. {
  1037. pData->pid = -1;
  1038. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1039. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1040. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1041. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1042. fail("startProcess() failed");
  1043. return false;
  1044. }
  1045. //----------------------------------------------------------------
  1046. // close duplicated handles used by the client
  1047. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1048. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1049. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  1050. #endif
  1051. //----------------------------------------------------------------
  1052. // wait for client to say something
  1053. if (waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  1054. {
  1055. #ifdef CARLA_OS_WIN
  1056. CARLA_SAFE_ASSERT(waitForClientConnect(pipeSendClient, 1000 /* 1 sec */));
  1057. #endif
  1058. pData->pipeRecv = pipeRecvClient;
  1059. pData->pipeSend = pipeSendClient;
  1060. pData->pipeClosed = false;
  1061. carla_stdout("ALL OK!");
  1062. return true;
  1063. }
  1064. //----------------------------------------------------------------
  1065. // failed to set non-block or get first child message, cannot continue
  1066. #ifdef CARLA_OS_WIN
  1067. if (TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1068. {
  1069. // wait for process to stop
  1070. waitForProcessToStop(pData->processInfo, 2*1000);
  1071. }
  1072. // clear pData->processInfo
  1073. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1074. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1075. carla_zeroStruct(pData->processInfo);
  1076. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1077. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1078. #else
  1079. if (::kill(pData->pid, SIGKILL) != -1)
  1080. {
  1081. // wait for killing to take place
  1082. waitForChildToStop(pData->pid, 2*1000, false);
  1083. }
  1084. pData->pid = -1;
  1085. #endif
  1086. //----------------------------------------------------------------
  1087. // close pipes
  1088. #ifdef CARLA_OS_WIN
  1089. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1090. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1091. #else
  1092. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1093. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1094. #endif
  1095. return false;
  1096. }
  1097. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1098. {
  1099. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1100. #ifdef CARLA_OS_WIN
  1101. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1102. {
  1103. const CarlaMutexLocker cml(pData->writeLock);
  1104. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1105. {
  1106. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1107. flushMessages();
  1108. }
  1109. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  1110. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1111. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1112. carla_zeroStruct(pData->processInfo);
  1113. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1114. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1115. }
  1116. #else
  1117. if (pData->pid != -1)
  1118. {
  1119. const CarlaMutexLocker cml(pData->writeLock);
  1120. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1121. {
  1122. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1123. flushMessages();
  1124. }
  1125. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1126. pData->pid = -1;
  1127. }
  1128. #endif
  1129. closePipeServer();
  1130. }
  1131. void CarlaPipeServer::closePipeServer() noexcept
  1132. {
  1133. carla_debug("CarlaPipeServer::closePipeServer()");
  1134. pData->pipeClosed = true;
  1135. const CarlaMutexLocker cml(pData->writeLock);
  1136. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1137. {
  1138. #ifdef CARLA_OS_WIN
  1139. DisconnectNamedPipe(pData->pipeRecv);
  1140. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1141. #else
  1142. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1143. #endif
  1144. pData->pipeRecv = INVALID_PIPE_VALUE;
  1145. }
  1146. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1147. {
  1148. #ifdef CARLA_OS_WIN
  1149. DisconnectNamedPipe(pData->pipeSend);
  1150. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1151. #else
  1152. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1153. #endif
  1154. pData->pipeSend = INVALID_PIPE_VALUE;
  1155. }
  1156. }
  1157. void CarlaPipeServer::writeShowMessage() const noexcept
  1158. {
  1159. const CarlaMutexLocker cml(pData->writeLock);
  1160. if (! _writeMsgBuffer("show\n", 5))
  1161. return;
  1162. flushMessages();
  1163. }
  1164. void CarlaPipeServer::writeFocusMessage() const noexcept
  1165. {
  1166. const CarlaMutexLocker cml(pData->writeLock);
  1167. if (! _writeMsgBuffer("focus\n", 6))
  1168. return;
  1169. flushMessages();
  1170. }
  1171. void CarlaPipeServer::writeHideMessage() const noexcept
  1172. {
  1173. const CarlaMutexLocker cml(pData->writeLock);
  1174. if (! _writeMsgBuffer("show\n", 5))
  1175. return;
  1176. flushMessages();
  1177. }
  1178. // -----------------------------------------------------------------------
  1179. CarlaPipeClient::CarlaPipeClient() noexcept
  1180. : CarlaPipeCommon()
  1181. {
  1182. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1183. }
  1184. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1185. {
  1186. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1187. closePipeClient();
  1188. }
  1189. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1190. {
  1191. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1192. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1193. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1194. const CarlaMutexLocker cml(pData->writeLock);
  1195. //----------------------------------------------------------------
  1196. // read arguments
  1197. #ifdef CARLA_OS_WIN
  1198. const char* const pipeRecvServerStr = argv[3];
  1199. const char* const pipeSendServerStr = argv[4];
  1200. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1201. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1202. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1203. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1204. #else
  1205. const int pipeRecvServer = std::atoi(argv[3]);
  1206. const int pipeSendServer = std::atoi(argv[4]);
  1207. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1208. /* */ int pipeSendClient = std::atoi(argv[6]);
  1209. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1210. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1211. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1212. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1213. //----------------------------------------------------------------
  1214. // close duplicated handles used by the client
  1215. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1216. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1217. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  1218. //----------------------------------------------------------------
  1219. // kill ourselves if parent dies
  1220. # ifdef CARLA_OS_LINUX
  1221. ::prctl(PR_SET_PDEATHSIG, SIGKILL);
  1222. // TODO, osx version too, see https://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits
  1223. # endif
  1224. #endif
  1225. //----------------------------------------------------------------
  1226. // done
  1227. pData->pipeRecv = pipeRecvServer;
  1228. pData->pipeSend = pipeSendServer;
  1229. pData->pipeClosed = false;
  1230. pData->clientClosingDown = false;
  1231. if (writeMessage("\n", 1))
  1232. flushMessages();
  1233. return true;
  1234. }
  1235. void CarlaPipeClient::closePipeClient() noexcept
  1236. {
  1237. carla_debug("CarlaPipeClient::closePipeClient()");
  1238. pData->pipeClosed = true;
  1239. const CarlaMutexLocker cml(pData->writeLock);
  1240. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1241. {
  1242. #ifdef CARLA_OS_WIN
  1243. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1244. #else
  1245. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1246. #endif
  1247. pData->pipeRecv = INVALID_PIPE_VALUE;
  1248. }
  1249. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1250. {
  1251. #ifdef CARLA_OS_WIN
  1252. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1253. #else
  1254. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1255. #endif
  1256. pData->pipeSend = INVALID_PIPE_VALUE;
  1257. }
  1258. }
  1259. void CarlaPipeClient::writeExitingMessageAndWait() noexcept
  1260. {
  1261. {
  1262. const CarlaMutexLocker cml(pData->writeLock);
  1263. if (_writeMsgBuffer("exiting\n", 8))
  1264. flushMessages();
  1265. }
  1266. // NOTE: no more messages are handled after this point
  1267. pData->clientClosingDown = true;
  1268. // FIXME: don't sleep forever
  1269. for (; ! pData->pipeClosed;)
  1270. {
  1271. carla_msleep(50);
  1272. idlePipe(true);
  1273. }
  1274. }
  1275. // -----------------------------------------------------------------------
  1276. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1277. : fKey(nullptr),
  1278. fOrigValue(nullptr)
  1279. {
  1280. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1281. fKey = carla_strdup_safe(key);
  1282. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1283. if (const char* const origValue = std::getenv(key))
  1284. {
  1285. fOrigValue = carla_strdup_safe(origValue);
  1286. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1287. }
  1288. if (value != nullptr)
  1289. carla_setenv(key, value);
  1290. else if (fOrigValue != nullptr)
  1291. carla_unsetenv(key);
  1292. }
  1293. ScopedEnvVar::~ScopedEnvVar() noexcept
  1294. {
  1295. bool hasOrigValue = false;
  1296. if (fOrigValue != nullptr)
  1297. {
  1298. hasOrigValue = true;
  1299. carla_setenv(fKey, fOrigValue);
  1300. delete[] fOrigValue;
  1301. fOrigValue = nullptr;
  1302. }
  1303. if (fKey != nullptr)
  1304. {
  1305. if (! hasOrigValue)
  1306. carla_unsetenv(fKey);
  1307. delete[] fKey;
  1308. fKey = nullptr;
  1309. }
  1310. }
  1311. // -----------------------------------------------------------------------
  1312. ScopedLocale::ScopedLocale() noexcept
  1313. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1314. {
  1315. ::setlocale(LC_NUMERIC, "C");
  1316. }
  1317. ScopedLocale::~ScopedLocale() noexcept
  1318. {
  1319. if (fLocale != nullptr)
  1320. {
  1321. ::setlocale(LC_NUMERIC, fLocale);
  1322. delete[] fLocale;
  1323. }
  1324. }
  1325. // -----------------------------------------------------------------------
  1326. #undef INVALID_PIPE_VALUE