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.

1686 lines
45KB

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