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.

1861 lines
50KB

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