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.

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