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.

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