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.

1931 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 WAIT_FAILED:
  69. carla_stderr("waitForAsyncObject process has stopped");
  70. return false;
  71. }
  72. }
  73. carla_debug("waitForAsyncObject loop start");
  74. dw = ::MsgWaitForMultipleObjectsEx(1, &object, INFINITE, QS_POSTMESSAGE|QS_TIMER, 0);
  75. carla_debug("waitForAsyncObject initial code is: %u", dw);
  76. if (dw == WAIT_OBJECT_0)
  77. {
  78. carla_debug("waitForAsyncObject WAIT_OBJECT_0");
  79. return true;
  80. }
  81. dw2 = ::GetLastError();
  82. if (dw == WAIT_OBJECT_0 + 1)
  83. {
  84. carla_debug("waitForAsyncObject loop +1");
  85. while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
  86. ::DispatchMessage(&msg);
  87. continue;
  88. }
  89. if (dw2 == 0)
  90. {
  91. carla_debug("waitForAsyncObject loop stop");
  92. return true;
  93. }
  94. carla_stderr2("waitForAsyncObject loop end reached, error was: %u", dw2);
  95. carla_msleep(5);
  96. }
  97. carla_stderr2("waitForAsyncObject reached the end, this should not happen");
  98. return false;
  99. }
  100. static inline
  101. ssize_t ReadFileWin32(const HANDLE pipeh, const HANDLE event, void* const buf, const std::size_t numBytes)
  102. {
  103. DWORD dw, dsize = numBytes;
  104. DWORD available = 0;
  105. if (::PeekNamedPipe(pipeh, nullptr, 0, nullptr, &available, nullptr) == FALSE || available == 0)
  106. return -1;
  107. OVERLAPPED ov;
  108. carla_zeroStruct(ov);
  109. ov.hEvent = event;
  110. if (::ReadFile(pipeh, buf, dsize, nullptr, &ov))
  111. {
  112. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  113. {
  114. carla_stderr("ReadFileWin32 GetOverlappedResult failed, error was: %u", ::GetLastError());
  115. return -1;
  116. }
  117. return static_cast<ssize_t>(dsize);
  118. }
  119. dw = ::GetLastError();
  120. if (dw == ERROR_IO_PENDING)
  121. {
  122. if (! waitForAsyncObject(event))
  123. {
  124. carla_stderr("ReadFileWin32 waitForAsyncObject failed, error was: %u", ::GetLastError());
  125. return -1;
  126. }
  127. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  128. {
  129. carla_stderr("ReadFileWin32 GetOverlappedResult of pending failed, error was: %u", ::GetLastError());
  130. return -1;
  131. }
  132. return static_cast<ssize_t>(dsize);
  133. }
  134. carla_stderr("ReadFileWin32 failed, error was: %u", dw);
  135. return -1;
  136. }
  137. static inline
  138. ssize_t WriteFileWin32(const HANDLE pipeh, const HANDLE event, const void* const buf, const std::size_t numBytes)
  139. {
  140. DWORD dw, dsize = numBytes;
  141. OVERLAPPED ov;
  142. carla_zeroStruct(ov);
  143. ov.hEvent = event;
  144. if (::WriteFile(pipeh, buf, dsize, nullptr, &ov))
  145. {
  146. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  147. {
  148. carla_stderr("WriteFileWin32 GetOverlappedResult failed, error was: %u", ::GetLastError());
  149. return -1;
  150. }
  151. return static_cast<ssize_t>(dsize);
  152. }
  153. dw = ::GetLastError();
  154. if (dw == ERROR_IO_PENDING)
  155. {
  156. if (! waitForAsyncObject(event))
  157. {
  158. carla_stderr("WriteFileWin32 waitForAsyncObject failed, error was: %u", ::GetLastError());
  159. return -1;
  160. }
  161. if (! ::GetOverlappedResult(pipeh, &ov, &dw, FALSE))
  162. {
  163. carla_stderr("WriteFileWin32 GetOverlappedResult of pending failed, error was: %u", ::GetLastError());
  164. return -1;
  165. }
  166. return static_cast<ssize_t>(dsize);
  167. }
  168. if (dw == ERROR_PIPE_NOT_CONNECTED)
  169. {
  170. carla_stdout("WriteFileWin32 failed, client has closed");
  171. return -2;
  172. }
  173. carla_stderr("WriteFileWin32 failed, error was: %u", dw);
  174. return -1;
  175. }
  176. #endif // CARLA_OS_WIN
  177. // -----------------------------------------------------------------------
  178. // startProcess
  179. #ifdef CARLA_OS_WIN
  180. static inline
  181. bool startProcess(const char* const argv[], PROCESS_INFORMATION* const processInfo)
  182. {
  183. CARLA_SAFE_ASSERT_RETURN(processInfo != nullptr, false);
  184. using water::String;
  185. String command;
  186. for (int i=0; argv[i] != nullptr; ++i)
  187. {
  188. String arg(argv[i]);
  189. // If there are spaces, surround it with quotes. If there are quotes,
  190. // replace them with \" so that CommandLineToArgv will correctly parse them.
  191. if (arg.containsAnyOf("\" "))
  192. arg = arg.replace("\"", "\\\"").quoted();
  193. command << arg << ' ';
  194. }
  195. command = command.trim();
  196. STARTUPINFO startupInfo;
  197. carla_zeroStruct(startupInfo);
  198. startupInfo.cb = sizeof(startupInfo);
  199. 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 WAIT_FAILED:
  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. readSucess = false;
  542. const char* const msg = _readline(true, 0, readSucess);
  543. if (! readSucess)
  544. break;
  545. if (msg == nullptr)
  546. continue;
  547. pData->isReading = true;
  548. if (std::strcmp(msg, "__carla-quit__") == 0)
  549. {
  550. pData->pipeClosed = true;
  551. }
  552. else if (! pData->clientClosingDown)
  553. {
  554. try {
  555. msgReceived(msg);
  556. } CARLA_SAFE_EXCEPTION("msgReceived");
  557. }
  558. pData->isReading = false;
  559. delete[] msg;
  560. if (onlyOnce || pData->pipeRecv == INVALID_PIPE_VALUE)
  561. break;
  562. }
  563. }
  564. // -------------------------------------------------------------------
  565. void CarlaPipeCommon::lockPipe() const noexcept
  566. {
  567. pData->writeLock.lock();
  568. }
  569. bool CarlaPipeCommon::tryLockPipe() const noexcept
  570. {
  571. return pData->writeLock.tryLock();
  572. }
  573. void CarlaPipeCommon::unlockPipe() const noexcept
  574. {
  575. pData->writeLock.unlock();
  576. }
  577. CarlaMutex& CarlaPipeCommon::getPipeLock() const noexcept
  578. {
  579. return pData->writeLock;
  580. }
  581. // -------------------------------------------------------------------
  582. bool CarlaPipeCommon::readNextLineAsBool(bool& value) const noexcept
  583. {
  584. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  585. if (const char* const msg = _readlineblock(false))
  586. {
  587. value = (std::strcmp(msg, "true") == 0);
  588. return true;
  589. }
  590. return false;
  591. }
  592. bool CarlaPipeCommon::readNextLineAsByte(uint8_t& value) const noexcept
  593. {
  594. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  595. if (const char* const msg = _readlineblock(false))
  596. {
  597. const int asint = std::atoi(msg);
  598. if (asint >= 0 && asint <= 0xFF)
  599. {
  600. value = static_cast<uint8_t>(asint);
  601. return true;
  602. }
  603. }
  604. return false;
  605. }
  606. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) const noexcept
  607. {
  608. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  609. if (const char* const msg = _readlineblock(false))
  610. {
  611. value = std::atoi(msg);
  612. return true;
  613. }
  614. return false;
  615. }
  616. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) const noexcept
  617. {
  618. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  619. if (const char* const msg = _readlineblock(false))
  620. {
  621. const long aslong = std::atol(msg);
  622. if (aslong >= 0)
  623. {
  624. value = static_cast<uint32_t>(aslong);
  625. return true;
  626. }
  627. }
  628. return false;
  629. }
  630. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) const noexcept
  631. {
  632. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  633. if (const char* const msg = _readlineblock(false))
  634. {
  635. value = std::atol(msg);
  636. return true;
  637. }
  638. return false;
  639. }
  640. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) const noexcept
  641. {
  642. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  643. if (const char* const msg = _readlineblock(false))
  644. {
  645. const int64_t asint64 = std::atol(msg);
  646. if (asint64 >= 0)
  647. {
  648. value = static_cast<uint64_t>(asint64);
  649. return true;
  650. }
  651. }
  652. return false;
  653. }
  654. bool CarlaPipeCommon::readNextLineAsFloat(float& value) const noexcept
  655. {
  656. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  657. if (const char* const msg = _readlineblock(false))
  658. {
  659. {
  660. const CarlaScopedLocale csl;
  661. value = static_cast<float>(std::atof(msg));
  662. }
  663. return true;
  664. }
  665. return false;
  666. }
  667. bool CarlaPipeCommon::readNextLineAsDouble(double& value) const noexcept
  668. {
  669. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  670. if (const char* const msg = _readlineblock(false))
  671. {
  672. {
  673. const CarlaScopedLocale csl;
  674. value = std::atof(msg);
  675. }
  676. return true;
  677. }
  678. return false;
  679. }
  680. bool CarlaPipeCommon::readNextLineAsString(const char*& value, const bool allocateString, uint32_t size) const noexcept
  681. {
  682. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  683. if (size >= 0xffff)
  684. size = 0;
  685. if (const char* const msg = _readlineblock(allocateString, static_cast<uint16_t>(size)))
  686. {
  687. value = msg;
  688. return true;
  689. }
  690. return false;
  691. }
  692. // -------------------------------------------------------------------
  693. // must be locked before calling
  694. bool CarlaPipeCommon::writeMessage(const char* const msg) const noexcept
  695. {
  696. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  697. if (pData->pipeClosed)
  698. return false;
  699. const std::size_t size(std::strlen(msg));
  700. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  701. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  702. return _writeMsgBuffer(msg, size);
  703. }
  704. bool CarlaPipeCommon::writeMessage(const char* const msg, std::size_t size) const noexcept
  705. {
  706. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  707. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  708. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  709. if (pData->pipeClosed)
  710. return false;
  711. return _writeMsgBuffer(msg, size);
  712. }
  713. bool CarlaPipeCommon::writeAndFixMessage(const char* const msg) const noexcept
  714. {
  715. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  716. if (pData->pipeClosed)
  717. return false;
  718. const std::size_t size(std::strlen(msg));
  719. char fixedMsg[size+2];
  720. if (size > 0)
  721. {
  722. std::strcpy(fixedMsg, msg);
  723. for (std::size_t i=0; i<size; ++i)
  724. {
  725. if (fixedMsg[i] == '\n')
  726. fixedMsg[i] = '\r';
  727. }
  728. if (fixedMsg[size-1] == '\r')
  729. {
  730. fixedMsg[size-1] = '\n';
  731. fixedMsg[size ] = '\0';
  732. fixedMsg[size+1] = '\0';
  733. }
  734. else
  735. {
  736. fixedMsg[size ] = '\n';
  737. fixedMsg[size+1] = '\0';
  738. }
  739. }
  740. else
  741. {
  742. fixedMsg[0] = '\n';
  743. fixedMsg[1] = '\0';
  744. }
  745. return _writeMsgBuffer(fixedMsg, size+1);
  746. }
  747. bool CarlaPipeCommon::writeEmptyMessage() const noexcept
  748. {
  749. if (pData->pipeClosed)
  750. return false;
  751. return _writeMsgBuffer("\n", 1);
  752. }
  753. bool CarlaPipeCommon::flushMessages() const noexcept
  754. {
  755. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  756. #if defined(CARLA_OS_LINUX) || defined(CARLA_OS_GNU_HURD)
  757. # if defined(__GLIBC__) && (__GLIBC__ * 1000 + __GLIBC_MINOR__) >= 2014
  758. // the only call that seems to do something
  759. return ::syncfs(pData->pipeSend) == 0;
  760. # endif
  761. #elif 0 // defined(CARLA_OS_WIN)
  762. // FIXME causes issues
  763. try {
  764. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  765. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  766. #endif
  767. return true;
  768. }
  769. // -------------------------------------------------------------------
  770. void CarlaPipeCommon::writeErrorMessage(const char* const error) const noexcept
  771. {
  772. CARLA_SAFE_ASSERT_RETURN(error != nullptr && error[0] != '\0',);
  773. const CarlaMutexLocker cml(pData->writeLock);
  774. if (! _writeMsgBuffer("error\n", 6))
  775. return;
  776. if (! writeAndFixMessage(error))
  777. return;
  778. flushMessages();
  779. }
  780. void CarlaPipeCommon::writeControlMessage(const uint32_t index, const float value) const noexcept
  781. {
  782. char tmpBuf[0xff];
  783. tmpBuf[0xfe] = '\0';
  784. const CarlaMutexLocker cml(pData->writeLock);
  785. if (! _writeMsgBuffer("control\n", 8))
  786. return;
  787. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  788. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  789. return;
  790. {
  791. const CarlaScopedLocale csl;
  792. std::snprintf(tmpBuf, 0xfe, "%.12g\n", static_cast<double>(value));
  793. }
  794. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  795. return;
  796. flushMessages();
  797. }
  798. void CarlaPipeCommon::writeConfigureMessage(const char* const key, const char* const value) const noexcept
  799. {
  800. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  801. CARLA_SAFE_ASSERT_RETURN(value != nullptr,);
  802. const CarlaMutexLocker cml(pData->writeLock);
  803. if (! _writeMsgBuffer("configure\n", 10))
  804. return;
  805. if (! writeAndFixMessage(key))
  806. return;
  807. if (! writeAndFixMessage(value))
  808. return;
  809. flushMessages();
  810. }
  811. void CarlaPipeCommon::writeProgramMessage(const uint32_t index) const noexcept
  812. {
  813. char tmpBuf[0xff];
  814. tmpBuf[0xfe] = '\0';
  815. const CarlaMutexLocker cml(pData->writeLock);
  816. if (! _writeMsgBuffer("program\n", 8))
  817. return;
  818. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  819. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  820. return;
  821. flushMessages();
  822. }
  823. void CarlaPipeCommon::writeProgramMessage(const uint8_t channel, const uint32_t bank, const uint32_t program) const noexcept
  824. {
  825. char tmpBuf[0xff];
  826. tmpBuf[0xfe] = '\0';
  827. const CarlaMutexLocker cml(pData->writeLock);
  828. if (! _writeMsgBuffer("program\n", 8))
  829. return;
  830. std::snprintf(tmpBuf, 0xfe, "%i\n", channel);
  831. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  832. return;
  833. std::snprintf(tmpBuf, 0xfe, "%i\n", bank);
  834. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  835. return;
  836. std::snprintf(tmpBuf, 0xfe, "%i\n", program);
  837. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  838. return;
  839. flushMessages();
  840. }
  841. void CarlaPipeCommon::writeMidiProgramMessage(const uint32_t bank, const uint32_t program) const noexcept
  842. {
  843. char tmpBuf[0xff];
  844. tmpBuf[0xfe] = '\0';
  845. const CarlaMutexLocker cml(pData->writeLock);
  846. if (! _writeMsgBuffer("midiprogram\n", 12))
  847. return;
  848. std::snprintf(tmpBuf, 0xfe, "%i\n", bank);
  849. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  850. return;
  851. std::snprintf(tmpBuf, 0xfe, "%i\n", program);
  852. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  853. return;
  854. flushMessages();
  855. }
  856. void CarlaPipeCommon::writeReloadProgramsMessage(const int32_t index) const noexcept
  857. {
  858. char tmpBuf[0xff];
  859. tmpBuf[0xfe] = '\0';
  860. const CarlaMutexLocker cml(pData->writeLock);
  861. if (! _writeMsgBuffer("reloadprograms\n", 15))
  862. return;
  863. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  864. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  865. return;
  866. flushMessages();
  867. }
  868. void CarlaPipeCommon::writeMidiNoteMessage(const bool onOff, const uint8_t channel, const uint8_t note, const uint8_t velocity) const noexcept
  869. {
  870. CARLA_SAFE_ASSERT_RETURN(channel < MAX_MIDI_CHANNELS,);
  871. CARLA_SAFE_ASSERT_RETURN(note < MAX_MIDI_NOTE,);
  872. CARLA_SAFE_ASSERT_RETURN(velocity < MAX_MIDI_VALUE,);
  873. char tmpBuf[0xff];
  874. tmpBuf[0xfe] = '\0';
  875. const CarlaMutexLocker cml(pData->writeLock);
  876. if (! _writeMsgBuffer("note\n", 5))
  877. return;
  878. std::snprintf(tmpBuf, 0xfe, "%s\n", bool2str(onOff));
  879. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  880. return;
  881. std::snprintf(tmpBuf, 0xfe, "%i\n", channel);
  882. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  883. return;
  884. std::snprintf(tmpBuf, 0xfe, "%i\n", note);
  885. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  886. return;
  887. std::snprintf(tmpBuf, 0xfe, "%i\n", velocity);
  888. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  889. return;
  890. flushMessages();
  891. }
  892. void CarlaPipeCommon::writeLv2AtomMessage(const uint32_t index, const LV2_Atom* const atom) const noexcept
  893. {
  894. CARLA_SAFE_ASSERT_RETURN(atom != nullptr,);
  895. char tmpBuf[0xff];
  896. tmpBuf[0xfe] = '\0';
  897. const uint32_t atomTotalSize(lv2_atom_total_size(atom));
  898. CarlaString base64atom(CarlaString::asBase64(atom, atomTotalSize));
  899. const CarlaMutexLocker cml(pData->writeLock);
  900. if (! _writeMsgBuffer("atom\n", 5))
  901. return;
  902. std::snprintf(tmpBuf, 0xfe, "%i\n", index);
  903. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  904. return;
  905. std::snprintf(tmpBuf, 0xfe, "%i\n", atomTotalSize);
  906. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  907. return;
  908. std::snprintf(tmpBuf, 0xfe, "%lu\n", static_cast<long unsigned>(base64atom.length()));
  909. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  910. return;
  911. if (! writeAndFixMessage(base64atom.buffer()))
  912. return;
  913. flushMessages();
  914. }
  915. void CarlaPipeCommon::writeLv2UridMessage(const uint32_t urid, const char* const uri) const noexcept
  916. {
  917. CARLA_SAFE_ASSERT_RETURN(urid != 0,);
  918. CARLA_SAFE_ASSERT_RETURN(uri != nullptr && uri[0] != '\0',);
  919. char tmpBuf[0xff];
  920. tmpBuf[0xfe] = '\0';
  921. const CarlaMutexLocker cml(pData->writeLock);
  922. if (! _writeMsgBuffer("urid\n", 5))
  923. return;
  924. std::snprintf(tmpBuf, 0xfe, "%i\n", urid);
  925. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  926. return;
  927. std::snprintf(tmpBuf, 0xfe, "%lu\n", static_cast<long unsigned>(std::strlen(uri)));
  928. if (! _writeMsgBuffer(tmpBuf, std::strlen(tmpBuf)))
  929. return;
  930. if (! writeAndFixMessage(uri))
  931. return;
  932. flushMessages();
  933. }
  934. // -------------------------------------------------------------------
  935. // internal
  936. const char* CarlaPipeCommon::_readline(const bool allocReturn, const uint16_t size, bool& readSucess) const noexcept
  937. {
  938. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  939. char c;
  940. char* ptr = pData->tmpBuf;
  941. ssize_t ret = -1;
  942. bool tooBig = false;
  943. pData->tmpStr.clear();
  944. if (size == 0 || size == 1)
  945. {
  946. for (int i=0; i<0xfffe; ++i)
  947. {
  948. try {
  949. #ifdef CARLA_OS_WIN
  950. ret = ReadFileWin32(pData->pipeRecv, pData->ovRecv, &c, 1);
  951. #else
  952. ret = ::read(pData->pipeRecv, &c, 1);
  953. #endif
  954. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  955. if (ret != 1)
  956. break;
  957. if (c == '\n')
  958. {
  959. *ptr = '\0';
  960. break;
  961. }
  962. if (c == '\r')
  963. c = '\n';
  964. *ptr++ = c;
  965. if (i+1 == 0xfffe)
  966. {
  967. i = 0;
  968. *ptr = '\0';
  969. tooBig = true;
  970. pData->tmpStr += pData->tmpBuf;
  971. ptr = pData->tmpBuf;
  972. }
  973. }
  974. }
  975. else
  976. {
  977. uint16_t remaining = size;
  978. readSucess = false;
  979. for (;;)
  980. {
  981. try {
  982. #ifdef CARLA_OS_WIN
  983. ret = ReadFileWin32(pData->pipeRecv, pData->ovRecv, ptr, remaining);
  984. #else
  985. ret = ::read(pData->pipeRecv, ptr, remaining);
  986. #endif
  987. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - read", nullptr);
  988. if (ret == -1 && errno == EAGAIN)
  989. continue;
  990. CARLA_SAFE_ASSERT_INT2_RETURN(ret > 0, ret, remaining, nullptr);
  991. CARLA_SAFE_ASSERT_INT2_RETURN(ret <= (ssize_t)remaining, ret, remaining, nullptr);
  992. for (ssize_t i=0; i<ret; ++i)
  993. {
  994. if (ptr[i] == '\r')
  995. ptr[i] = '\n';
  996. }
  997. ptr += ret;
  998. *ptr = '\0';
  999. remaining = static_cast<uint16_t>(remaining - ret);
  1000. if (remaining != 0)
  1001. continue;
  1002. readSucess = true;
  1003. if (allocReturn)
  1004. {
  1005. pData->tmpStr = pData->tmpBuf;
  1006. return pData->tmpStr.releaseBufferPointer();
  1007. }
  1008. return pData->tmpBuf;
  1009. }
  1010. }
  1011. if (ptr != pData->tmpBuf)
  1012. {
  1013. *ptr = '\0';
  1014. if (! allocReturn && ! tooBig)
  1015. {
  1016. readSucess = true;
  1017. return pData->tmpBuf;
  1018. }
  1019. pData->tmpStr += pData->tmpBuf;
  1020. }
  1021. else if (pData->tmpStr.isEmpty() && ret != 1)
  1022. {
  1023. // some error
  1024. return nullptr;
  1025. }
  1026. readSucess = true;
  1027. if (! allocReturn && ! tooBig)
  1028. return pData->tmpBuf;
  1029. return allocReturn ? pData->tmpStr.releaseBufferPointer() : pData->tmpStr.buffer();
  1030. }
  1031. const char* CarlaPipeCommon::_readlineblock(const bool allocReturn,
  1032. const uint16_t size,
  1033. const uint32_t timeOutMilliseconds) const noexcept
  1034. {
  1035. const uint32_t timeoutEnd = water::Time::getMillisecondCounter() + timeOutMilliseconds;
  1036. bool readSucess;
  1037. for (;;)
  1038. {
  1039. readSucess = false;
  1040. const char* const msg = _readline(allocReturn, size, readSucess);
  1041. if (readSucess)
  1042. return msg;
  1043. if (water::Time::getMillisecondCounter() >= timeoutEnd)
  1044. break;
  1045. carla_msleep(5);
  1046. }
  1047. static const bool testingForValgrind = std::getenv("CARLA_VALGRIND_TEST") != nullptr;
  1048. if (testingForValgrind)
  1049. {
  1050. const uint32_t timeoutEnd2 = water::Time::getMillisecondCounter() + 1000;
  1051. for (;;)
  1052. {
  1053. readSucess = false;
  1054. const char* const msg = _readline(allocReturn, size, readSucess);
  1055. if (readSucess)
  1056. return msg;
  1057. if (water::Time::getMillisecondCounter() >= timeoutEnd2)
  1058. break;
  1059. carla_msleep(100);
  1060. }
  1061. }
  1062. carla_stderr("readlineblock timed out");
  1063. return nullptr;
  1064. }
  1065. bool CarlaPipeCommon::_writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  1066. {
  1067. if (pData->pipeClosed)
  1068. return false;
  1069. if (pData->pipeSend == INVALID_PIPE_VALUE)
  1070. {
  1071. carla_stderr2("CarlaPipe write error, isServer:%s, message was:\n%s", bool2str(pData->isServer), msg);
  1072. return false;
  1073. }
  1074. ssize_t ret;
  1075. try {
  1076. #ifdef CARLA_OS_WIN
  1077. ret = WriteFileWin32(pData->pipeSend, pData->ovSend, msg, size);
  1078. #else
  1079. ret = ::write(pData->pipeSend, msg, size);
  1080. #endif
  1081. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  1082. #ifdef CARLA_OS_WIN
  1083. if (ret == -2)
  1084. {
  1085. pData->pipeClosed = true;
  1086. return false;
  1087. }
  1088. #endif
  1089. if (ret == static_cast<ssize_t>(size))
  1090. {
  1091. if (pData->lastMessageFailed)
  1092. pData->lastMessageFailed = false;
  1093. return true;
  1094. }
  1095. if (! pData->lastMessageFailed)
  1096. {
  1097. pData->lastMessageFailed = true;
  1098. fprintf(stderr,
  1099. "CarlaPipeCommon::_writeMsgBuffer(..., " P_SIZE ") - failed with " P_SSIZE " (%s), message was:\n%s",
  1100. size, ret, bool2str(pData->isServer), msg);
  1101. }
  1102. return false;
  1103. }
  1104. // -----------------------------------------------------------------------
  1105. CarlaPipeServer::CarlaPipeServer() noexcept
  1106. : CarlaPipeCommon()
  1107. {
  1108. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  1109. pData->isServer = true;
  1110. }
  1111. CarlaPipeServer::~CarlaPipeServer() /*noexcept*/
  1112. {
  1113. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  1114. stopPipeServer(5*1000);
  1115. }
  1116. uintptr_t CarlaPipeServer::getPID() const noexcept
  1117. {
  1118. #ifndef CARLA_OS_WIN
  1119. return static_cast<uintptr_t>(pData->pid);
  1120. #else
  1121. return 0;
  1122. #endif
  1123. }
  1124. // --------------------------------------------------------------------------------------------------------------------
  1125. bool CarlaPipeServer::startPipeServer(const char* const filename,
  1126. const char* const arg1,
  1127. const char* const arg2,
  1128. const int size) noexcept
  1129. {
  1130. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1131. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1132. #ifdef CARLA_OS_WIN
  1133. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == INVALID_HANDLE_VALUE, false);
  1134. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == INVALID_HANDLE_VALUE, false);
  1135. #else
  1136. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  1137. #endif
  1138. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  1139. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  1140. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  1141. carla_debug("CarlaPipeServer::startPipeServer(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  1142. char pipeRecvServerStr[100+1];
  1143. char pipeSendServerStr[100+1];
  1144. char pipeRecvClientStr[100+1];
  1145. char pipeSendClientStr[100+1];
  1146. pipeRecvServerStr[100] = '\0';
  1147. pipeSendServerStr[100] = '\0';
  1148. pipeRecvClientStr[100] = '\0';
  1149. pipeSendClientStr[100] = '\0';
  1150. const CarlaMutexLocker cml(pData->writeLock);
  1151. //-----------------------------------------------------------------------------------------------------------------
  1152. // create pipes
  1153. #ifdef CARLA_OS_WIN
  1154. HANDLE pipe1, pipe2;
  1155. std::srand(static_cast<uint>(std::time(nullptr)));
  1156. static ulong sCounter = 0;
  1157. ++sCounter;
  1158. const int randint = std::rand();
  1159. std::snprintf(pipeRecvServerStr, 100, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  1160. std::snprintf(pipeSendServerStr, 100, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  1161. std::snprintf(pipeRecvClientStr, 100, "ignored");
  1162. std::snprintf(pipeSendClientStr, 100, "ignored");
  1163. SECURITY_ATTRIBUTES sa;
  1164. carla_zeroStruct(sa);
  1165. sa.nLength = sizeof(sa);
  1166. sa.bInheritHandle = TRUE;
  1167. 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);
  1168. if (pipe1 == INVALID_HANDLE_VALUE)
  1169. {
  1170. fail("pipe creation failed");
  1171. return false;
  1172. }
  1173. 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);
  1174. if (pipe2 == INVALID_HANDLE_VALUE)
  1175. {
  1176. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1177. fail("pipe creation failed");
  1178. return false;
  1179. }
  1180. const HANDLE pipeRecvClient = pipe2;
  1181. const HANDLE pipeSendClient = pipe1;
  1182. #else
  1183. int pipe1[2]; // read by server, written by client
  1184. int pipe2[2]; // read by client, written by server
  1185. if (::pipe(pipe1) != 0)
  1186. {
  1187. fail("pipe1 creation failed");
  1188. return false;
  1189. }
  1190. if (::pipe(pipe2) != 0)
  1191. {
  1192. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1193. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1194. fail("pipe2 creation failed");
  1195. return false;
  1196. }
  1197. /* */ int pipeRecvServer = pipe1[0];
  1198. /* */ int pipeSendServer = pipe2[1];
  1199. const int pipeRecvClient = pipe2[0];
  1200. const int pipeSendClient = pipe1[1];
  1201. std::snprintf(pipeRecvServerStr, 100, "%i", pipeRecvServer);
  1202. std::snprintf(pipeSendServerStr, 100, "%i", pipeSendServer);
  1203. std::snprintf(pipeRecvClientStr, 100, "%i", pipeRecvClient);
  1204. std::snprintf(pipeSendClientStr, 100, "%i", pipeSendClient);
  1205. //-----------------------------------------------------------------------------------------------------------------
  1206. // set size, non-fatal
  1207. # ifdef CARLA_OS_LINUX
  1208. try {
  1209. ::fcntl(pipeRecvClient, F_SETPIPE_SZ, size);
  1210. } CARLA_SAFE_EXCEPTION("Set pipe size");
  1211. try {
  1212. ::fcntl(pipeRecvServer, F_SETPIPE_SZ, size);
  1213. } CARLA_SAFE_EXCEPTION("Set pipe size");
  1214. # endif
  1215. //-----------------------------------------------------------------------------------------------------------------
  1216. // set non-block
  1217. int ret;
  1218. try {
  1219. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  1220. } catch (...) {
  1221. ret = -1;
  1222. fail("failed to set pipe as non-block");
  1223. }
  1224. if (ret == 0)
  1225. {
  1226. try {
  1227. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  1228. } catch (...) {
  1229. ret = -1;
  1230. fail("failed to set pipe as non-block");
  1231. }
  1232. }
  1233. if (ret < 0)
  1234. {
  1235. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1236. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1237. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1238. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1239. return false;
  1240. }
  1241. #endif
  1242. //-----------------------------------------------------------------------------------------------------------------
  1243. // set arguments
  1244. const char* argv[8];
  1245. //-----------------------------------------------------------------------------------------------------------------
  1246. // argv[0] => filename
  1247. argv[0] = filename;
  1248. //-----------------------------------------------------------------------------------------------------------------
  1249. // argv[1-2] => args
  1250. argv[1] = arg1;
  1251. argv[2] = arg2;
  1252. //-----------------------------------------------------------------------------------------------------------------
  1253. // argv[3-6] => pipes
  1254. argv[3] = pipeRecvServerStr;
  1255. argv[4] = pipeSendServerStr;
  1256. argv[5] = pipeRecvClientStr;
  1257. argv[6] = pipeSendClientStr;
  1258. //-----------------------------------------------------------------------------------------------------------------
  1259. // argv[7] => null
  1260. argv[7] = nullptr;
  1261. //-----------------------------------------------------------------------------------------------------------------
  1262. // start process
  1263. #ifdef CARLA_OS_WIN
  1264. if (! startProcess(argv, &pData->processInfo))
  1265. {
  1266. carla_zeroStruct(pData->processInfo);
  1267. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1268. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1269. try { ::CloseHandle(pipe1); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1)");
  1270. try { ::CloseHandle(pipe2); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2)");
  1271. fail("startProcess() failed");
  1272. return false;
  1273. }
  1274. // just to make sure
  1275. CARLA_SAFE_ASSERT(pData->processInfo.hThread != INVALID_HANDLE_VALUE);
  1276. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != INVALID_HANDLE_VALUE);
  1277. #else
  1278. if (! startProcess(argv, pData->pid))
  1279. {
  1280. pData->pid = -1;
  1281. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  1282. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  1283. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  1284. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  1285. fail("startProcess() failed");
  1286. return false;
  1287. }
  1288. //-----------------------------------------------------------------------------------------------------------------
  1289. // close duplicated handles used by the client
  1290. try { ::close(pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  1291. try { ::close(pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  1292. #endif
  1293. //-----------------------------------------------------------------------------------------------------------------
  1294. // wait for client to say something
  1295. #ifdef CARLA_OS_WIN
  1296. void* const ovRecv = pData->ovRecv;
  1297. void* const process = pData->processInfo.hProcess;
  1298. #else
  1299. void* const ovRecv = nullptr;
  1300. void* const process = nullptr;
  1301. #endif
  1302. if (waitForClientFirstMessage(pipeRecvClient, ovRecv, process, 10*1000 /* 10 secs */))
  1303. {
  1304. pData->pipeRecv = pipeRecvClient;
  1305. pData->pipeSend = pipeSendClient;
  1306. pData->pipeClosed = false;
  1307. carla_stdout("ALL OK!");
  1308. return true;
  1309. }
  1310. //-----------------------------------------------------------------------------------------------------------------
  1311. // failed to set non-block or get first child message, cannot continue
  1312. #ifdef CARLA_OS_WIN
  1313. if (::TerminateProcess(pData->processInfo.hProcess, 9) != FALSE)
  1314. {
  1315. // wait for process to stop
  1316. waitForProcessToStop(pData->processInfo.hProcess, 2*1000, false);
  1317. }
  1318. // clear pData->processInfo
  1319. try { ::CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1320. try { ::CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1321. carla_zeroStruct(pData->processInfo);
  1322. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1323. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1324. #else
  1325. if (::kill(pData->pid, SIGKILL) != -1)
  1326. {
  1327. // wait for killing to take place
  1328. waitForChildToStop(pData->pid, 2*1000, false);
  1329. }
  1330. pData->pid = -1;
  1331. #endif
  1332. //-----------------------------------------------------------------------------------------------------------------
  1333. // close pipes
  1334. #ifdef CARLA_OS_WIN
  1335. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  1336. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  1337. #else
  1338. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1339. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1340. #endif
  1341. return false;
  1342. // maybe unused
  1343. (void)size; (void)ovRecv; (void)process;
  1344. }
  1345. void CarlaPipeServer::stopPipeServer(const uint32_t timeOutMilliseconds) noexcept
  1346. {
  1347. carla_debug("CarlaPipeServer::stopPipeServer(%i)", timeOutMilliseconds);
  1348. #ifdef CARLA_OS_WIN
  1349. if (pData->processInfo.hThread != INVALID_HANDLE_VALUE || pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  1350. {
  1351. const CarlaMutexLocker cml(pData->writeLock);
  1352. if (pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed)
  1353. {
  1354. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1355. flushMessages();
  1356. }
  1357. waitForProcessToStopOrKillIt(pData->processInfo.hProcess, timeOutMilliseconds);
  1358. try { ::CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  1359. try { ::CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  1360. carla_zeroStruct(pData->processInfo);
  1361. pData->processInfo.hProcess = INVALID_HANDLE_VALUE;
  1362. pData->processInfo.hThread = INVALID_HANDLE_VALUE;
  1363. }
  1364. #else
  1365. if (pData->pid != -1)
  1366. {
  1367. const CarlaMutexLocker cml(pData->writeLock);
  1368. if (pData->pipeSend != INVALID_PIPE_VALUE && ! pData->pipeClosed)
  1369. {
  1370. if (_writeMsgBuffer("__carla-quit__\n", 15))
  1371. flushMessages();
  1372. }
  1373. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  1374. pData->pid = -1;
  1375. }
  1376. #endif
  1377. closePipeServer();
  1378. }
  1379. void CarlaPipeServer::closePipeServer() noexcept
  1380. {
  1381. carla_debug("CarlaPipeServer::closePipeServer()");
  1382. pData->pipeClosed = true;
  1383. const CarlaMutexLocker cml(pData->writeLock);
  1384. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1385. {
  1386. #ifdef CARLA_OS_WIN
  1387. DisconnectNamedPipe(pData->pipeRecv);
  1388. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1389. #else
  1390. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1391. #endif
  1392. pData->pipeRecv = INVALID_PIPE_VALUE;
  1393. }
  1394. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1395. {
  1396. #ifdef CARLA_OS_WIN
  1397. DisconnectNamedPipe(pData->pipeSend);
  1398. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1399. #else
  1400. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1401. #endif
  1402. pData->pipeSend = INVALID_PIPE_VALUE;
  1403. }
  1404. }
  1405. void CarlaPipeServer::writeShowMessage() const noexcept
  1406. {
  1407. const CarlaMutexLocker cml(pData->writeLock);
  1408. if (! _writeMsgBuffer("show\n", 5))
  1409. return;
  1410. flushMessages();
  1411. }
  1412. void CarlaPipeServer::writeFocusMessage() const noexcept
  1413. {
  1414. const CarlaMutexLocker cml(pData->writeLock);
  1415. if (! _writeMsgBuffer("focus\n", 6))
  1416. return;
  1417. flushMessages();
  1418. }
  1419. void CarlaPipeServer::writeHideMessage() const noexcept
  1420. {
  1421. const CarlaMutexLocker cml(pData->writeLock);
  1422. if (! _writeMsgBuffer("show\n", 5))
  1423. return;
  1424. flushMessages();
  1425. }
  1426. // -----------------------------------------------------------------------
  1427. CarlaPipeClient::CarlaPipeClient() noexcept
  1428. : CarlaPipeCommon()
  1429. {
  1430. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  1431. }
  1432. CarlaPipeClient::~CarlaPipeClient() /*noexcept*/
  1433. {
  1434. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  1435. closePipeClient();
  1436. }
  1437. bool CarlaPipeClient::initPipeClient(const char* argv[]) noexcept
  1438. {
  1439. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  1440. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  1441. carla_debug("CarlaPipeClient::initPipeClient(%p)", argv);
  1442. const CarlaMutexLocker cml(pData->writeLock);
  1443. //----------------------------------------------------------------
  1444. // read arguments
  1445. #ifdef CARLA_OS_WIN
  1446. const char* const pipeRecvServerStr = argv[3];
  1447. const char* const pipeSendServerStr = argv[4];
  1448. HANDLE pipeRecvServer = ::CreateFileA(pipeRecvServerStr, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1449. HANDLE pipeSendServer = ::CreateFileA(pipeSendServerStr, GENERIC_WRITE, 0x0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  1450. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  1451. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  1452. #else
  1453. const int pipeRecvServer = std::atoi(argv[3]);
  1454. const int pipeSendServer = std::atoi(argv[4]);
  1455. /* */ int pipeRecvClient = std::atoi(argv[5]);
  1456. /* */ int pipeSendClient = std::atoi(argv[6]);
  1457. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  1458. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  1459. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  1460. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  1461. //----------------------------------------------------------------
  1462. // close duplicated handles used by the client
  1463. try { ::close(pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  1464. try { ::close(pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  1465. //----------------------------------------------------------------
  1466. // kill ourselves if parent dies
  1467. carla_terminateProcessOnParentExit(false);
  1468. #endif
  1469. //----------------------------------------------------------------
  1470. // done
  1471. pData->pipeRecv = pipeRecvServer;
  1472. pData->pipeSend = pipeSendServer;
  1473. pData->pipeClosed = false;
  1474. pData->clientClosingDown = false;
  1475. if (writeMessage("\n", 1))
  1476. flushMessages();
  1477. return true;
  1478. }
  1479. void CarlaPipeClient::closePipeClient() noexcept
  1480. {
  1481. carla_debug("CarlaPipeClient::closePipeClient()");
  1482. pData->pipeClosed = true;
  1483. const CarlaMutexLocker cml(pData->writeLock);
  1484. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1485. {
  1486. #ifdef CARLA_OS_WIN
  1487. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1488. #else
  1489. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1490. #endif
  1491. pData->pipeRecv = INVALID_PIPE_VALUE;
  1492. }
  1493. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1494. {
  1495. #ifdef CARLA_OS_WIN
  1496. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1497. #else
  1498. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1499. #endif
  1500. pData->pipeSend = INVALID_PIPE_VALUE;
  1501. }
  1502. }
  1503. void CarlaPipeClient::writeExitingMessageAndWait() noexcept
  1504. {
  1505. {
  1506. const CarlaMutexLocker cml(pData->writeLock);
  1507. if (_writeMsgBuffer("exiting\n", 8))
  1508. flushMessages();
  1509. }
  1510. // NOTE: no more messages are handled after this point
  1511. pData->clientClosingDown = true;
  1512. for (int i=0; i < 100 && ! pData->pipeClosed; ++i)
  1513. {
  1514. carla_msleep(50);
  1515. idlePipe(true);
  1516. }
  1517. if (! pData->pipeClosed)
  1518. carla_stderr2("writeExitingMessageAndWait pipe is still running!");
  1519. }
  1520. // -----------------------------------------------------------------------
  1521. #undef INVALID_PIPE_VALUE