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.

1913 lines
51KB

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