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.

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