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.

1324 lines
37KB

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