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.

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