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.

1711 lines
46KB

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