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.

1989 lines
54KB

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