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.

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