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.

1923 lines
52KB

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