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.

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