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.

2000 lines
54KB

  1. // SPDX-FileCopyrightText: 2011-2025 Filipe Coelho <falktx@falktx.com>
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "CarlaPipeUtils.hpp"
  4. #include "CarlaProcessUtils.hpp"
  5. #include "CarlaScopeUtils.hpp"
  6. #include "CarlaMIDI.h"
  7. #include "distrho/extra/Sleep.hpp"
  8. #include "distrho/extra/String.hpp"
  9. #include "distrho/extra/Time.hpp"
  10. // needed for atom-util
  11. #ifndef nullptr
  12. # undef NULL
  13. # define NULL nullptr
  14. #endif
  15. #ifdef BUILDING_CARLA
  16. # include "lv2/atom-util.h"
  17. #else
  18. # include "lv2/atom/util.h"
  19. #endif
  20. #include <fcntl.h>
  21. #ifdef CARLA_OS_WIN
  22. # include "water/text/String.h"
  23. # include <ctime>
  24. #else
  25. # include <cerrno>
  26. # include <signal.h>
  27. # include <sys/wait.h>
  28. # ifdef CARLA_OS_LINUX
  29. # include <sys/prctl.h>
  30. # ifndef F_SETPIPE_SZ
  31. # define F_SETPIPE_SZ 1031
  32. # endif
  33. # endif
  34. #endif
  35. #ifdef CARLA_OS_WIN
  36. # define INVALID_PIPE_VALUE INVALID_HANDLE_VALUE
  37. #else
  38. # define INVALID_PIPE_VALUE -1
  39. #endif
  40. #ifdef CARLA_OS_WIN
  41. // -----------------------------------------------------------------------
  42. // win32 stuff
  43. static inline
  44. bool waitForAsyncObject(const HANDLE object, const HANDLE process = INVALID_HANDLE_VALUE)
  45. {
  46. DWORD dw, dw2;
  47. MSG msg;
  48. // we give it a max
  49. for (int i=20000; --i>=0;)
  50. {
  51. if (process != INVALID_HANDLE_VALUE)
  52. {
  53. switch (::WaitForSingleObject(process, 0))
  54. {
  55. case WAIT_OBJECT_0:
  56. case WAIT_FAILED:
  57. carla_stderr("waitForAsyncObject process has stopped");
  58. return false;
  59. }
  60. }
  61. carla_debug("waitForAsyncObject loop start");
  62. dw = ::MsgWaitForMultipleObjectsEx(1, &object, INFINITE, QS_POSTMESSAGE|QS_TIMER, 0);
  63. carla_debug("waitForAsyncObject initial code is: %u", dw);
  64. if (dw == WAIT_OBJECT_0)
  65. {
  66. carla_debug("waitForAsyncObject WAIT_OBJECT_0");
  67. return true;
  68. }
  69. dw2 = ::GetLastError();
  70. if (dw == WAIT_OBJECT_0 + 1)
  71. {
  72. carla_debug("waitForAsyncObject loop +1");
  73. while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
  74. ::DispatchMessage(&msg);
  75. continue;
  76. }
  77. if (dw2 == 0)
  78. {
  79. carla_debug("waitForAsyncObject loop stop");
  80. return true;
  81. }
  82. carla_stderr2("waitForAsyncObject loop end reached, error was: %u", dw2);
  83. d_msleep(5);
  84. }
  85. carla_stderr2("waitForAsyncObject reached the end, this should not happen");
  86. return false;
  87. }
  88. static inline
  89. ssize_t ReadFileWin32(const HANDLE pipeh, const HANDLE event, void* const buf, const DWORD numBytes)
  90. {
  91. DWORD dw, dsize = numBytes;
  92. DWORD available = 0;
  93. if (::PeekNamedPipe(pipeh, nullptr, 0, nullptr, &available, nullptr) == FALSE || available == 0)
  94. return -1;
  95. OVERLAPPED ov;
  96. carla_zeroStruct(ov);
  97. ov.hEvent = event;
  98. if (::ReadFile(pipeh, buf, dsize, nullptr, &ov))
  99. {
  100. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  101. {
  102. carla_stderr("ReadFileWin32 GetOverlappedResult failed, error was: %u", ::GetLastError());
  103. return -1;
  104. }
  105. return static_cast<ssize_t>(dsize);
  106. }
  107. dw = ::GetLastError();
  108. if (dw == ERROR_IO_PENDING)
  109. {
  110. if (! waitForAsyncObject(event))
  111. {
  112. carla_stderr("ReadFileWin32 waitForAsyncObject failed, error was: %u", ::GetLastError());
  113. return -1;
  114. }
  115. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  116. {
  117. carla_stderr("ReadFileWin32 GetOverlappedResult of pending failed, error was: %u", ::GetLastError());
  118. return -1;
  119. }
  120. return static_cast<ssize_t>(dsize);
  121. }
  122. carla_stderr("ReadFileWin32 failed, error was: %u", dw);
  123. return -1;
  124. }
  125. static inline
  126. ssize_t WriteFileWin32(const HANDLE pipeh, const HANDLE event, const void* const buf, const DWORD numBytes)
  127. {
  128. DWORD dw, dsize = numBytes;
  129. OVERLAPPED ov;
  130. carla_zeroStruct(ov);
  131. ov.hEvent = event;
  132. if (::WriteFile(pipeh, buf, dsize, nullptr, &ov))
  133. {
  134. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  135. {
  136. carla_stderr("WriteFileWin32 GetOverlappedResult failed, error was: %u", ::GetLastError());
  137. return -1;
  138. }
  139. return static_cast<ssize_t>(dsize);
  140. }
  141. dw = ::GetLastError();
  142. if (dw == ERROR_IO_PENDING)
  143. {
  144. if (! waitForAsyncObject(event))
  145. {
  146. carla_stderr("WriteFileWin32 waitForAsyncObject failed, error was: %u", ::GetLastError());
  147. return -1;
  148. }
  149. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  150. {
  151. carla_stderr("WriteFileWin32 GetOverlappedResult of pending failed, error was: %u", ::GetLastError());
  152. return -1;
  153. }
  154. return static_cast<ssize_t>(dsize);
  155. }
  156. if (dw == ERROR_PIPE_NOT_CONNECTED)
  157. {
  158. carla_stdout("WriteFileWin32 failed, client has closed");
  159. return -2;
  160. }
  161. carla_stderr("WriteFileWin32 failed, error was: %u", dw);
  162. return -1;
  163. }
  164. #endif // CARLA_OS_WIN
  165. // -----------------------------------------------------------------------
  166. // startProcess
  167. #ifdef CARLA_OS_WIN
  168. static inline
  169. bool startProcess(const char* const argv[], PROCESS_INFORMATION* const processInfo)
  170. {
  171. CARLA_SAFE_ASSERT_RETURN(processInfo != nullptr, false);
  172. using water::String;
  173. String command;
  174. for (int i=0; argv[i] != nullptr; ++i)
  175. {
  176. String arg(argv[i]);
  177. // If there are spaces, surround it with quotes. If there are quotes,
  178. // replace them with \" so that CommandLineToArgv will correctly parse them.
  179. if (arg.containsAnyOf("\" "))
  180. arg = arg.replace("\"", "\\\"").quoted();
  181. command << arg << ' ';
  182. }
  183. command = command.trim();
  184. STARTUPINFOA startupInfo;
  185. carla_zeroStruct(startupInfo);
  186. startupInfo.cb = sizeof(startupInfo);
  187. if (::CreateProcessA(nullptr, const_cast<LPSTR>(command.toRawUTF8()),
  188. nullptr, nullptr, TRUE, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
  189. nullptr, nullptr, &startupInfo, processInfo) != FALSE)
  190. return true;
  191. carla_stderr2("startProcess failed, error was: %u", ::GetLastError());
  192. return false;
  193. }
  194. static inline
  195. bool waitForClientConnect(const HANDLE pipe, const HANDLE event, const HANDLE process, const uint32_t timeOutMilliseconds) noexcept
  196. {
  197. CARLA_SAFE_ASSERT_RETURN(pipe != INVALID_PIPE_VALUE, false);
  198. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  199. DWORD dw;
  200. OVERLAPPED ov;
  201. carla_zeroStruct(ov);
  202. ov.hEvent = event;
  203. const uint32_t timeoutEnd = d_gettime_ms() + timeOutMilliseconds;
  204. for (;;)
  205. {
  206. if (::ConnectNamedPipe(pipe, &ov))
  207. {
  208. if (! ::GetOverlappedResult(pipe, &ov, &dw, FALSE))
  209. {
  210. carla_stderr2("ConnectNamedPipe GetOverlappedResult failed, error was: %u", ::GetLastError());
  211. return false;
  212. }
  213. return true;
  214. }
  215. const DWORD err = ::GetLastError();
  216. switch (err)
  217. {
  218. case ERROR_PIPE_CONNECTED:
  219. return true;
  220. case ERROR_IO_PENDING:
  221. if (! waitForAsyncObject(event, process))
  222. {
  223. carla_stderr2("ConnectNamedPipe waitForAsyncObject failed, error was: %u", ::GetLastError());
  224. return false;
  225. }
  226. if (! ::GetOverlappedResult(pipe, &ov, &dw, FALSE))
  227. {
  228. carla_stderr2("ConnectNamedPipe GetOverlappedResult of pending failed, error was: %u", ::GetLastError());
  229. return false;
  230. }
  231. return true;
  232. case ERROR_PIPE_LISTENING:
  233. if (d_gettime_ms() < timeoutEnd)
  234. {
  235. d_msleep(5);
  236. continue;
  237. }
  238. carla_stderr2("ConnectNamedPipe listening timed out");
  239. return false;
  240. default:
  241. carla_stderr2("ConnectNamedPipe failed, error was: %u", err);
  242. return false;
  243. }
  244. }
  245. return true;
  246. }
  247. #else
  248. static inline
  249. bool startProcess(const char* const argv[], pid_t& pidinst) noexcept
  250. {
  251. const CarlaScopedEnvVar sev1("LD_LIBRARY_PATH", nullptr);
  252. const CarlaScopedEnvVar sev2("LD_PRELOAD", nullptr);
  253. #ifdef __clang__
  254. #pragma clang diagnostic push
  255. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  256. #endif
  257. const pid_t ret = pidinst = vfork();
  258. #ifdef __clang__
  259. #pragma clang diagnostic pop
  260. #endif
  261. switch (ret)
  262. {
  263. case 0: { // child process
  264. execvp(argv[0], const_cast<char* const*>(argv));
  265. String error(std::strerror(errno));
  266. carla_stderr2("exec failed: %s", error.buffer());
  267. _exit(1); // this is not noexcept safe but doesn't matter anyway
  268. } break;
  269. case -1: { // error
  270. String error(std::strerror(errno));
  271. carla_stderr2("vfork() failed: %s", error.buffer());
  272. } break;
  273. }
  274. return (ret > 0);
  275. }
  276. #endif
  277. // -----------------------------------------------------------------------
  278. // waitForClientFirstMessage
  279. template<typename P>
  280. static inline
  281. bool waitForClientFirstMessage(const P& pipe, void* const ovRecv, void* const process, const uint32_t timeOutMilliseconds) noexcept
  282. {
  283. CARLA_SAFE_ASSERT_RETURN(pipe != INVALID_PIPE_VALUE, false);
  284. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  285. char c;
  286. ssize_t ret;
  287. const uint32_t timeoutEnd = d_gettime_ms() + timeOutMilliseconds;
  288. #ifdef CARLA_OS_WIN
  289. if (! waitForClientConnect(pipe, (HANDLE)ovRecv, (HANDLE)process, timeOutMilliseconds))
  290. return false;
  291. #endif
  292. for (;;)
  293. {
  294. try {
  295. #ifdef CARLA_OS_WIN
  296. ret = ReadFileWin32(pipe, (HANDLE)ovRecv, &c, 1);
  297. #else
  298. ret = ::read(pipe, &c, 1);
  299. #endif
  300. } CARLA_SAFE_EXCEPTION_RETURN("read pipe", false);
  301. switch (ret)
  302. {
  303. case 1:
  304. if (c == '\n')
  305. return true;
  306. carla_stderr("waitForClientFirstMessage() - read has wrong first char '%c'", c);return false;
  307. return false;
  308. case -1: // failed to read
  309. #ifdef CARLA_OS_WIN
  310. if (::GetLastError() == ERROR_NO_DATA)
  311. #else
  312. if (errno == EAGAIN)
  313. #endif
  314. {
  315. if (d_gettime_ms() < timeoutEnd)
  316. {
  317. d_msleep(5);
  318. continue;
  319. }
  320. carla_stderr("waitForClientFirstMessage() - read timed out");
  321. }
  322. else
  323. {
  324. #ifdef CARLA_OS_WIN
  325. carla_stderr("waitForClientFirstMessage() - read failed");
  326. #else
  327. String error(std::strerror(errno));
  328. carla_stderr("waitForClientFirstMessage() - read failed: %s", error.buffer());
  329. #endif
  330. }
  331. return false;
  332. default: // ???
  333. carla_stderr("waitForClientFirstMessage() - read returned %i", int(ret));
  334. return false;
  335. }
  336. }
  337. // maybe unused
  338. (void)ovRecv; (void)process;
  339. }
  340. // -----------------------------------------------------------------------
  341. // waitForChildToStop / waitForProcessToStop
  342. #ifdef CARLA_OS_WIN
  343. static inline
  344. bool waitForProcessToStop(const HANDLE process, const uint32_t timeOutMilliseconds, bool sendTerminate) noexcept
  345. {
  346. CARLA_SAFE_ASSERT_RETURN(process != INVALID_HANDLE_VALUE, false);
  347. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  348. const uint32_t timeoutEnd = d_gettime_ms() + timeOutMilliseconds;
  349. for (;;)
  350. {
  351. switch (::WaitForSingleObject(process, 0))
  352. {
  353. case WAIT_OBJECT_0:
  354. case WAIT_FAILED:
  355. return true;
  356. }
  357. if (sendTerminate)
  358. {
  359. sendTerminate = false;
  360. ::TerminateProcess(process, 15);
  361. }
  362. if (d_gettime_ms() >= timeoutEnd)
  363. break;
  364. d_msleep(5);
  365. }
  366. return false;
  367. }
  368. static inline
  369. void waitForProcessToStopOrKillIt(const HANDLE process, const uint32_t timeOutMilliseconds) noexcept
  370. {
  371. CARLA_SAFE_ASSERT_RETURN(process != INVALID_HANDLE_VALUE,);
  372. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  373. if (! waitForProcessToStop(process, timeOutMilliseconds, true))
  374. {
  375. carla_stderr("waitForProcessToStopOrKillIt() - process didn't stop, force termination");
  376. if (::TerminateProcess(process, 9) != FALSE)
  377. {
  378. // wait for process to stop
  379. waitForProcessToStop(process, timeOutMilliseconds, false);
  380. }
  381. }
  382. }
  383. #else
  384. static inline
  385. bool waitForChildToStop(const pid_t pid, const uint32_t timeOutMilliseconds, bool sendTerminate) noexcept
  386. {
  387. CARLA_SAFE_ASSERT_RETURN(pid > 0, false);
  388. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  389. pid_t ret;
  390. const uint32_t timeoutEnd = d_gettime_ms() + timeOutMilliseconds;
  391. for (;;)
  392. {
  393. try {
  394. ret = ::waitpid(pid, nullptr, WNOHANG);
  395. } CARLA_SAFE_EXCEPTION_BREAK("waitpid");
  396. switch (ret)
  397. {
  398. case -1:
  399. if (errno == ECHILD)
  400. {
  401. // success, child doesn't exist
  402. return true;
  403. }
  404. else
  405. {
  406. String error(std::strerror(errno));
  407. carla_stderr("waitForChildToStop() - waitpid failed: %s", error.buffer());
  408. return false;
  409. }
  410. break;
  411. case 0:
  412. if (sendTerminate)
  413. {
  414. sendTerminate = false;
  415. ::kill(pid, SIGTERM);
  416. }
  417. if (d_gettime_ms() < timeoutEnd)
  418. {
  419. d_msleep(5);
  420. continue;
  421. }
  422. carla_stderr("waitForChildToStop() - timed out");
  423. break;
  424. default:
  425. if (ret == pid)
  426. {
  427. // success
  428. return true;
  429. }
  430. else
  431. {
  432. carla_stderr("waitForChildToStop() - got wrong pid %i (requested was %i)", int(ret), int(pid));
  433. return false;
  434. }
  435. }
  436. break;
  437. }
  438. return false;
  439. }
  440. static inline
  441. void waitForChildToStopOrKillIt(pid_t& pid, const uint32_t timeOutMilliseconds) noexcept
  442. {
  443. CARLA_SAFE_ASSERT_RETURN(pid > 0,);
  444. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  445. if (! waitForChildToStop(pid, timeOutMilliseconds, true))
  446. {
  447. carla_stderr("waitForChildToStopOrKillIt() - process didn't stop, force killing");
  448. if (::kill(pid, SIGKILL) != -1)
  449. {
  450. // wait for killing to take place
  451. waitForChildToStop(pid, timeOutMilliseconds, false);
  452. }
  453. else
  454. {
  455. String error(std::strerror(errno));
  456. carla_stderr("waitForChildToStopOrKillIt() - kill failed: %s", error.buffer());
  457. }
  458. }
  459. }
  460. #endif
  461. // -----------------------------------------------------------------------
  462. struct CarlaPipeCommon::PrivateData {
  463. // pipes
  464. #ifdef CARLA_OS_WIN
  465. PROCESS_INFORMATION processInfo;
  466. HANDLE pipeRecv;
  467. HANDLE pipeSend;
  468. HANDLE ovRecv;
  469. HANDLE ovSend;
  470. #else
  471. pid_t pid;
  472. int pipeRecv;
  473. int pipeSend;
  474. #endif
  475. // read functions must only be called in context of idlePipe()
  476. bool isReading;
  477. // the client side is closing down, only waiting for response from server
  478. bool clientClosingDown;
  479. // other side of pipe has closed
  480. bool pipeClosed;
  481. // print error only once
  482. bool lastMessageFailed;
  483. // for debugging
  484. bool isServer;
  485. // common write lock
  486. CarlaMutex writeLock;
  487. // temporary buffers for _readline()
  488. mutable char tmpBuf[0xffff];
  489. mutable String tmpStr;
  490. PrivateData() noexcept
  491. #ifdef CARLA_OS_WIN
  492. : processInfo(),
  493. #else
  494. : pid(-1),
  495. #endif
  496. pipeRecv(INVALID_PIPE_VALUE),
  497. pipeSend(INVALID_PIPE_VALUE),
  498. isReading(false),
  499. clientClosingDown(false),
  500. pipeClosed(true),
  501. lastMessageFailed(false),
  502. isServer(false),
  503. writeLock(),
  504. tmpBuf(),
  505. tmpStr()
  506. {
  507. #ifdef CARLA_OS_WIN
  508. carla_zeroStruct(processInfo);
  509. processInfo.hProcess = INVALID_HANDLE_VALUE;
  510. processInfo.hThread = INVALID_HANDLE_VALUE;
  511. ovRecv = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
  512. ovSend = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
  513. #endif
  514. carla_zeroChars(tmpBuf, 0xffff);
  515. }
  516. CARLA_DECLARE_NON_COPYABLE(PrivateData)
  517. };
  518. // -----------------------------------------------------------------------
  519. CarlaPipeCommon::CarlaPipeCommon() noexcept
  520. : pData(new PrivateData())
  521. {
  522. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  523. }
  524. CarlaPipeCommon::~CarlaPipeCommon() /*noexcept*/
  525. {
  526. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  527. delete pData;
  528. }
  529. // -------------------------------------------------------------------
  530. bool CarlaPipeCommon::isPipeRunning() const noexcept
  531. {
  532. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed);
  533. }
  534. void CarlaPipeCommon::idlePipe(const bool onlyOnce) noexcept
  535. {
  536. bool readSucess;
  537. for (;;)
  538. {
  539. readSucess = false;
  540. const char* const msg = _readline(true, 0, readSucess);
  541. if (! readSucess)
  542. break;
  543. if (msg == nullptr)
  544. continue;
  545. pData->isReading = true;
  546. if (std::strcmp(msg, "__carla-quit__") == 0)
  547. {
  548. pData->pipeClosed = true;
  549. }
  550. else if (! pData->clientClosingDown)
  551. {
  552. try {
  553. msgReceived(msg);
  554. } CARLA_SAFE_EXCEPTION("msgReceived");
  555. }
  556. pData->isReading = false;
  557. std::free(const_cast<char*>(msg));
  558. if (onlyOnce || pData->pipeRecv == INVALID_PIPE_VALUE)
  559. break;
  560. }
  561. }
  562. // -------------------------------------------------------------------
  563. void CarlaPipeCommon::lockPipe() const noexcept
  564. {
  565. pData->writeLock.lock();
  566. }
  567. bool CarlaPipeCommon::tryLockPipe() const noexcept
  568. {
  569. return pData->writeLock.tryLock();
  570. }
  571. void CarlaPipeCommon::unlockPipe() const noexcept
  572. {
  573. pData->writeLock.unlock();
  574. }
  575. CarlaMutex& CarlaPipeCommon::getPipeLock() const noexcept
  576. {
  577. return pData->writeLock;
  578. }
  579. // -------------------------------------------------------------------
  580. bool CarlaPipeCommon::readNextLineAsBool(bool& value) const noexcept
  581. {
  582. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  583. if (const char* const msg = _readlineblock(false))
  584. {
  585. value = (std::strcmp(msg, "true") == 0);
  586. return true;
  587. }
  588. return false;
  589. }
  590. bool CarlaPipeCommon::readNextLineAsByte(uint8_t& value) const noexcept
  591. {
  592. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  593. if (const char* const msg = _readlineblock(false))
  594. {
  595. const int asint = std::atoi(msg);
  596. if (asint >= 0 && asint <= 0xFF)
  597. {
  598. value = static_cast<uint8_t>(asint);
  599. return true;
  600. }
  601. }
  602. return false;
  603. }
  604. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) const noexcept
  605. {
  606. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  607. if (const char* const msg = _readlineblock(false))
  608. {
  609. value = std::atoi(msg);
  610. return true;
  611. }
  612. return false;
  613. }
  614. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) const noexcept
  615. {
  616. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  617. if (const char* const msg = _readlineblock(false))
  618. {
  619. #if (defined(__WORDSIZE) && __WORDSIZE < 64) || (defined(__SIZE_WIDTH__) && __SIZE_WIDTH__ < 64) || \
  620. defined(CARLA_OS_WIN) || defined(CARLA_OS_MAC)
  621. const long long aslong = std::atoll(msg);
  622. #else
  623. const long aslong = std::atol(msg);
  624. #endif
  625. if (aslong >= 0)
  626. {
  627. value = static_cast<uint32_t>(aslong);
  628. return true;
  629. }
  630. }
  631. return false;
  632. }
  633. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) const noexcept
  634. {
  635. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  636. if (const char* const msg = _readlineblock(false))
  637. {
  638. value = std::atol(msg);
  639. return true;
  640. }
  641. return false;
  642. }
  643. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) const noexcept
  644. {
  645. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  646. if (const char* const msg = _readlineblock(false))
  647. {
  648. const int64_t asint64 = std::atol(msg);
  649. if (asint64 >= 0)
  650. {
  651. value = static_cast<uint64_t>(asint64);
  652. return true;
  653. }
  654. }
  655. return false;
  656. }
  657. bool CarlaPipeCommon::readNextLineAsFloat(float& value) const noexcept
  658. {
  659. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  660. if (const char* const msg = _readlineblock(false))
  661. {
  662. {
  663. const ScopedSafeLocale ssl;
  664. value = static_cast<float>(std::atof(msg));
  665. }
  666. return true;
  667. }
  668. return false;
  669. }
  670. bool CarlaPipeCommon::readNextLineAsDouble(double& value) const noexcept
  671. {
  672. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  673. if (const char* const msg = _readlineblock(false))
  674. {
  675. {
  676. const ScopedSafeLocale ssl;
  677. value = std::atof(msg);
  678. }
  679. return true;
  680. }
  681. return false;
  682. }
  683. bool CarlaPipeCommon::readNextLineAsString(const char*& value, const bool allocateString, uint32_t size) const noexcept
  684. {
  685. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  686. if (size >= 0xffff)
  687. size = 0;
  688. if (const char* const msg = _readlineblock(allocateString, static_cast<uint16_t>(size)))
  689. {
  690. value = msg;
  691. return true;
  692. }
  693. return false;
  694. }
  695. char* CarlaPipeCommon::readNextLineAsString() const noexcept
  696. {
  697. CARLA_SAFE_ASSERT_RETURN(pData->isReading, nullptr);
  698. return const_cast<char*>(_readlineblock(true, 0));
  699. }
  700. // -------------------------------------------------------------------
  701. // must be locked before calling
  702. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  703. {
  704. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  705. if (pData->pipeClosed)
  706. return false;
  707. const std::size_t size(std::strlen(msg));
  708. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  709. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  710. return _writeMsgBuffer(msg, size);
  711. }
  712. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  713. {
  714. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  715. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  716. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  717. if (pData->pipeClosed)
  718. return false;
  719. return _writeMsgBuffer(msg, size);
  720. }
  721. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  722. {
  723. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  724. if (pData->pipeClosed)
  725. return false;
  726. const std::size_t size(std::strlen(msg));
  727. char* const fixedMsg = static_cast<char*>(std::malloc(size+2));
  728. CARLA_SAFE_ASSERT_RETURN(fixedMsg != nullptr, false);
  729. if (size > 0)
  730. {
  731. std::strcpy(fixedMsg, msg);
  732. for (std::size_t i=0; i<size; ++i)
  733. {
  734. if (fixedMsg[i] == '\n')
  735. fixedMsg[i] = '\r';
  736. }
  737. if (fixedMsg[size-1] == '\r')
  738. {
  739. fixedMsg[size-1] = '\n';
  740. fixedMsg[size ] = '\0';
  741. fixedMsg[size+1] = '\0';
  742. }
  743. else
  744. {
  745. fixedMsg[size ] = '\n';
  746. fixedMsg[size+1] = '\0';
  747. }
  748. }
  749. else
  750. {
  751. fixedMsg[0] = '\n';
  752. fixedMsg[1] = '\0';
  753. }
  754. const bool ret = _writeMsgBuffer(fixedMsg, size+1);
  755. std::free(fixedMsg);
  756. return ret;
  757. }
  758. bool CarlaPipeCommon::writeEmptyMessage() const noexcept
  759. {
  760. if (pData->pipeClosed)
  761. return false;
  762. return _writeMsgBuffer("\n", 1);
  763. }
  764. bool CarlaPipeCommon::syncMessages() const noexcept
  765. {
  766. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  767. #if defined(CARLA_OS_LINUX) || defined(CARLA_OS_GNU_HURD)
  768. # if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2014
  769. // the only call that seems to do something
  770. return ::syncfs(pData->pipeSend) == 0;
  771. # endif
  772. #elif 0 // defined(CARLA_OS_WIN)
  773. // FIXME causes issues
  774. try {
  775. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  776. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  777. #endif
  778. return true;
  779. }
  780. // -------------------------------------------------------------------
  781. bool CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  782. {
  783. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0', false);
  784. const CarlaMutexLocker cml(pData->writeLock);
  785. if (! _writeMsgBuffer("error\n", 6))
  786. return false;
  787. if (! writeAndFixMessage(error))
  788. return false;
  789. syncMessages();
  790. return true;
  791. }
  792. bool CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value, const bool withWriteLock) const noexcept
  793. {
  794. if (withWriteLock)
  795. {
  796. const CarlaMutexLocker cml(pData->writeLock);
  797. return writeControlMessage(index, value, false);
  798. }
  799. char tmpBuf[0xff];
  800. tmpBuf[0xfe] = '\0';
  801. if (! _writeMsgBuffer("control\n", 8))
  802. return false;
  803. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  804. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  805. return false;
  806. {
  807. const ScopedSafeLocale ssl;
  808. std::snprintf(tmpBuf, 0xfe, "%.12g\n", static_cast<double>(value));
  809. }
  810. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  811. return false;
  812. syncMessages();
  813. return true;
  814. }
  815. bool CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  816. {
  817. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0', false);
  818. CARLA_SAFE_ASSERT_RETURN(value != nullptr, false);
  819. const CarlaMutexLocker cml(pData->writeLock);
  820. if (! _writeMsgBuffer("configure\n", 10))
  821. return false;
  822. if (! writeAndFixMessage(key))
  823. return false;
  824. if (! writeAndFixMessage(value))
  825. return false;
  826. syncMessages();
  827. return true;
  828. }
  829. bool CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  830. {
  831. char tmpBuf[0xff];
  832. tmpBuf[0xfe] = '\0';
  833. const CarlaMutexLocker cml(pData->writeLock);
  834. if (! _writeMsgBuffer("program\n", 8))
  835. return false;
  836. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  837. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  838. return false;
  839. syncMessages();
  840. return true;
  841. }
  842. bool CarlaPipeCommon::writeProgramMessage(const uint8_t channel, const uint32_t bank, const uint32_t program) const noexcept
  843. {
  844. char tmpBuf[0xff];
  845. tmpBuf[0xfe] = '\0';
  846. const CarlaMutexLocker cml(pData->writeLock);
  847. if (! _writeMsgBuffer("program\n", 8))
  848. return false;
  849. std::snprintf(tmpBuf, 0xfe, "%i\n", channel);
  850. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  851. return false;
  852. std::snprintf(tmpBuf, 0xfe, "%i\n", bank);
  853. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  854. return false;
  855. std::snprintf(tmpBuf, 0xfe, "%i\n", program);
  856. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  857. return false;
  858. syncMessages();
  859. return true;
  860. }
  861. bool CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  862. {
  863. char tmpBuf[0xff];
  864. tmpBuf[0xfe] = '\0';
  865. const CarlaMutexLocker cml(pData->writeLock);
  866. if (! _writeMsgBuffer("midiprogram\n", 12))
  867. return false;
  868. std::snprintf(tmpBuf, 0xfe, "%i\n", bank);
  869. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  870. return false;
  871. std::snprintf(tmpBuf, 0xfe, "%i\n", program);
  872. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  873. return false;
  874. syncMessages();
  875. return true;
  876. }
  877. bool CarlaPipeCommon::writeReloadProgramsMessage(const int32_t index) const noexcept
  878. {
  879. char tmpBuf[0xff];
  880. tmpBuf[0xfe] = '\0';
  881. const CarlaMutexLocker cml(pData->writeLock);
  882. if (! _writeMsgBuffer("reloadprograms\n", 15))
  883. return false;
  884. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  885. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  886. return false;
  887. syncMessages();
  888. return true;
  889. }
  890. bool CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  891. {
  892. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  893. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE, false);
  894. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE, false);
  895. char tmpBuf[0xff];
  896. tmpBuf[0xfe] = '\0';
  897. const CarlaMutexLocker cml(pData->writeLock);
  898. if (! _writeMsgBuffer("note\n", 5))
  899. return false;
  900. std::snprintf(tmpBuf, 0xfe, "%s\n", bool2str(onOff));
  901. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  902. return false;
  903. std::snprintf(tmpBuf, 0xfe, "%i\n", channel);
  904. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  905. return false;
  906. std::snprintf(tmpBuf, 0xfe, "%i\n", note);
  907. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  908. return false;
  909. std::snprintf(tmpBuf, 0xfe, "%i\n", velocity);
  910. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  911. return false;
  912. syncMessages();
  913. return true;
  914. }
  915. bool CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  916. {
  917. CARLA_SAFE_ASSERT_RETURN(atom != nullptr, false);
  918. char tmpBuf[0xff];
  919. tmpBuf[0xfe] = '\0';
  920. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  921. String base64atom(String::asBase64(atom, atomTotalSize));
  922. const CarlaMutexLocker cml(pData->writeLock);
  923. if (! _writeMsgBuffer("atom\n", 5))
  924. return false;
  925. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  926. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  927. return false;
  928. std::snprintf(tmpBuf, 0xfe, "%i\n", atomTotalSize);
  929. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  930. return false;
  931. std::snprintf(tmpBuf, 0xfe, "%lu\n", static_cast<long unsigned>(base64atom.length()));
  932. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  933. return false;
  934. if (! writeAndFixMessage(base64atom.buffer()))
  935. return false;
  936. syncMessages();
  937. return true;
  938. }
  939. bool CarlaPipeCommon::writeLv2ParameterMessage(const char* const uri, const float value, const bool withWriteLock) const noexcept
  940. {
  941. if (withWriteLock)
  942. {
  943. const CarlaMutexLocker cml(pData->writeLock);
  944. return writeLv2ParameterMessage(uri, value, false);
  945. }
  946. char tmpBuf[0xff];
  947. tmpBuf[0xfe] = '\0';
  948. if (! _writeMsgBuffer("parameter\n", 10))
  949. return false;
  950. if (! writeAndFixMessage(uri))
  951. return false;
  952. {
  953. const ScopedSafeLocale ssl;
  954. std::snprintf(tmpBuf, 0xfe, "%.12g\n", static_cast<double>(value));
  955. }
  956. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  957. return false;
  958. syncMessages();
  959. return true;
  960. }
  961. bool CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  962. {
  963. CARLA_SAFE_ASSERT_RETURN(urid != 0, false);
  964. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', false);
  965. char tmpBuf[0xff];
  966. tmpBuf[0xfe] = '\0';
  967. const CarlaMutexLocker cml(pData->writeLock);
  968. if (! _writeMsgBuffer("urid\n", 5))
  969. return false;
  970. std::snprintf(tmpBuf, 0xfe, "%i\n", urid);
  971. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  972. return false;
  973. std::snprintf(tmpBuf, 0xfe, "%lu\n", static_cast<long unsigned>(std::strlen(uri)));
  974. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  975. return false;
  976. if (! writeAndFixMessage(uri))
  977. return false;
  978. syncMessages();
  979. return true;
  980. }
  981. // -------------------------------------------------------------------
  982. // internal
  983. const char* CarlaPipeCommon::_readline(const bool allocReturn, const uint16_t size, bool& readSucess) const noexcept
  984. {
  985. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  986. char c;
  987. char* ptr = pData->tmpBuf;
  988. ssize_t ret = -1;
  989. bool tooBig = false;
  990. pData->tmpStr.clear();
  991. if (size == 0 || size == 1)
  992. {
  993. for (int i=0; i<0xfffe; ++i)
  994. {
  995. try {
  996. #ifdef CARLA_OS_WIN
  997. ret = ReadFileWin32(pData->pipeRecv, pData->ovRecv, &c, 1);
  998. #else
  999. ret = ::read(pData->pipeRecv, &c, 1);
  1000. #endif
  1001. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  1002. if (ret != 1)
  1003. break;
  1004. if (c == '\n')
  1005. {
  1006. *ptr = '\0';
  1007. break;
  1008. }
  1009. if (c == '\r')
  1010. c = '\n';
  1011. *ptr++ = c;
  1012. if (i+1 == 0xfffe)
  1013. {
  1014. i = 0;
  1015. *ptr = '\0';
  1016. tooBig = true;
  1017. pData->tmpStr += pData->tmpBuf;
  1018. ptr = pData->tmpBuf;
  1019. }
  1020. }
  1021. }
  1022. else
  1023. {
  1024. uint16_t remaining = size;
  1025. readSucess = false;
  1026. for (;;)
  1027. {
  1028. try {
  1029. #ifdef CARLA_OS_WIN
  1030. ret = ReadFileWin32(pData->pipeRecv, pData->ovRecv, ptr, remaining);
  1031. #else
  1032. ret = ::read(pData->pipeRecv, ptr, remaining);
  1033. #endif
  1034. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - read", nullptr);
  1035. if (ret == -1 && errno == EAGAIN)
  1036. continue;
  1037. CARLA_SAFE_ASSERT_INT2_RETURN(ret > 0, ret, remaining, nullptr);
  1038. CARLA_SAFE_ASSERT_INT2_RETURN(ret <= (ssize_t)remaining, ret, remaining, nullptr);
  1039. for (ssize_t i=0; i<ret; ++i)
  1040. {
  1041. if (ptr[i] == '\r')
  1042. ptr[i] = '\n';
  1043. }
  1044. ptr += ret;
  1045. *ptr = '\0';
  1046. remaining = static_cast<uint16_t>(remaining - ret);
  1047. if (remaining != 0)
  1048. continue;
  1049. readSucess = true;
  1050. if (allocReturn)
  1051. {
  1052. pData->tmpStr = pData->tmpBuf;
  1053. return pData->tmpStr.getAndReleaseBuffer();
  1054. }
  1055. return pData->tmpBuf;
  1056. }
  1057. }
  1058. if (ptr != pData->tmpBuf)
  1059. {
  1060. *ptr = '\0';
  1061. if (! allocReturn && ! tooBig)
  1062. {
  1063. readSucess = true;
  1064. return pData->tmpBuf;
  1065. }
  1066. pData->tmpStr += pData->tmpBuf;
  1067. }
  1068. else if (pData->tmpStr.isEmpty() && ret != 1)
  1069. {
  1070. // some error
  1071. return nullptr;
  1072. }
  1073. readSucess = true;
  1074. if (! allocReturn && ! tooBig)
  1075. return pData->tmpBuf;
  1076. return allocReturn ? pData->tmpStr.getAndReleaseBuffer() : pData->tmpStr.buffer();
  1077. }
  1078. const char* CarlaPipeCommon::_readlineblock(const bool allocReturn,
  1079. const uint16_t size,
  1080. const uint32_t timeOutMilliseconds) const noexcept
  1081. {
  1082. const uint32_t timeoutEnd = d_gettime_ms() + timeOutMilliseconds;
  1083. bool readSucess;
  1084. for (;;)
  1085. {
  1086. readSucess = false;
  1087. const char* const msg = _readline(allocReturn, size, readSucess);
  1088. if (readSucess)
  1089. return msg;
  1090. if (d_gettime_ms() >= timeoutEnd)
  1091. break;
  1092. d_msleep(5);
  1093. }
  1094. static const bool testingForValgrind = std::getenv("CARLA_VALGRIND_TEST") != nullptr;
  1095. if (testingForValgrind)
  1096. {
  1097. const uint32_t timeoutEnd2 = d_gettime_ms() + 1000;
  1098. for (;;)
  1099. {
  1100. readSucess = false;
  1101. const char* const msg = _readline(allocReturn, size, readSucess);
  1102. if (readSucess)
  1103. return msg;
  1104. if (d_gettime_ms() >= timeoutEnd2)
  1105. break;
  1106. d_msleep(100);
  1107. }
  1108. }
  1109. carla_stderr("readlineblock timed out");
  1110. return nullptr;
  1111. }
  1112. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  1113. {
  1114. if (pData->pipeClosed)
  1115. return false;
  1116. if (pData->pipeSend == INVALID_PIPE_VALUE)
  1117. {
  1118. carla_stderr2("CarlaPipe write error, isServer:%s, message was:\n%s", bool2str(pData->isServer), msg);
  1119. return false;
  1120. }
  1121. ssize_t ret;
  1122. try {
  1123. #ifdef CARLA_OS_WIN
  1124. ret = WriteFileWin32(pData->pipeSend, pData->ovSend, msg, static_cast<DWORD>(size));
  1125. #else
  1126. ret = ::write(pData->pipeSend, msg, size);
  1127. #endif
  1128. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  1129. #ifdef CARLA_OS_WIN
  1130. if (ret == -2)
  1131. {
  1132. pData->pipeClosed = true;
  1133. return false;
  1134. }
  1135. #endif
  1136. if (ret == static_cast<ssize_t>(size))
  1137. {
  1138. if (pData->lastMessageFailed)
  1139. pData->lastMessageFailed = false;
  1140. return true;
  1141. }
  1142. if (! pData->lastMessageFailed)
  1143. {
  1144. pData->lastMessageFailed = true;
  1145. fprintf(stderr,
  1146. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE " (%s), message was:\n%s",
  1147. size, ret, bool2str(pData->isServer), msg);
  1148. }
  1149. return false;
  1150. }
  1151. // -----------------------------------------------------------------------
  1152. CarlaPipeServer::CarlaPipeServer() noexcept
  1153. : CarlaPipeCommon()
  1154. {
  1155. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  1156. pData->isServer = true;
  1157. }
  1158. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  1159. {
  1160. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  1161. stopPipeServer(5*1000);
  1162. }
  1163. uintptr_t CarlaPipeServer::getPID() const noexcept
  1164. {
  1165. #ifndef CARLA_OS_WIN
  1166. return static_cast<uintptr_t>(pData->pid);
  1167. #else
  1168. return 0;
  1169. #endif
  1170. }
  1171. // --------------------------------------------------------------------------------------------------------------------
  1172. bool CarlaPipeServer::startPipeServer(const char* const helperTool,
  1173. const char* const filename,
  1174. const char* const arg1,
  1175. const char* const arg2,
  1176. const int size,
  1177. int timeOutMilliseconds) noexcept
  1178. {
  1179. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1180. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1181. #ifdef CARLA_OS_WIN
  1182. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  1183. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  1184. #else
  1185. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  1186. #endif
  1187. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  1188. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  1189. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  1190. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  1191. if (timeOutMilliseconds < 0)
  1192. timeOutMilliseconds = 10 * 1000;
  1193. char pipeRecvServerStr[100+1];
  1194. char pipeSendServerStr[100+1];
  1195. char pipeRecvClientStr[100+1];
  1196. char pipeSendClientStr[100+1];
  1197. pipeRecvServerStr[100] = '\0';
  1198. pipeSendServerStr[100] = '\0';
  1199. pipeRecvClientStr[100] = '\0';
  1200. pipeSendClientStr[100] = '\0';
  1201. const CarlaMutexLocker cml(pData->writeLock);
  1202. //-----------------------------------------------------------------------------------------------------------------
  1203. // create pipes
  1204. #ifdef CARLA_OS_WIN
  1205. HANDLE pipe1, pipe2;
  1206. std::srand(static_cast<uint>(std::time(nullptr)));
  1207. static ulong sCounter = 0;
  1208. ++sCounter;
  1209. const int randint = std::rand();
  1210. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  1211. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  1212. std::snprintf(pipeRecvClientStr, 100, "ignored");
  1213. std::snprintf(pipeSendClientStr, 100, "ignored");
  1214. SECURITY_ATTRIBUTES sa;
  1215. carla_zeroStruct(sa);
  1216. sa.nLength = sizeof(sa);
  1217. sa.bInheritHandle = TRUE;
  1218. pipe1 = ::CreateNamedPipeA(pipeRecvServerStr, PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, 1, size, size, 0, &sa);
  1219. if (pipe1 == INVALID_HANDLE_VALUE)
  1220. {
  1221. fail("pipe creation failed");
  1222. return false;
  1223. }
  1224. pipe2 = ::CreateNamedPipeA(pipeSendServerStr, PIPE_ACCESS_DUPLEX|FILE_FLAG_FIRST_PIPE_INSTANCE|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, 1, size, size, 0, &sa);
  1225. if (pipe2 == INVALID_HANDLE_VALUE)
  1226. {
  1227. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1228. fail("pipe creation failed");
  1229. return false;
  1230. }
  1231. const HANDLE pipeRecvClient = pipe2;
  1232. const HANDLE pipeSendClient = pipe1;
  1233. #else
  1234. int pipe1[2]; // read by server, written by client
  1235. int pipe2[2]; // read by client, written by server
  1236. if (::pipe(pipe1) != 0)
  1237. {
  1238. fail("pipe1 creation failed");
  1239. return false;
  1240. }
  1241. if (::pipe(pipe2) != 0)
  1242. {
  1243. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1244. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1245. fail("pipe2 creation failed");
  1246. return false;
  1247. }
  1248. /* */ int pipeRecvServer = pipe1[0];
  1249. /* */ int pipeSendServer = pipe2[1];
  1250. const int pipeRecvClient = pipe2[0];
  1251. const int pipeSendClient = pipe1[1];
  1252. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  1253. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  1254. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  1255. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  1256. //-----------------------------------------------------------------------------------------------------------------
  1257. // set size, non-fatal
  1258. # ifdef CARLA_OS_LINUX
  1259. try {
  1260. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  1261. } CARLA_SAFE_EXCEPTION("Set pipe size");
  1262. try {
  1263. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  1264. } CARLA_SAFE_EXCEPTION("Set pipe size");
  1265. # endif
  1266. //-----------------------------------------------------------------------------------------------------------------
  1267. // set non-block
  1268. int ret;
  1269. try {
  1270. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  1271. } catch (...) {
  1272. ret = -1;
  1273. fail("failed to set pipe as non-block");
  1274. }
  1275. if (ret == 0)
  1276. {
  1277. try {
  1278. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  1279. } catch (...) {
  1280. ret = -1;
  1281. fail("failed to set pipe as non-block");
  1282. }
  1283. }
  1284. if (ret < 0)
  1285. {
  1286. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1287. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1288. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1289. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1290. return false;
  1291. }
  1292. #endif
  1293. //-----------------------------------------------------------------------------------------------------------------
  1294. // set arguments
  1295. const char* argv[9] = {};
  1296. int i = 0;
  1297. if (helperTool != nullptr)
  1298. argv[i++] = helperTool;
  1299. //-----------------------------------------------------------------------------------------------------------------
  1300. // argv[0] => filename
  1301. argv[i++] = filename;
  1302. //-----------------------------------------------------------------------------------------------------------------
  1303. // argv[1-2] => args
  1304. argv[i++] = arg1;
  1305. argv[i++] = arg2;
  1306. //-----------------------------------------------------------------------------------------------------------------
  1307. // argv[3-6] => pipes
  1308. argv[i++] = pipeRecvServerStr;
  1309. argv[i++] = pipeSendServerStr;
  1310. argv[i++] = pipeRecvClientStr;
  1311. argv[i++] = pipeSendClientStr;
  1312. //-----------------------------------------------------------------------------------------------------------------
  1313. // start process
  1314. #ifdef CARLA_OS_WIN
  1315. if (! startProcess(argv, &pData->processInfo))
  1316. {
  1317. carla_zeroStruct(pData->processInfo);
  1318. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1319. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1320. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1321. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  1322. return false;
  1323. }
  1324. // just to make sure
  1325. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1326. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1327. #else
  1328. if (! startProcess(argv, pData->pid))
  1329. {
  1330. pData->pid = -1;
  1331. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1332. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1333. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1334. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1335. fail("startProcess() failed");
  1336. return false;
  1337. }
  1338. //-----------------------------------------------------------------------------------------------------------------
  1339. // close duplicated handles used by the client
  1340. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1341. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1342. #endif
  1343. //-----------------------------------------------------------------------------------------------------------------
  1344. // wait for client to say something
  1345. #ifdef CARLA_OS_WIN
  1346. void* const ovRecv = pData->ovRecv;
  1347. void* const process = pData->processInfo.hProcess;
  1348. #else
  1349. void* const ovRecv = nullptr;
  1350. void* const process = nullptr;
  1351. #endif
  1352. if (waitForClientFirstMessage(pipeRecvClient, ovRecv, process, timeOutMilliseconds))
  1353. {
  1354. pData->pipeRecv = pipeRecvClient;
  1355. pData->pipeSend = pipeSendClient;
  1356. pData->pipeClosed = false;
  1357. carla_debug("ALL OK!");
  1358. return true;
  1359. }
  1360. //-----------------------------------------------------------------------------------------------------------------
  1361. // failed to set non-block or get first child message, cannot continue
  1362. #ifdef CARLA_OS_WIN
  1363. if (::TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1364. {
  1365. // wait for process to stop
  1366. waitForProcessToStop(pData->processInfo.hProcess, 2*1000, false);
  1367. }
  1368. // clear pData->processInfo
  1369. try { ::CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1370. try { ::CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1371. carla_zeroStruct(pData->processInfo);
  1372. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1373. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1374. #else
  1375. if (::kill(pData->pid, SIGKILL) != -1)
  1376. {
  1377. // wait for killing to take place
  1378. waitForChildToStop(pData->pid, 2*1000, false);
  1379. }
  1380. pData->pid = -1;
  1381. #endif
  1382. //-----------------------------------------------------------------------------------------------------------------
  1383. // close pipes
  1384. #ifdef CARLA_OS_WIN
  1385. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1386. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1387. #else
  1388. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1389. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1390. #endif
  1391. return false;
  1392. // maybe unused
  1393. (void)size; (void)ovRecv; (void)process;
  1394. }
  1395. bool CarlaPipeServer::startPipeServer(const char* const filename,
  1396. const char* const arg1,
  1397. const char* const arg2,
  1398. const int size,
  1399. const int timeOutMilliseconds) noexcept
  1400. {
  1401. return startPipeServer(nullptr, filename, arg1, arg2, size, timeOutMilliseconds);
  1402. }
  1403. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1404. {
  1405. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1406. #ifdef CARLA_OS_WIN
  1407. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1408. {
  1409. const CarlaMutexLocker cml(pData->writeLock);
  1410. if (pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed)
  1411. {
  1412. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1413. syncMessages();
  1414. }
  1415. waitForProcessToStopOrKillIt(pData->processInfo.hProcess, timeOutMilliseconds);
  1416. try { ::CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1417. try { ::CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1418. carla_zeroStruct(pData->processInfo);
  1419. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1420. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1421. }
  1422. #else
  1423. if (pData->pid != -1)
  1424. {
  1425. const CarlaMutexLocker cml(pData->writeLock);
  1426. if (pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed)
  1427. {
  1428. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1429. syncMessages();
  1430. }
  1431. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1432. pData->pid = -1;
  1433. }
  1434. #endif
  1435. closePipeServer();
  1436. }
  1437. void CarlaPipeServer::closePipeServer() noexcept
  1438. {
  1439. carla_debug("CarlaPipeServer::closePipeServer()");
  1440. pData->pipeClosed = true;
  1441. const CarlaMutexLocker cml(pData->writeLock);
  1442. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1443. {
  1444. #ifdef CARLA_OS_WIN
  1445. DisconnectNamedPipe(pData->pipeRecv);
  1446. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1447. #else
  1448. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1449. #endif
  1450. pData->pipeRecv = INVALID_PIPE_VALUE;
  1451. }
  1452. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1453. {
  1454. #ifdef CARLA_OS_WIN
  1455. DisconnectNamedPipe(pData->pipeSend);
  1456. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1457. #else
  1458. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1459. #endif
  1460. pData->pipeSend = INVALID_PIPE_VALUE;
  1461. }
  1462. }
  1463. void CarlaPipeServer::writeShowMessage() const noexcept
  1464. {
  1465. const CarlaMutexLocker cml(pData->writeLock);
  1466. if (! _writeMsgBuffer("show\n", 5))
  1467. return;
  1468. syncMessages();
  1469. }
  1470. void CarlaPipeServer::writeFocusMessage() const noexcept
  1471. {
  1472. const CarlaMutexLocker cml(pData->writeLock);
  1473. if (! _writeMsgBuffer("focus\n", 6))
  1474. return;
  1475. syncMessages();
  1476. }
  1477. void CarlaPipeServer::writeHideMessage() const noexcept
  1478. {
  1479. const CarlaMutexLocker cml(pData->writeLock);
  1480. if (! _writeMsgBuffer("show\n", 5))
  1481. return;
  1482. syncMessages();
  1483. }
  1484. // -----------------------------------------------------------------------
  1485. CarlaPipeClient::CarlaPipeClient() noexcept
  1486. : CarlaPipeCommon()
  1487. {
  1488. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1489. }
  1490. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1491. {
  1492. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1493. closePipeClient();
  1494. }
  1495. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1496. {
  1497. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1498. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1499. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1500. const CarlaMutexLocker cml(pData->writeLock);
  1501. //----------------------------------------------------------------
  1502. // read arguments
  1503. #ifdef CARLA_OS_WIN
  1504. const char* const pipeRecvServerStr = argv[3];
  1505. const char* const pipeSendServerStr = argv[4];
  1506. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1507. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1508. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1509. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1510. #else
  1511. const int pipeRecvServer = std::atoi(argv[3]);
  1512. const int pipeSendServer = std::atoi(argv[4]);
  1513. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1514. /* */ int pipeSendClient = std::atoi(argv[6]);
  1515. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1516. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1517. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1518. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1519. //----------------------------------------------------------------
  1520. // close duplicated handles used by the client
  1521. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1522. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1523. //----------------------------------------------------------------
  1524. // kill ourselves if parent dies
  1525. carla_terminateProcessOnParentExit(false);
  1526. #endif
  1527. //----------------------------------------------------------------
  1528. // done
  1529. pData->pipeRecv = pipeRecvServer;
  1530. pData->pipeSend = pipeSendServer;
  1531. pData->pipeClosed = false;
  1532. pData->clientClosingDown = false;
  1533. if (writeMessage("\n", 1))
  1534. syncMessages();
  1535. return true;
  1536. }
  1537. void CarlaPipeClient::closePipeClient() noexcept
  1538. {
  1539. carla_debug("CarlaPipeClient::closePipeClient()");
  1540. pData->pipeClosed = true;
  1541. const CarlaMutexLocker cml(pData->writeLock);
  1542. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1543. {
  1544. #ifdef CARLA_OS_WIN
  1545. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1546. #else
  1547. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1548. #endif
  1549. pData->pipeRecv = INVALID_PIPE_VALUE;
  1550. }
  1551. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1552. {
  1553. #ifdef CARLA_OS_WIN
  1554. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1555. #else
  1556. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1557. #endif
  1558. pData->pipeSend = INVALID_PIPE_VALUE;
  1559. }
  1560. }
  1561. void CarlaPipeClient::writeExitingMessageAndWait() noexcept
  1562. {
  1563. {
  1564. const CarlaMutexLocker cml(pData->writeLock);
  1565. if (_writeMsgBuffer("exiting\n", 8))
  1566. syncMessages();
  1567. }
  1568. // NOTE: no more messages are handled after this point
  1569. pData->clientClosingDown = true;
  1570. for (int i=0; i < 100 && ! pData->pipeClosed; ++i)
  1571. {
  1572. d_msleep(50);
  1573. idlePipe(true);
  1574. }
  1575. if (! pData->pipeClosed)
  1576. carla_stderr2("writeExitingMessageAndWait pipe is still running!");
  1577. }
  1578. // -----------------------------------------------------------------------
  1579. #undef INVALID_PIPE_VALUE