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.

2006 lines
54KB

  1. /*
  2. * Carla Pipe Utilities
  3. * Copyright (C) 2013-2023 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 "CarlaTimeUtils.hpp"
  21. #include "CarlaMIDI.h"
  22. // needed for atom-util
  23. #ifndef nullptr
  24. # undef NULL
  25. # define NULL nullptr
  26. #endif
  27. #ifdef BUILDING_CARLA
  28. # include "lv2/atom-util.h"
  29. #else
  30. # include "lv2/atom/util.h"
  31. #endif
  32. #include <fcntl.h>
  33. #ifdef CARLA_OS_WIN
  34. # include "water/text/String.h"
  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 DWORD 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 DWORD 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 = carla_gettime_ms() + 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 (carla_gettime_ms() < 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 = carla_gettime_ms() + 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 (carla_gettime_ms() < 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 = carla_gettime_ms() + 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 (carla_gettime_ms() >= 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 = carla_gettime_ms() + 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 (carla_gettime_ms() < 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. char* CarlaPipeCommon::readNextLineAsString() const noexcept
  708. {
  709. CARLA_SAFE_ASSERT_RETURN(pData->isReading, nullptr);
  710. return const_cast<char*>(_readlineblock(true, 0));
  711. }
  712. // -------------------------------------------------------------------
  713. // must be locked before calling
  714. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  715. {
  716. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  717. if (pData->pipeClosed)
  718. return false;
  719. const std::size_t size(std::strlen(msg));
  720. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  721. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  722. return _writeMsgBuffer(msg, size);
  723. }
  724. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  725. {
  726. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  727. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  728. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  729. if (pData->pipeClosed)
  730. return false;
  731. return _writeMsgBuffer(msg, size);
  732. }
  733. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  734. {
  735. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  736. if (pData->pipeClosed)
  737. return false;
  738. const std::size_t size(std::strlen(msg));
  739. char* const fixedMsg = static_cast<char*>(std::malloc(size+2));
  740. CARLA_SAFE_ASSERT_RETURN(fixedMsg != nullptr, false);
  741. if (size > 0)
  742. {
  743. std::strcpy(fixedMsg, msg);
  744. for (std::size_t i=0; i<size; ++i)
  745. {
  746. if (fixedMsg[i] == '\n')
  747. fixedMsg[i] = '\r';
  748. }
  749. if (fixedMsg[size-1] == '\r')
  750. {
  751. fixedMsg[size-1] = '\n';
  752. fixedMsg[size ] = '\0';
  753. fixedMsg[size+1] = '\0';
  754. }
  755. else
  756. {
  757. fixedMsg[size ] = '\n';
  758. fixedMsg[size+1] = '\0';
  759. }
  760. }
  761. else
  762. {
  763. fixedMsg[0] = '\n';
  764. fixedMsg[1] = '\0';
  765. }
  766. const bool ret = _writeMsgBuffer(fixedMsg, size+1);
  767. std::free(fixedMsg);
  768. return ret;
  769. }
  770. bool CarlaPipeCommon::writeEmptyMessage() const noexcept
  771. {
  772. if (pData->pipeClosed)
  773. return false;
  774. return _writeMsgBuffer("\n", 1);
  775. }
  776. bool CarlaPipeCommon::syncMessages() const noexcept
  777. {
  778. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  779. #if defined(CARLA_OS_LINUX) || defined(CARLA_OS_GNU_HURD)
  780. # if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2014
  781. // the only call that seems to do something
  782. return ::syncfs(pData->pipeSend) == 0;
  783. # endif
  784. #elif 0 // defined(CARLA_OS_WIN)
  785. // FIXME causes issues
  786. try {
  787. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  788. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  789. #endif
  790. return true;
  791. }
  792. // -------------------------------------------------------------------
  793. bool CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  794. {
  795. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0', false);
  796. const CarlaMutexLocker cml(pData->writeLock);
  797. if (! _writeMsgBuffer("error\n", 6))
  798. return false;
  799. if (! writeAndFixMessage(error))
  800. return false;
  801. syncMessages();
  802. return true;
  803. }
  804. bool CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value, const bool withWriteLock) const noexcept
  805. {
  806. if (withWriteLock)
  807. {
  808. const CarlaMutexLocker cml(pData->writeLock);
  809. return writeControlMessage(index, value, false);
  810. }
  811. char tmpBuf[0xff];
  812. tmpBuf[0xfe] = '\0';
  813. if (! _writeMsgBuffer("control\n", 8))
  814. return false;
  815. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  816. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  817. return false;
  818. {
  819. const CarlaScopedLocale csl;
  820. std::snprintf(tmpBuf, 0xfe, "%.12g\n", static_cast<double>(value));
  821. }
  822. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  823. return false;
  824. syncMessages();
  825. return true;
  826. }
  827. bool CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  828. {
  829. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0', false);
  830. CARLA_SAFE_ASSERT_RETURN(value != nullptr, false);
  831. const CarlaMutexLocker cml(pData->writeLock);
  832. if (! _writeMsgBuffer("configure\n", 10))
  833. return false;
  834. if (! writeAndFixMessage(key))
  835. return false;
  836. if (! writeAndFixMessage(value))
  837. return false;
  838. syncMessages();
  839. return true;
  840. }
  841. bool CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  842. {
  843. char tmpBuf[0xff];
  844. tmpBuf[0xfe] = '\0';
  845. const CarlaMutexLocker cml(pData->writeLock);
  846. if (! _writeMsgBuffer("program\n", 8))
  847. return false;
  848. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  849. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  850. return false;
  851. syncMessages();
  852. return true;
  853. }
  854. bool CarlaPipeCommon::writeProgramMessage(const uint8_t channel, const uint32_t bank, const uint32_t program) const noexcept
  855. {
  856. char tmpBuf[0xff];
  857. tmpBuf[0xfe] = '\0';
  858. const CarlaMutexLocker cml(pData->writeLock);
  859. if (! _writeMsgBuffer("program\n", 8))
  860. return false;
  861. std::snprintf(tmpBuf, 0xfe, "%i\n", channel);
  862. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  863. return false;
  864. std::snprintf(tmpBuf, 0xfe, "%i\n", bank);
  865. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  866. return false;
  867. std::snprintf(tmpBuf, 0xfe, "%i\n", program);
  868. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  869. return false;
  870. syncMessages();
  871. return true;
  872. }
  873. bool CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  874. {
  875. char tmpBuf[0xff];
  876. tmpBuf[0xfe] = '\0';
  877. const CarlaMutexLocker cml(pData->writeLock);
  878. if (! _writeMsgBuffer("midiprogram\n", 12))
  879. return false;
  880. std::snprintf(tmpBuf, 0xfe, "%i\n", bank);
  881. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  882. return false;
  883. std::snprintf(tmpBuf, 0xfe, "%i\n", program);
  884. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  885. return false;
  886. syncMessages();
  887. return true;
  888. }
  889. bool CarlaPipeCommon::writeReloadProgramsMessage(const int32_t index) const noexcept
  890. {
  891. char tmpBuf[0xff];
  892. tmpBuf[0xfe] = '\0';
  893. const CarlaMutexLocker cml(pData->writeLock);
  894. if (! _writeMsgBuffer("reloadprograms\n", 15))
  895. return false;
  896. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  897. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  898. return false;
  899. syncMessages();
  900. return true;
  901. }
  902. bool CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  903. {
  904. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS, false);
  905. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE, false);
  906. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE, false);
  907. char tmpBuf[0xff];
  908. tmpBuf[0xfe] = '\0';
  909. const CarlaMutexLocker cml(pData->writeLock);
  910. if (! _writeMsgBuffer("note\n", 5))
  911. return false;
  912. std::snprintf(tmpBuf, 0xfe, "%s\n", bool2str(onOff));
  913. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  914. return false;
  915. std::snprintf(tmpBuf, 0xfe, "%i\n", channel);
  916. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  917. return false;
  918. std::snprintf(tmpBuf, 0xfe, "%i\n", note);
  919. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  920. return false;
  921. std::snprintf(tmpBuf, 0xfe, "%i\n", velocity);
  922. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  923. return false;
  924. syncMessages();
  925. return true;
  926. }
  927. bool CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  928. {
  929. CARLA_SAFE_ASSERT_RETURN(atom != nullptr, false);
  930. char tmpBuf[0xff];
  931. tmpBuf[0xfe] = '\0';
  932. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  933. CarlaString base64atom(CarlaString::asBase64(atom, atomTotalSize));
  934. const CarlaMutexLocker cml(pData->writeLock);
  935. if (! _writeMsgBuffer("atom\n", 5))
  936. return false;
  937. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  938. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  939. return false;
  940. std::snprintf(tmpBuf, 0xfe, "%i\n", atomTotalSize);
  941. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  942. return false;
  943. std::snprintf(tmpBuf, 0xfe, "%lu\n", static_cast<long unsigned>(base64atom.length()));
  944. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  945. return false;
  946. if (! writeAndFixMessage(base64atom.buffer()))
  947. return false;
  948. syncMessages();
  949. return true;
  950. }
  951. bool CarlaPipeCommon::writeLv2ParameterMessage(const char* const uri, const float value, const bool withWriteLock) const noexcept
  952. {
  953. if (withWriteLock)
  954. {
  955. const CarlaMutexLocker cml(pData->writeLock);
  956. return writeLv2ParameterMessage(uri, value, false);
  957. }
  958. char tmpBuf[0xff];
  959. tmpBuf[0xfe] = '\0';
  960. if (! _writeMsgBuffer("parameter\n", 10))
  961. return false;
  962. if (! writeAndFixMessage(uri))
  963. return false;
  964. {
  965. const CarlaScopedLocale csl;
  966. std::snprintf(tmpBuf, 0xfe, "%.12g\n", static_cast<double>(value));
  967. }
  968. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  969. return false;
  970. syncMessages();
  971. return true;
  972. }
  973. bool CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  974. {
  975. CARLA_SAFE_ASSERT_RETURN(urid != 0, false);
  976. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0', false);
  977. char tmpBuf[0xff];
  978. tmpBuf[0xfe] = '\0';
  979. const CarlaMutexLocker cml(pData->writeLock);
  980. if (! _writeMsgBuffer("urid\n", 5))
  981. return false;
  982. std::snprintf(tmpBuf, 0xfe, "%i\n", urid);
  983. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  984. return false;
  985. std::snprintf(tmpBuf, 0xfe, "%lu\n", static_cast<long unsigned>(std::strlen(uri)));
  986. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  987. return false;
  988. if (! writeAndFixMessage(uri))
  989. return false;
  990. syncMessages();
  991. return true;
  992. }
  993. // -------------------------------------------------------------------
  994. // internal
  995. const char* CarlaPipeCommon::_readline(const bool allocReturn, const uint16_t size, bool& readSucess) const noexcept
  996. {
  997. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  998. char c;
  999. char* ptr = pData->tmpBuf;
  1000. ssize_t ret = -1;
  1001. bool tooBig = false;
  1002. pData->tmpStr.clear();
  1003. if (size == 0 || size == 1)
  1004. {
  1005. for (int i=0; i<0xfffe; ++i)
  1006. {
  1007. try {
  1008. #ifdef CARLA_OS_WIN
  1009. ret = ReadFileWin32(pData->pipeRecv, pData->ovRecv, &c, 1);
  1010. #else
  1011. ret = ::read(pData->pipeRecv, &c, 1);
  1012. #endif
  1013. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  1014. if (ret != 1)
  1015. break;
  1016. if (c == '\n')
  1017. {
  1018. *ptr = '\0';
  1019. break;
  1020. }
  1021. if (c == '\r')
  1022. c = '\n';
  1023. *ptr++ = c;
  1024. if (i+1 == 0xfffe)
  1025. {
  1026. i = 0;
  1027. *ptr = '\0';
  1028. tooBig = true;
  1029. pData->tmpStr += pData->tmpBuf;
  1030. ptr = pData->tmpBuf;
  1031. }
  1032. }
  1033. }
  1034. else
  1035. {
  1036. uint16_t remaining = size;
  1037. readSucess = false;
  1038. for (;;)
  1039. {
  1040. try {
  1041. #ifdef CARLA_OS_WIN
  1042. ret = ReadFileWin32(pData->pipeRecv, pData->ovRecv, ptr, remaining);
  1043. #else
  1044. ret = ::read(pData->pipeRecv, ptr, remaining);
  1045. #endif
  1046. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - read", nullptr);
  1047. if (ret == -1 && errno == EAGAIN)
  1048. continue;
  1049. CARLA_SAFE_ASSERT_INT2_RETURN(ret > 0, ret, remaining, nullptr);
  1050. CARLA_SAFE_ASSERT_INT2_RETURN(ret <= (ssize_t)remaining, ret, remaining, nullptr);
  1051. for (ssize_t i=0; i<ret; ++i)
  1052. {
  1053. if (ptr[i] == '\r')
  1054. ptr[i] = '\n';
  1055. }
  1056. ptr += ret;
  1057. *ptr = '\0';
  1058. remaining = static_cast<uint16_t>(remaining - ret);
  1059. if (remaining != 0)
  1060. continue;
  1061. readSucess = true;
  1062. if (allocReturn)
  1063. {
  1064. pData->tmpStr = pData->tmpBuf;
  1065. return pData->tmpStr.releaseBufferPointer();
  1066. }
  1067. return pData->tmpBuf;
  1068. }
  1069. }
  1070. if (ptr != pData->tmpBuf)
  1071. {
  1072. *ptr = '\0';
  1073. if (! allocReturn && ! tooBig)
  1074. {
  1075. readSucess = true;
  1076. return pData->tmpBuf;
  1077. }
  1078. pData->tmpStr += pData->tmpBuf;
  1079. }
  1080. else if (pData->tmpStr.isEmpty() && ret != 1)
  1081. {
  1082. // some error
  1083. return nullptr;
  1084. }
  1085. readSucess = true;
  1086. if (! allocReturn && ! tooBig)
  1087. return pData->tmpBuf;
  1088. return allocReturn ? pData->tmpStr.releaseBufferPointer() : pData->tmpStr.buffer();
  1089. }
  1090. const char* CarlaPipeCommon::_readlineblock(const bool allocReturn,
  1091. const uint16_t size,
  1092. const uint32_t timeOutMilliseconds) const noexcept
  1093. {
  1094. const uint32_t timeoutEnd = carla_gettime_ms() + timeOutMilliseconds;
  1095. bool readSucess;
  1096. for (;;)
  1097. {
  1098. readSucess = false;
  1099. const char* const msg = _readline(allocReturn, size, readSucess);
  1100. if (readSucess)
  1101. return msg;
  1102. if (carla_gettime_ms() >= timeoutEnd)
  1103. break;
  1104. carla_msleep(5);
  1105. }
  1106. static const bool testingForValgrind = std::getenv("CARLA_VALGRIND_TEST") != nullptr;
  1107. if (testingForValgrind)
  1108. {
  1109. const uint32_t timeoutEnd2 = carla_gettime_ms() + 1000;
  1110. for (;;)
  1111. {
  1112. readSucess = false;
  1113. const char* const msg = _readline(allocReturn, size, readSucess);
  1114. if (readSucess)
  1115. return msg;
  1116. if (carla_gettime_ms() >= timeoutEnd2)
  1117. break;
  1118. carla_msleep(100);
  1119. }
  1120. }
  1121. carla_stderr("readlineblock timed out");
  1122. return nullptr;
  1123. }
  1124. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  1125. {
  1126. if (pData->pipeClosed)
  1127. return false;
  1128. if (pData->pipeSend == INVALID_PIPE_VALUE)
  1129. {
  1130. carla_stderr2("CarlaPipe write error, isServer:%s, message was:\n%s", bool2str(pData->isServer), msg);
  1131. return false;
  1132. }
  1133. ssize_t ret;
  1134. try {
  1135. #ifdef CARLA_OS_WIN
  1136. ret = WriteFileWin32(pData->pipeSend, pData->ovSend, msg, static_cast<DWORD>(size));
  1137. #else
  1138. ret = ::write(pData->pipeSend, msg, size);
  1139. #endif
  1140. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  1141. #ifdef CARLA_OS_WIN
  1142. if (ret == -2)
  1143. {
  1144. pData->pipeClosed = true;
  1145. return false;
  1146. }
  1147. #endif
  1148. if (ret == static_cast<ssize_t>(size))
  1149. {
  1150. if (pData->lastMessageFailed)
  1151. pData->lastMessageFailed = false;
  1152. return true;
  1153. }
  1154. if (! pData->lastMessageFailed)
  1155. {
  1156. pData->lastMessageFailed = true;
  1157. fprintf(stderr,
  1158. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE " (%s), message was:\n%s",
  1159. size, ret, bool2str(pData->isServer), msg);
  1160. }
  1161. return false;
  1162. }
  1163. // -----------------------------------------------------------------------
  1164. CarlaPipeServer::CarlaPipeServer() noexcept
  1165. : CarlaPipeCommon()
  1166. {
  1167. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  1168. pData->isServer = true;
  1169. }
  1170. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  1171. {
  1172. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  1173. stopPipeServer(5*1000);
  1174. }
  1175. uintptr_t CarlaPipeServer::getPID() const noexcept
  1176. {
  1177. #ifndef CARLA_OS_WIN
  1178. return static_cast<uintptr_t>(pData->pid);
  1179. #else
  1180. return 0;
  1181. #endif
  1182. }
  1183. // --------------------------------------------------------------------------------------------------------------------
  1184. bool CarlaPipeServer::startPipeServer(const char* const helperTool,
  1185. const char* const filename,
  1186. const char* const arg1,
  1187. const char* const arg2,
  1188. const int size) noexcept
  1189. {
  1190. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1191. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1192. #ifdef CARLA_OS_WIN
  1193. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  1194. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  1195. #else
  1196. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  1197. #endif
  1198. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  1199. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  1200. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  1201. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  1202. char pipeRecvServerStr[100+1];
  1203. char pipeSendServerStr[100+1];
  1204. char pipeRecvClientStr[100+1];
  1205. char pipeSendClientStr[100+1];
  1206. pipeRecvServerStr[100] = '\0';
  1207. pipeSendServerStr[100] = '\0';
  1208. pipeRecvClientStr[100] = '\0';
  1209. pipeSendClientStr[100] = '\0';
  1210. const CarlaMutexLocker cml(pData->writeLock);
  1211. //-----------------------------------------------------------------------------------------------------------------
  1212. // create pipes
  1213. #ifdef CARLA_OS_WIN
  1214. HANDLE pipe1, pipe2;
  1215. std::srand(static_cast<uint>(std::time(nullptr)));
  1216. static ulong sCounter = 0;
  1217. ++sCounter;
  1218. const int randint = std::rand();
  1219. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  1220. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  1221. std::snprintf(pipeRecvClientStr, 100, "ignored");
  1222. std::snprintf(pipeSendClientStr, 100, "ignored");
  1223. SECURITY_ATTRIBUTES sa;
  1224. carla_zeroStruct(sa);
  1225. sa.nLength = sizeof(sa);
  1226. sa.bInheritHandle = TRUE;
  1227. 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);
  1228. if (pipe1 == INVALID_HANDLE_VALUE)
  1229. {
  1230. fail("pipe creation failed");
  1231. return false;
  1232. }
  1233. 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);
  1234. if (pipe2 == INVALID_HANDLE_VALUE)
  1235. {
  1236. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1237. fail("pipe creation failed");
  1238. return false;
  1239. }
  1240. const HANDLE pipeRecvClient = pipe2;
  1241. const HANDLE pipeSendClient = pipe1;
  1242. #else
  1243. int pipe1[2]; // read by server, written by client
  1244. int pipe2[2]; // read by client, written by server
  1245. if (::pipe(pipe1) != 0)
  1246. {
  1247. fail("pipe1 creation failed");
  1248. return false;
  1249. }
  1250. if (::pipe(pipe2) != 0)
  1251. {
  1252. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1253. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1254. fail("pipe2 creation failed");
  1255. return false;
  1256. }
  1257. /* */ int pipeRecvServer = pipe1[0];
  1258. /* */ int pipeSendServer = pipe2[1];
  1259. const int pipeRecvClient = pipe2[0];
  1260. const int pipeSendClient = pipe1[1];
  1261. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  1262. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  1263. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  1264. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  1265. //-----------------------------------------------------------------------------------------------------------------
  1266. // set size, non-fatal
  1267. # ifdef CARLA_OS_LINUX
  1268. try {
  1269. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  1270. } CARLA_SAFE_EXCEPTION("Set pipe size");
  1271. try {
  1272. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  1273. } CARLA_SAFE_EXCEPTION("Set pipe size");
  1274. # endif
  1275. //-----------------------------------------------------------------------------------------------------------------
  1276. // set non-block
  1277. int ret;
  1278. try {
  1279. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  1280. } catch (...) {
  1281. ret = -1;
  1282. fail("failed to set pipe as non-block");
  1283. }
  1284. if (ret == 0)
  1285. {
  1286. try {
  1287. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  1288. } catch (...) {
  1289. ret = -1;
  1290. fail("failed to set pipe as non-block");
  1291. }
  1292. }
  1293. if (ret < 0)
  1294. {
  1295. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1296. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1297. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1298. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1299. return false;
  1300. }
  1301. #endif
  1302. //-----------------------------------------------------------------------------------------------------------------
  1303. // set arguments
  1304. const char* argv[9] = {};
  1305. int i = 0;
  1306. if (helperTool != nullptr)
  1307. argv[i++] = helperTool;
  1308. //-----------------------------------------------------------------------------------------------------------------
  1309. // argv[0] => filename
  1310. argv[i++] = filename;
  1311. //-----------------------------------------------------------------------------------------------------------------
  1312. // argv[1-2] => args
  1313. argv[i++] = arg1;
  1314. argv[i++] = arg2;
  1315. //-----------------------------------------------------------------------------------------------------------------
  1316. // argv[3-6] => pipes
  1317. argv[i++] = pipeRecvServerStr;
  1318. argv[i++] = pipeSendServerStr;
  1319. argv[i++] = pipeRecvClientStr;
  1320. argv[i++] = pipeSendClientStr;
  1321. //-----------------------------------------------------------------------------------------------------------------
  1322. // start process
  1323. #ifdef CARLA_OS_WIN
  1324. if (! startProcess(argv, &pData->processInfo))
  1325. {
  1326. carla_zeroStruct(pData->processInfo);
  1327. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1328. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1329. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1330. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  1331. return false;
  1332. }
  1333. // just to make sure
  1334. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1335. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1336. #else
  1337. if (! startProcess(argv, pData->pid))
  1338. {
  1339. pData->pid = -1;
  1340. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1341. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1342. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1343. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1344. fail("startProcess() failed");
  1345. return false;
  1346. }
  1347. //-----------------------------------------------------------------------------------------------------------------
  1348. // close duplicated handles used by the client
  1349. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1350. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1351. #endif
  1352. //-----------------------------------------------------------------------------------------------------------------
  1353. // wait for client to say something
  1354. #ifdef CARLA_OS_WIN
  1355. void* const ovRecv = pData->ovRecv;
  1356. void* const process = pData->processInfo.hProcess;
  1357. #else
  1358. void* const ovRecv = nullptr;
  1359. void* const process = nullptr;
  1360. #endif
  1361. if (waitForClientFirstMessage(pipeRecvClient, ovRecv, process, 10*1000 /* 10 secs */))
  1362. {
  1363. pData->pipeRecv = pipeRecvClient;
  1364. pData->pipeSend = pipeSendClient;
  1365. pData->pipeClosed = false;
  1366. carla_debug("ALL OK!");
  1367. return true;
  1368. }
  1369. //-----------------------------------------------------------------------------------------------------------------
  1370. // failed to set non-block or get first child message, cannot continue
  1371. #ifdef CARLA_OS_WIN
  1372. if (::TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1373. {
  1374. // wait for process to stop
  1375. waitForProcessToStop(pData->processInfo.hProcess, 2*1000, false);
  1376. }
  1377. // clear pData->processInfo
  1378. try { ::CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1379. try { ::CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1380. carla_zeroStruct(pData->processInfo);
  1381. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1382. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1383. #else
  1384. if (::kill(pData->pid, SIGKILL) != -1)
  1385. {
  1386. // wait for killing to take place
  1387. waitForChildToStop(pData->pid, 2*1000, false);
  1388. }
  1389. pData->pid = -1;
  1390. #endif
  1391. //-----------------------------------------------------------------------------------------------------------------
  1392. // close pipes
  1393. #ifdef CARLA_OS_WIN
  1394. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1395. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1396. #else
  1397. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1398. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1399. #endif
  1400. return false;
  1401. // maybe unused
  1402. (void)size; (void)ovRecv; (void)process;
  1403. }
  1404. bool CarlaPipeServer::startPipeServer(const char* const filename,
  1405. const char* const arg1,
  1406. const char* const arg2,
  1407. const int size) noexcept
  1408. {
  1409. return startPipeServer(nullptr, filename, arg1, arg2, size);
  1410. }
  1411. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1412. {
  1413. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1414. #ifdef CARLA_OS_WIN
  1415. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  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. syncMessages();
  1422. }
  1423. waitForProcessToStopOrKillIt(pData->processInfo.hProcess, timeOutMilliseconds);
  1424. try { ::CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1425. try { ::CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1426. carla_zeroStruct(pData->processInfo);
  1427. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1428. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1429. }
  1430. #else
  1431. if (pData->pid != -1)
  1432. {
  1433. const CarlaMutexLocker cml(pData->writeLock);
  1434. if (pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed)
  1435. {
  1436. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1437. syncMessages();
  1438. }
  1439. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1440. pData->pid = -1;
  1441. }
  1442. #endif
  1443. closePipeServer();
  1444. }
  1445. void CarlaPipeServer::closePipeServer() noexcept
  1446. {
  1447. carla_debug("CarlaPipeServer::closePipeServer()");
  1448. pData->pipeClosed = true;
  1449. const CarlaMutexLocker cml(pData->writeLock);
  1450. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1451. {
  1452. #ifdef CARLA_OS_WIN
  1453. DisconnectNamedPipe(pData->pipeRecv);
  1454. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1455. #else
  1456. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1457. #endif
  1458. pData->pipeRecv = INVALID_PIPE_VALUE;
  1459. }
  1460. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1461. {
  1462. #ifdef CARLA_OS_WIN
  1463. DisconnectNamedPipe(pData->pipeSend);
  1464. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1465. #else
  1466. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1467. #endif
  1468. pData->pipeSend = INVALID_PIPE_VALUE;
  1469. }
  1470. }
  1471. void CarlaPipeServer::writeShowMessage() const noexcept
  1472. {
  1473. const CarlaMutexLocker cml(pData->writeLock);
  1474. if (! _writeMsgBuffer("show\n", 5))
  1475. return;
  1476. syncMessages();
  1477. }
  1478. void CarlaPipeServer::writeFocusMessage() const noexcept
  1479. {
  1480. const CarlaMutexLocker cml(pData->writeLock);
  1481. if (! _writeMsgBuffer("focus\n", 6))
  1482. return;
  1483. syncMessages();
  1484. }
  1485. void CarlaPipeServer::writeHideMessage() const noexcept
  1486. {
  1487. const CarlaMutexLocker cml(pData->writeLock);
  1488. if (! _writeMsgBuffer("show\n", 5))
  1489. return;
  1490. syncMessages();
  1491. }
  1492. // -----------------------------------------------------------------------
  1493. CarlaPipeClient::CarlaPipeClient() noexcept
  1494. : CarlaPipeCommon()
  1495. {
  1496. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1497. }
  1498. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1499. {
  1500. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1501. closePipeClient();
  1502. }
  1503. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1504. {
  1505. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1506. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1507. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1508. const CarlaMutexLocker cml(pData->writeLock);
  1509. //----------------------------------------------------------------
  1510. // read arguments
  1511. #ifdef CARLA_OS_WIN
  1512. const char* const pipeRecvServerStr = argv[3];
  1513. const char* const pipeSendServerStr = argv[4];
  1514. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1515. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1516. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1517. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1518. #else
  1519. const int pipeRecvServer = std::atoi(argv[3]);
  1520. const int pipeSendServer = std::atoi(argv[4]);
  1521. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1522. /* */ int pipeSendClient = std::atoi(argv[6]);
  1523. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1524. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1525. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1526. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1527. //----------------------------------------------------------------
  1528. // close duplicated handles used by the client
  1529. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1530. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1531. //----------------------------------------------------------------
  1532. // kill ourselves if parent dies
  1533. carla_terminateProcessOnParentExit(false);
  1534. #endif
  1535. //----------------------------------------------------------------
  1536. // done
  1537. pData->pipeRecv = pipeRecvServer;
  1538. pData->pipeSend = pipeSendServer;
  1539. pData->pipeClosed = false;
  1540. pData->clientClosingDown = false;
  1541. if (writeMessage("\n", 1))
  1542. syncMessages();
  1543. return true;
  1544. }
  1545. void CarlaPipeClient::closePipeClient() noexcept
  1546. {
  1547. carla_debug("CarlaPipeClient::closePipeClient()");
  1548. pData->pipeClosed = true;
  1549. const CarlaMutexLocker cml(pData->writeLock);
  1550. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1551. {
  1552. #ifdef CARLA_OS_WIN
  1553. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1554. #else
  1555. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1556. #endif
  1557. pData->pipeRecv = INVALID_PIPE_VALUE;
  1558. }
  1559. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1560. {
  1561. #ifdef CARLA_OS_WIN
  1562. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1563. #else
  1564. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1565. #endif
  1566. pData->pipeSend = INVALID_PIPE_VALUE;
  1567. }
  1568. }
  1569. void CarlaPipeClient::writeExitingMessageAndWait() noexcept
  1570. {
  1571. {
  1572. const CarlaMutexLocker cml(pData->writeLock);
  1573. if (_writeMsgBuffer("exiting\n", 8))
  1574. syncMessages();
  1575. }
  1576. // NOTE: no more messages are handled after this point
  1577. pData->clientClosingDown = true;
  1578. for (int i=0; i < 100 && ! pData->pipeClosed; ++i)
  1579. {
  1580. carla_msleep(50);
  1581. idlePipe(true);
  1582. }
  1583. if (! pData->pipeClosed)
  1584. carla_stderr2("writeExitingMessageAndWait pipe is still running!");
  1585. }
  1586. // -----------------------------------------------------------------------
  1587. #undef INVALID_PIPE_VALUE