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.

1888 lines
51KB

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