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.

1248 lines
34KB

  1. /*
  2. * Carla Utility Tests
  3. * Copyright (C) 2013-2014 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 "juce_core.h"
  20. #include <clocale>
  21. #ifdef CARLA_OS_WIN
  22. # include <ctime>
  23. #else
  24. # include <cerrno>
  25. # include <fcntl.h>
  26. # include <signal.h>
  27. # include <sys/wait.h>
  28. #endif
  29. #ifdef CARLA_OS_WIN
  30. # define INVALID_PIPE_VALUE INVALID_HANDLE_VALUE
  31. #else
  32. # define INVALID_PIPE_VALUE -1
  33. #endif
  34. #ifdef CARLA_OS_WIN
  35. // -----------------------------------------------------------------------
  36. // win32 stuff
  37. struct OverlappedEvent {
  38. OVERLAPPED over;
  39. OverlappedEvent()
  40. : over()
  41. {
  42. carla_zeroStruct(over);
  43. over.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
  44. }
  45. ~OverlappedEvent()
  46. {
  47. ::CloseHandle(over.hEvent);
  48. }
  49. CARLA_DECLARE_NON_COPY_STRUCT(OverlappedEvent)
  50. };
  51. static inline
  52. ssize_t ReadFileNonBlock(const HANDLE pipeh, const HANDLE cancelh, void* buf, size_t numBytes)
  53. {
  54. DWORD dsize;
  55. OverlappedEvent over;
  56. if (::ReadFile(pipeh, buf, numBytes, &dsize, &over.over) != FALSE)
  57. return static_cast<ssize_t>(dsize);
  58. if (GetLastError() == ERROR_IO_PENDING)
  59. {
  60. HANDLE handles[] = { over.over.hEvent, cancelh };
  61. if (WaitForMultipleObjects(2, handles, FALSE, 0) != WAIT_OBJECT_0)
  62. {
  63. CancelIo(pipeh);
  64. return -1;
  65. }
  66. if (GetOverlappedResult(pipeh, &over.over, &dsize, FALSE) != FALSE)
  67. return static_cast<ssize_t>(dsize);
  68. }
  69. return -1;
  70. }
  71. #endif // CARLA_OS_WIN
  72. // -----------------------------------------------------------------------
  73. // startProcess
  74. #ifdef CARLA_OS_WIN
  75. static inline
  76. bool startProcess(const char* const argv[], PROCESS_INFORMATION& processInfo)
  77. {
  78. using juce::String;
  79. String command;
  80. for (int i=0; argv[i] != nullptr; ++i)
  81. {
  82. String arg(argv[i]);
  83. // If there are spaces, surround it with quotes. If there are quotes,
  84. // replace them with \" so that CommandLineToArgv will correctly parse them.
  85. if (arg.containsAnyOf("\" "))
  86. arg = arg.replace("\"", "\\\"").quoted();
  87. command << arg << ' ';
  88. }
  89. command = command.trim();
  90. STARTUPINFOW startupInfo;
  91. carla_zeroStruct(startupInfo);
  92. //# if 1
  93. startupInfo.hStdInput = INVALID_HANDLE_VALUE;
  94. startupInfo.hStdOutput = INVALID_HANDLE_VALUE;
  95. startupInfo.hStdError = INVALID_HANDLE_VALUE;
  96. startupInfo.dwFlags = STARTF_USESTDHANDLES;
  97. //# endif
  98. startupInfo.cb = sizeof(STARTUPINFOW);
  99. return CreateProcessW(nullptr, const_cast<LPWSTR>(command.toWideCharPointer()),
  100. nullptr, nullptr, TRUE, 0x0, nullptr, nullptr, &startupInfo, &processInfo) != FALSE;
  101. }
  102. #else
  103. static inline
  104. bool startProcess(const char* const argv[], pid_t& pidinst) noexcept
  105. {
  106. const pid_t ret = pidinst = vfork();
  107. switch (ret)
  108. {
  109. case 0: { // child process
  110. execvp(argv[0], const_cast<char* const*>(argv));
  111. CarlaString error(std::strerror(errno));
  112. carla_stderr2("exec failed: %s", error.buffer());
  113. _exit(0); // this is not noexcept safe but doesn't matter anyway
  114. } break;
  115. case -1: { // error
  116. CarlaString error(std::strerror(errno));
  117. carla_stderr2("fork() failed: %s", error.buffer());
  118. _exit(0); // this is not noexcept safe but doesn't matter anyway
  119. } break;
  120. }
  121. return (ret > 0);
  122. }
  123. #endif
  124. // -----------------------------------------------------------------------
  125. // waitForClientFirstMessage
  126. template<typename P>
  127. static inline
  128. bool waitForClientFirstMessage(const P& pipe, const uint32_t timeOutMilliseconds) noexcept
  129. {
  130. #ifdef CARLA_OS_WIN
  131. CARLA_SAFE_ASSERT_RETURN(pipe.handle != INVALID_HANDLE_VALUE, false);
  132. CARLA_SAFE_ASSERT_RETURN(pipe.cancel != INVALID_HANDLE_VALUE, false);
  133. #else
  134. CARLA_SAFE_ASSERT_RETURN(pipe > 0, false);
  135. #endif
  136. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  137. char c;
  138. ssize_t ret;
  139. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  140. for (;;)
  141. {
  142. try {
  143. #ifdef CARLA_OS_WIN
  144. ret = ::ReadFileNonBlock(pipe.handle, pipe.cancel, &c, 1);
  145. #else
  146. ret = ::read(pipe, &c, 1);
  147. #endif
  148. } CARLA_SAFE_EXCEPTION_BREAK("read pipefd");
  149. switch (ret)
  150. {
  151. case -1: // failed to read
  152. #ifndef CARLA_OS_WIN
  153. if (errno == EAGAIN)
  154. #endif
  155. {
  156. if (juce::Time::getMillisecondCounter() < timeoutEnd)
  157. {
  158. carla_msleep(5);
  159. continue;
  160. }
  161. carla_stderr("waitForClientFirstMessage() - timed out");
  162. }
  163. #ifndef CARLA_OS_WIN
  164. else
  165. {
  166. carla_stderr("waitForClientFirstMessage() - read failed");
  167. CarlaString error(std::strerror(errno));
  168. carla_stderr("waitForClientFirstMessage() - read failed: %s", error.buffer());
  169. }
  170. #endif
  171. break;
  172. case 1: // read ok
  173. if (c == '\n')
  174. {
  175. // success
  176. return true;
  177. }
  178. else
  179. {
  180. carla_stderr("waitForClientFirstMessage() - read has wrong first char '%c'", c);
  181. }
  182. break;
  183. default: // ???
  184. carla_stderr("waitForClientFirstMessage() - read returned %i", int(ret));
  185. break;
  186. }
  187. break;
  188. }
  189. return false;
  190. }
  191. // -----------------------------------------------------------------------
  192. // waitForChildToStop / waitForProcessToStop
  193. #ifdef CARLA_OS_WIN
  194. static inline
  195. bool waitForProcessToStop(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  196. {
  197. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE, false);
  198. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  199. // TODO - this code is completly wrong...
  200. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  201. for (;;)
  202. {
  203. if (WaitForSingleObject(processInfo.hProcess, 0) == WAIT_OBJECT_0)
  204. return true;
  205. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  206. break;
  207. carla_msleep(5);
  208. }
  209. return false;
  210. }
  211. static inline
  212. void waitForProcessToStopOrKillIt(const PROCESS_INFORMATION& processInfo, const uint32_t timeOutMilliseconds) noexcept
  213. {
  214. CARLA_SAFE_ASSERT_RETURN(processInfo.hProcess != INVALID_HANDLE_VALUE,);
  215. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  216. if (! waitForProcessToStop(processInfo, timeOutMilliseconds))
  217. {
  218. carla_stderr("waitForProcessToStopOrKillIt() - process didn't stop, force termination");
  219. if (TerminateProcess(processInfo.hProcess, 0) != FALSE)
  220. {
  221. // wait for process to stop
  222. waitForProcessToStop(processInfo, timeOutMilliseconds);
  223. }
  224. }
  225. }
  226. #else
  227. static inline
  228. bool waitForChildToStop(const pid_t pid, const uint32_t timeOutMilliseconds) noexcept
  229. {
  230. CARLA_SAFE_ASSERT_RETURN(pid > 0, false);
  231. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0, false);
  232. pid_t ret;
  233. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  234. for (;;)
  235. {
  236. try {
  237. ret = ::waitpid(pid, nullptr, WNOHANG);
  238. } CARLA_SAFE_EXCEPTION_BREAK("waitpid");
  239. switch (ret)
  240. {
  241. case -1:
  242. if (errno == ECHILD)
  243. {
  244. // success, child doesn't exist
  245. return true;
  246. }
  247. else
  248. {
  249. CarlaString error(std::strerror(errno));
  250. carla_stderr("waitForChildToStop() - waitpid failed: %s", error.buffer());
  251. return false;
  252. }
  253. break;
  254. case 0:
  255. if (juce::Time::getMillisecondCounter() < timeoutEnd)
  256. {
  257. carla_msleep(5);
  258. continue;
  259. }
  260. carla_stderr("waitForChildToStop() - timed out");
  261. break;
  262. default:
  263. if (ret == pid)
  264. {
  265. // success
  266. return true;
  267. }
  268. else
  269. {
  270. carla_stderr("waitForChildToStop() - got wrong pid %i (requested was %i)", int(ret), int(pid));
  271. return false;
  272. }
  273. }
  274. break;
  275. }
  276. return false;
  277. }
  278. static inline
  279. void waitForChildToStopOrKillIt(pid_t& pid, const uint32_t timeOutMilliseconds) noexcept
  280. {
  281. CARLA_SAFE_ASSERT_RETURN(pid > 0,);
  282. CARLA_SAFE_ASSERT_RETURN(timeOutMilliseconds > 0,);
  283. if (! waitForChildToStop(pid, timeOutMilliseconds))
  284. {
  285. carla_stderr("waitForChildToStopOrKillIt() - process didn't stop, force killing");
  286. if (::kill(pid, SIGKILL) != -1)
  287. {
  288. // wait for killing to take place
  289. waitForChildToStop(pid, timeOutMilliseconds);
  290. }
  291. else
  292. {
  293. CarlaString error(std::strerror(errno));
  294. carla_stderr("waitForChildToStopOrKillIt() - kill failed: %s", error.buffer());
  295. }
  296. }
  297. }
  298. #endif
  299. // -----------------------------------------------------------------------
  300. struct CarlaPipeCommon::PrivateData {
  301. // pipes
  302. #ifdef CARLA_OS_WIN
  303. PROCESS_INFORMATION processInfo;
  304. HANDLE cancelEvent;
  305. HANDLE pipeRecv;
  306. HANDLE pipeSend;
  307. #else
  308. pid_t pid;
  309. int pipeRecv;
  310. int pipeSend;
  311. #endif
  312. // read functions must only be called in context of idle()
  313. bool isReading;
  314. // common write lock
  315. CarlaMutex writeLock;
  316. // temporary buffers for readline()
  317. char tmpBuf[0xff+1];
  318. CarlaString tmpStr;
  319. PrivateData() noexcept
  320. #ifdef CARLA_OS_WIN
  321. : processInfo(),
  322. cancelEvent(INVALID_HANDLE_VALUE),
  323. #else
  324. : pid(-1),
  325. #endif
  326. pipeRecv(INVALID_PIPE_VALUE),
  327. pipeSend(INVALID_PIPE_VALUE),
  328. isReading(false),
  329. writeLock(),
  330. tmpBuf(),
  331. tmpStr()
  332. {
  333. #ifdef CARLA_OS_WIN
  334. carla_zeroStruct(processInfo);
  335. try {
  336. cancelEvent = ::CreateEvent(nullptr, FALSE, FALSE, nullptr);
  337. } CARLA_SAFE_EXCEPTION("CreateEvent");
  338. #endif
  339. carla_zeroChar(tmpBuf, 0xff+1);
  340. }
  341. ~PrivateData() noexcept
  342. {
  343. #ifdef CARLA_OS_WIN
  344. if (cancelEvent != INVALID_HANDLE_VALUE)
  345. {
  346. ::CloseHandle(cancelEvent);
  347. cancelEvent = INVALID_HANDLE_VALUE;
  348. }
  349. #endif
  350. }
  351. CARLA_DECLARE_NON_COPY_STRUCT(PrivateData)
  352. };
  353. // -----------------------------------------------------------------------
  354. CarlaPipeCommon::CarlaPipeCommon() noexcept
  355. : pData(new PrivateData()),
  356. leakDetector_CarlaPipeCommon()
  357. {
  358. carla_debug("CarlaPipeCommon::CarlaPipeCommon()");
  359. }
  360. CarlaPipeCommon::~CarlaPipeCommon() noexcept
  361. {
  362. carla_debug("CarlaPipeCommon::~CarlaPipeCommon()");
  363. delete pData;
  364. }
  365. // -------------------------------------------------------------------
  366. void CarlaPipeCommon::idle() noexcept
  367. {
  368. const char* locale = nullptr;
  369. for (;;)
  370. {
  371. const char* const msg(readline());
  372. if (msg == nullptr)
  373. break;
  374. if (locale == nullptr)
  375. {
  376. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  377. ::setlocale(LC_NUMERIC, "C");
  378. }
  379. pData->isReading = true;
  380. try {
  381. msgReceived(msg);
  382. } CARLA_SAFE_EXCEPTION("msgReceived");
  383. pData->isReading = false;
  384. delete[] msg;
  385. }
  386. if (locale != nullptr)
  387. {
  388. ::setlocale(LC_NUMERIC, locale);
  389. delete[] locale;
  390. }
  391. }
  392. bool CarlaPipeCommon::isRunning() const noexcept
  393. {
  394. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE);
  395. }
  396. // -------------------------------------------------------------------
  397. void CarlaPipeCommon::lock() const noexcept
  398. {
  399. pData->writeLock.lock();
  400. }
  401. bool CarlaPipeCommon::tryLock() const noexcept
  402. {
  403. return pData->writeLock.tryLock();
  404. }
  405. void CarlaPipeCommon::unlock() const noexcept
  406. {
  407. pData->writeLock.unlock();
  408. }
  409. CarlaMutex& CarlaPipeCommon::getLock() noexcept
  410. {
  411. return pData->writeLock;
  412. }
  413. // -------------------------------------------------------------------
  414. bool CarlaPipeCommon::readNextLineAsBool(bool& value) noexcept
  415. {
  416. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  417. if (const char* const msg = readlineblock())
  418. {
  419. value = (std::strcmp(msg, "true") == 0);
  420. delete[] msg;
  421. return true;
  422. }
  423. return false;
  424. }
  425. bool CarlaPipeCommon::readNextLineAsInt(int32_t& value) noexcept
  426. {
  427. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  428. if (const char* const msg = readlineblock())
  429. {
  430. value = std::atoi(msg);
  431. delete[] msg;
  432. return true;
  433. }
  434. return false;
  435. }
  436. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) noexcept
  437. {
  438. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  439. if (const char* const msg = readlineblock())
  440. {
  441. int32_t tmp = std::atoi(msg);
  442. delete[] msg;
  443. if (tmp >= 0)
  444. {
  445. value = static_cast<uint32_t>(tmp);
  446. return true;
  447. }
  448. }
  449. return false;
  450. }
  451. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) noexcept
  452. {
  453. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  454. if (const char* const msg = readlineblock())
  455. {
  456. value = std::atol(msg);
  457. delete[] msg;
  458. return true;
  459. }
  460. return false;
  461. }
  462. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) noexcept
  463. {
  464. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  465. if (const char* const msg = readlineblock())
  466. {
  467. int64_t tmp = std::atol(msg);
  468. delete[] msg;
  469. if (tmp >= 0)
  470. {
  471. value = static_cast<uint64_t>(tmp);
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. bool CarlaPipeCommon::readNextLineAsFloat(float& value) noexcept
  478. {
  479. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  480. if (const char* const msg = readlineblock())
  481. {
  482. value = static_cast<float>(std::atof(msg));
  483. delete[] msg;
  484. return true;
  485. }
  486. return false;
  487. }
  488. bool CarlaPipeCommon::readNextLineAsDouble(double& value) noexcept
  489. {
  490. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  491. if (const char* const msg = readlineblock())
  492. {
  493. value = std::atof(msg);
  494. delete[] msg;
  495. return true;
  496. }
  497. return false;
  498. }
  499. bool CarlaPipeCommon::readNextLineAsString(const char*& value) noexcept
  500. {
  501. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  502. if (const char* const msg = readlineblock())
  503. {
  504. value = msg;
  505. return true;
  506. }
  507. return false;
  508. }
  509. // -------------------------------------------------------------------
  510. // must be locked before calling
  511. bool CarlaPipeCommon::writeMsg(const char* const msg) const noexcept
  512. {
  513. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  514. const std::size_t size(std::strlen(msg));
  515. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  516. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  517. return writeMsgBuffer(msg, size);
  518. }
  519. bool CarlaPipeCommon::writeMsg(const char* const msg, std::size_t size) const noexcept
  520. {
  521. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  522. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  523. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  524. return writeMsgBuffer(msg, size);
  525. }
  526. bool CarlaPipeCommon::writeAndFixMsg(const char* const msg) noexcept
  527. {
  528. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  529. const std::size_t size(std::strlen(msg));
  530. char fixedMsg[size+2];
  531. if (size > 0)
  532. {
  533. std::strcpy(fixedMsg, msg);
  534. for (size_t i=0; i < size; ++i)
  535. {
  536. if (fixedMsg[i] == '\n')
  537. fixedMsg[i] = '\r';
  538. }
  539. if (fixedMsg[size-1] == '\r')
  540. {
  541. fixedMsg[size-1] = '\n';
  542. fixedMsg[size] = '\0';
  543. fixedMsg[size+1] = '\0';
  544. }
  545. else
  546. {
  547. fixedMsg[size] = '\n';
  548. fixedMsg[size+1] = '\0';
  549. }
  550. }
  551. else
  552. {
  553. fixedMsg[0] = '\n';
  554. fixedMsg[1] = '\0';
  555. }
  556. return writeMsgBuffer(fixedMsg, size+1);
  557. }
  558. // -------------------------------------------------------------------
  559. // internal
  560. const char* CarlaPipeCommon::readline() noexcept
  561. {
  562. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  563. char c;
  564. char* ptr = pData->tmpBuf;
  565. ssize_t ret;
  566. pData->tmpStr.clear();
  567. for (int i=0; i < 0xff; ++i)
  568. {
  569. try {
  570. #ifdef CARLA_OS_WIN
  571. ret = ::ReadFileNonBlock(pData->pipeRecv, pData->cancelEvent, &c, 1);
  572. #else
  573. ret = ::read(pData->pipeRecv, &c, 1);
  574. #endif
  575. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  576. if (ret == 1 && c != '\n')
  577. {
  578. if (c == '\r')
  579. c = '\n';
  580. *ptr++ = c;
  581. if (i+1 == 0xff)
  582. {
  583. i = 0;
  584. ptr = pData->tmpBuf;
  585. pData->tmpStr += pData->tmpBuf;
  586. }
  587. continue;
  588. }
  589. if (pData->tmpStr.isNotEmpty() || ptr != pData->tmpBuf)
  590. {
  591. if (ptr != pData->tmpBuf)
  592. {
  593. *ptr = '\0';
  594. pData->tmpStr += pData->tmpBuf;
  595. }
  596. try {
  597. return pData->tmpStr.dup();
  598. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  599. }
  600. break;
  601. }
  602. return nullptr;
  603. }
  604. const char* CarlaPipeCommon::readlineblock(const uint32_t timeOutMilliseconds) noexcept
  605. {
  606. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  607. for (;;)
  608. {
  609. if (const char* const msg = readline())
  610. return msg;
  611. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  612. break;
  613. carla_msleep(5);
  614. }
  615. carla_stderr("readlineblock timed out");
  616. return nullptr;
  617. }
  618. bool CarlaPipeCommon::writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  619. {
  620. // TESTING remove later (replace with trylock scope)
  621. if (pData->writeLock.tryLock())
  622. {
  623. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  624. pData->writeLock.unlock();
  625. return false;
  626. }
  627. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  628. try {
  629. #ifdef CARLA_OS_WIN
  630. return (::WriteFile(pData->pipeSend, msg, size, nullptr, nullptr) != FALSE);
  631. #else
  632. return (::write(pData->pipeSend, msg, size) == static_cast<ssize_t>(size));
  633. #endif
  634. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  635. }
  636. // -----------------------------------------------------------------------
  637. CarlaPipeServer::CarlaPipeServer() noexcept
  638. : CarlaPipeCommon(),
  639. leakDetector_CarlaPipeServer()
  640. {
  641. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  642. }
  643. CarlaPipeServer::~CarlaPipeServer() noexcept
  644. {
  645. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  646. stop(5*1000);
  647. }
  648. // -----------------------------------------------------------------------
  649. bool CarlaPipeServer::start(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  650. {
  651. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  652. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  653. #ifdef CARLA_OS_WIN
  654. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == nullptr, false);
  655. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == nullptr, false);
  656. #else
  657. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  658. #endif
  659. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  660. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  661. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  662. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  663. const CarlaMutexLocker cml(pData->writeLock);
  664. //----------------------------------------------------------------
  665. // create pipes
  666. #ifdef CARLA_OS_WIN
  667. HANDLE pipe1[2]; // read by server, written by client
  668. HANDLE pipe2[2]; // read by client, written by server
  669. SECURITY_ATTRIBUTES sa;
  670. carla_zeroStruct(sa);
  671. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  672. sa.bInheritHandle = TRUE;
  673. std::srand(static_cast<uint>(std::time(nullptr)));
  674. char strBuf[0xff+1];
  675. strBuf[0xff] = '\0';
  676. static ulong sCounter = 0;
  677. ++sCounter;
  678. const int randint = std::rand();
  679. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  680. pipe1[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  681. pipe1[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  682. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  683. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  684. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  685. if (pipe1[0] == INVALID_HANDLE_VALUE || pipe1[1] == INVALID_HANDLE_VALUE || pipe2[0] == INVALID_HANDLE_VALUE || pipe2[1] == INVALID_HANDLE_VALUE)
  686. {
  687. if (pipe1[0] != INVALID_HANDLE_VALUE) {
  688. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  689. }
  690. if (pipe1[1] != INVALID_HANDLE_VALUE) {
  691. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  692. }
  693. if (pipe2[0] != INVALID_HANDLE_VALUE) {
  694. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  695. }
  696. if (pipe2[1] != INVALID_HANDLE_VALUE) {
  697. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  698. }
  699. fail("pipe creation failed");
  700. return false;
  701. }
  702. HANDLE pipeRecvServer = pipe1[0];
  703. HANDLE pipeRecvClient = pipe2[0];
  704. HANDLE pipeSendClient = pipe1[1];
  705. HANDLE pipeSendServer = pipe2[1];
  706. #else
  707. int pipe1[2]; // read by server, written by client
  708. int pipe2[2]; // read by client, written by server
  709. if (::pipe(pipe1) != 0)
  710. {
  711. fail("pipe1 creation failed");
  712. return false;
  713. }
  714. if (::pipe(pipe2) != 0)
  715. {
  716. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  717. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  718. fail("pipe2 creation failed");
  719. return false;
  720. }
  721. int pipeRecvServer = pipe1[0];
  722. int pipeRecvClient = pipe2[0];
  723. int pipeSendClient = pipe1[1];
  724. int pipeSendServer = pipe2[1];
  725. #endif
  726. //----------------------------------------------------------------
  727. // set arguments
  728. const char* argv[8];
  729. //----------------------------------------------------------------
  730. // argv[0] => filename
  731. argv[0] = filename;
  732. //----------------------------------------------------------------
  733. // argv[1-2] => args
  734. argv[1] = arg1;
  735. argv[2] = arg2;
  736. //----------------------------------------------------------------
  737. // argv[3-6] => pipes
  738. char pipeRecvServerStr[100+1];
  739. char pipeRecvClientStr[100+1];
  740. char pipeSendServerStr[100+1];
  741. char pipeSendClientStr[100+1];
  742. std::snprintf(pipeRecvServerStr, 100, P_INTPTR, (intptr_t)pipeRecvServer); // pipe1[0]
  743. std::snprintf(pipeRecvClientStr, 100, P_INTPTR, (intptr_t)pipeRecvClient); // pipe2[0]
  744. std::snprintf(pipeSendServerStr, 100, P_INTPTR, (intptr_t)pipeSendServer); // pipe2[1]
  745. std::snprintf(pipeSendClientStr, 100, P_INTPTR, (intptr_t)pipeSendClient); // pipe1[1]
  746. pipeRecvServerStr[100] = '\0';
  747. pipeRecvClientStr[100] = '\0';
  748. pipeSendServerStr[100] = '\0';
  749. pipeSendClientStr[100] = '\0';
  750. argv[3] = pipeRecvServerStr; // pipe1[0] close READ
  751. argv[4] = pipeRecvClientStr; // pipe2[0] READ
  752. argv[5] = pipeSendServerStr; // pipe2[1] close SEND
  753. argv[6] = pipeSendClientStr; // pipe1[1] SEND
  754. //----------------------------------------------------------------
  755. // argv[7] => null
  756. argv[7] = nullptr;
  757. //----------------------------------------------------------------
  758. // start process
  759. #ifdef CARLA_OS_WIN
  760. if (! startProcess(argv, pData->processInfo))
  761. {
  762. carla_zeroStruct(pData->processInfo);
  763. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  764. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  765. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  766. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  767. fail("startProcess() failed");
  768. return false;
  769. }
  770. // just to make sure
  771. CARLA_SAFE_ASSERT(pData->processInfo.hThread != nullptr);
  772. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != nullptr);
  773. #else
  774. if (! startProcess(argv, pData->pid))
  775. {
  776. pData->pid = -1;
  777. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  778. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  779. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  780. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  781. fail("startProcess() failed");
  782. return false;
  783. }
  784. #endif
  785. //----------------------------------------------------------------
  786. // close duplicated handles used by the client
  787. #ifdef CARLA_OS_WIN
  788. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  789. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  790. #else
  791. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  792. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  793. #endif
  794. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  795. #ifndef CARLA_OS_WIN
  796. //----------------------------------------------------------------
  797. // set non-block reading
  798. int ret = 0;
  799. try {
  800. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  801. } catch (...) {
  802. ret = -1;
  803. fail("failed to set pipe as non-block");
  804. }
  805. #endif
  806. //----------------------------------------------------------------
  807. // wait for client to say something
  808. #ifdef CARLA_OS_WIN
  809. struct { HANDLE handle; HANDLE cancel; } pipe;
  810. pipe.handle = pipeRecvClient;
  811. pipe.cancel = pData->cancelEvent;
  812. if ( waitForClientFirstMessage(pipe, 10*1000 /* 10 secs */))
  813. #else
  814. if (ret != -1 && waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  815. #endif
  816. {
  817. pData->pipeRecv = pipeRecvClient;
  818. pData->pipeSend = pipeSendClient;
  819. carla_stdout("ALL OK!");
  820. return true;
  821. }
  822. //----------------------------------------------------------------
  823. // failed to set non-block or get first child message, cannot continue
  824. #ifdef CARLA_OS_WIN
  825. if (TerminateProcess(pData->processInfo.hProcess, 0) != FALSE)
  826. {
  827. // wait for process to stop
  828. waitForProcessToStop(pData->processInfo, 2*1000);
  829. }
  830. // clear pData->processInfo
  831. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  832. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  833. carla_zeroStruct(pData->processInfo);
  834. #else
  835. if (::kill(pData->pid, SIGKILL) != -1)
  836. {
  837. // wait for killing to take place
  838. waitForChildToStop(pData->pid, 2*1000);
  839. }
  840. pData->pid = -1;
  841. #endif
  842. //----------------------------------------------------------------
  843. // close pipes
  844. #ifdef CARLA_OS_WIN
  845. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  846. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  847. #else
  848. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  849. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  850. #endif
  851. return false;
  852. }
  853. void CarlaPipeServer::stop(const uint32_t timeOutMilliseconds) noexcept
  854. {
  855. carla_debug("CarlaPipeServer::stop(%i)", timeOutMilliseconds);
  856. #ifdef CARLA_OS_WIN
  857. if (pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  858. {
  859. const CarlaMutexLocker cml(pData->writeLock);
  860. if (pData->pipeSend != INVALID_PIPE_VALUE)
  861. writeMsgBuffer("quit\n", 5);
  862. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  863. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  864. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  865. carla_zeroStruct(pData->processInfo);
  866. }
  867. #else
  868. if (pData->pid != -1)
  869. {
  870. const CarlaMutexLocker cml(pData->writeLock);
  871. if (pData->pipeSend != INVALID_PIPE_VALUE)
  872. writeMsgBuffer("quit\n", 5);
  873. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  874. pData->pid = -1;
  875. }
  876. #endif
  877. close();
  878. }
  879. void CarlaPipeServer::close() noexcept
  880. {
  881. carla_debug("CarlaPipeServer::close()");
  882. const CarlaMutexLocker cml(pData->writeLock);
  883. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  884. {
  885. #ifdef CARLA_OS_WIN
  886. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  887. #else
  888. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  889. #endif
  890. pData->pipeRecv = INVALID_PIPE_VALUE;
  891. }
  892. if (pData->pipeSend != INVALID_PIPE_VALUE)
  893. {
  894. #ifdef CARLA_OS_WIN
  895. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  896. #else
  897. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  898. #endif
  899. pData->pipeSend = INVALID_PIPE_VALUE;
  900. }
  901. }
  902. // -----------------------------------------------------------------------
  903. CarlaPipeClient::CarlaPipeClient() noexcept
  904. : CarlaPipeCommon(),
  905. leakDetector_CarlaPipeClient()
  906. {
  907. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  908. }
  909. CarlaPipeClient::~CarlaPipeClient() noexcept
  910. {
  911. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  912. close();
  913. }
  914. bool CarlaPipeClient::init(char* argv[]) noexcept
  915. {
  916. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  917. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  918. const CarlaMutexLocker cml(pData->writeLock);
  919. //----------------------------------------------------------------
  920. // read arguments
  921. #ifdef CARLA_OS_WIN
  922. HANDLE pipeRecvServer = (HANDLE)std::atol(argv[3]); // READ
  923. HANDLE pipeRecvClient = (HANDLE)std::atol(argv[4]);
  924. HANDLE pipeSendServer = (HANDLE)std::atol(argv[5]); // SEND
  925. HANDLE pipeSendClient = (HANDLE)std::atol(argv[6]);
  926. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  927. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient != INVALID_HANDLE_VALUE, false);
  928. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  929. CARLA_SAFE_ASSERT_RETURN(pipeSendClient != INVALID_HANDLE_VALUE, false);
  930. #else
  931. int pipeRecvServer = std::atoi(argv[3]); // READ
  932. int pipeRecvClient = std::atoi(argv[4]);
  933. int pipeSendServer = std::atoi(argv[5]); // SEND
  934. int pipeSendClient = std::atoi(argv[6]);
  935. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  936. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  937. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  938. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  939. #endif
  940. //----------------------------------------------------------------
  941. // close duplicated handles used by the client
  942. #ifdef CARLA_OS_WIN
  943. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  944. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  945. #else
  946. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  947. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  948. #endif
  949. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  950. #ifndef CARLA_OS_WIN
  951. //----------------------------------------------------------------
  952. // set non-block reading
  953. int ret = 0;
  954. try {
  955. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  956. } catch (...) {
  957. ret = -1;
  958. }
  959. CARLA_SAFE_ASSERT_RETURN(ret != -1, false);
  960. #endif
  961. //----------------------------------------------------------------
  962. // done
  963. pData->pipeRecv = pipeRecvServer;
  964. pData->pipeSend = pipeSendServer;
  965. writeMsg("\n");
  966. return true;
  967. }
  968. void CarlaPipeClient::close() noexcept
  969. {
  970. carla_debug("CarlaPipeClient::close()");
  971. const CarlaMutexLocker cml(pData->writeLock);
  972. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  973. {
  974. #ifdef CARLA_OS_WIN
  975. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  976. #else
  977. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  978. #endif
  979. pData->pipeRecv = INVALID_PIPE_VALUE;
  980. }
  981. if (pData->pipeSend != INVALID_PIPE_VALUE)
  982. {
  983. #ifdef CARLA_OS_WIN
  984. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  985. #else
  986. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  987. #endif
  988. pData->pipeSend = INVALID_PIPE_VALUE;
  989. }
  990. }
  991. // -----------------------------------------------------------------------
  992. ScopedLocale::ScopedLocale() noexcept
  993. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  994. {
  995. ::setlocale(LC_NUMERIC, "C");
  996. }
  997. ScopedLocale::~ScopedLocale() noexcept
  998. {
  999. if (fLocale != nullptr)
  1000. {
  1001. ::setlocale(LC_NUMERIC, fLocale);
  1002. delete[] fLocale;
  1003. }
  1004. }
  1005. // -----------------------------------------------------------------------
  1006. #undef INVALID_PIPE_VALUE