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.

1304 lines
36KB

  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 idle()
  337. bool isReading;
  338. // common write lock
  339. CarlaMutex writeLock;
  340. // temporary buffers for readline()
  341. char tmpBuf[0xff+1];
  342. 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. void CarlaPipeCommon::idle() noexcept
  391. {
  392. const char* locale = nullptr;
  393. for (;;)
  394. {
  395. const char* const msg(readline());
  396. if (msg == nullptr)
  397. break;
  398. if (locale == nullptr)
  399. {
  400. locale = carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr));
  401. ::setlocale(LC_NUMERIC, "C");
  402. }
  403. pData->isReading = true;
  404. try {
  405. msgReceived(msg);
  406. } CARLA_SAFE_EXCEPTION("msgReceived");
  407. pData->isReading = false;
  408. delete[] msg;
  409. }
  410. if (locale != nullptr)
  411. {
  412. ::setlocale(LC_NUMERIC, locale);
  413. delete[] locale;
  414. }
  415. }
  416. bool CarlaPipeCommon::isRunning() const noexcept
  417. {
  418. return (pData->pipeRecv != INVALID_PIPE_VALUE && pData->pipeSend != INVALID_PIPE_VALUE);
  419. }
  420. // -------------------------------------------------------------------
  421. void CarlaPipeCommon::lock() const noexcept
  422. {
  423. pData->writeLock.lock();
  424. }
  425. bool CarlaPipeCommon::tryLock() const noexcept
  426. {
  427. return pData->writeLock.tryLock();
  428. }
  429. void CarlaPipeCommon::unlock() const noexcept
  430. {
  431. pData->writeLock.unlock();
  432. }
  433. CarlaMutex& CarlaPipeCommon::getLock() noexcept
  434. {
  435. return pData->writeLock;
  436. }
  437. // -------------------------------------------------------------------
  438. bool CarlaPipeCommon::readNextLineAsBool(bool& value) 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::readNextLineAsInt(int32_t& value) noexcept
  450. {
  451. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  452. if (const char* const msg = readlineblock())
  453. {
  454. value = std::atoi(msg);
  455. delete[] msg;
  456. return true;
  457. }
  458. return false;
  459. }
  460. bool CarlaPipeCommon::readNextLineAsUInt(uint32_t& value) noexcept
  461. {
  462. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  463. if (const char* const msg = readlineblock())
  464. {
  465. int32_t tmp = std::atoi(msg);
  466. delete[] msg;
  467. if (tmp >= 0)
  468. {
  469. value = static_cast<uint32_t>(tmp);
  470. return true;
  471. }
  472. }
  473. return false;
  474. }
  475. bool CarlaPipeCommon::readNextLineAsLong(int64_t& value) noexcept
  476. {
  477. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  478. if (const char* const msg = readlineblock())
  479. {
  480. value = std::atol(msg);
  481. delete[] msg;
  482. return true;
  483. }
  484. return false;
  485. }
  486. bool CarlaPipeCommon::readNextLineAsULong(uint64_t& value) noexcept
  487. {
  488. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  489. if (const char* const msg = readlineblock())
  490. {
  491. int64_t tmp = std::atol(msg);
  492. delete[] msg;
  493. if (tmp >= 0)
  494. {
  495. value = static_cast<uint64_t>(tmp);
  496. return true;
  497. }
  498. }
  499. return false;
  500. }
  501. bool CarlaPipeCommon::readNextLineAsFloat(float& value) noexcept
  502. {
  503. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  504. if (const char* const msg = readlineblock())
  505. {
  506. value = static_cast<float>(std::atof(msg));
  507. delete[] msg;
  508. return true;
  509. }
  510. return false;
  511. }
  512. bool CarlaPipeCommon::readNextLineAsDouble(double& value) noexcept
  513. {
  514. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  515. if (const char* const msg = readlineblock())
  516. {
  517. value = std::atof(msg);
  518. delete[] msg;
  519. return true;
  520. }
  521. return false;
  522. }
  523. bool CarlaPipeCommon::readNextLineAsString(const char*& value) noexcept
  524. {
  525. CARLA_SAFE_ASSERT_RETURN(pData->isReading, false);
  526. if (const char* const msg = readlineblock())
  527. {
  528. value = msg;
  529. return true;
  530. }
  531. return false;
  532. }
  533. // -------------------------------------------------------------------
  534. // must be locked before calling
  535. bool CarlaPipeCommon::writeMsg(const char* const msg) const noexcept
  536. {
  537. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  538. const std::size_t size(std::strlen(msg));
  539. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  540. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  541. return writeMsgBuffer(msg, size);
  542. }
  543. bool CarlaPipeCommon::writeMsg(const char* const msg, std::size_t size) const noexcept
  544. {
  545. CARLA_SAFE_ASSERT_RETURN(msg != nullptr && msg[0] != '\0', false);
  546. CARLA_SAFE_ASSERT_RETURN(size > 0, false);
  547. CARLA_SAFE_ASSERT_RETURN(msg[size-1] == '\n', false);
  548. return writeMsgBuffer(msg, size);
  549. }
  550. bool CarlaPipeCommon::writeAndFixMsg(const char* const msg) const noexcept
  551. {
  552. CARLA_SAFE_ASSERT_RETURN(msg != nullptr, false);
  553. const std::size_t size(std::strlen(msg));
  554. char fixedMsg[size+2];
  555. if (size > 0)
  556. {
  557. std::strcpy(fixedMsg, msg);
  558. for (size_t i=0; i < size; ++i)
  559. {
  560. if (fixedMsg[i] == '\n')
  561. fixedMsg[i] = '\r';
  562. }
  563. if (fixedMsg[size-1] == '\r')
  564. {
  565. fixedMsg[size-1] = '\n';
  566. fixedMsg[size] = '\0';
  567. fixedMsg[size+1] = '\0';
  568. }
  569. else
  570. {
  571. fixedMsg[size] = '\n';
  572. fixedMsg[size+1] = '\0';
  573. }
  574. }
  575. else
  576. {
  577. fixedMsg[0] = '\n';
  578. fixedMsg[1] = '\0';
  579. }
  580. return writeMsgBuffer(fixedMsg, size+1);
  581. }
  582. bool CarlaPipeCommon::flush() const noexcept
  583. {
  584. // TESTING remove later (replace with trylock scope)
  585. if (pData->writeLock.tryLock())
  586. {
  587. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  588. pData->writeLock.unlock();
  589. return false;
  590. }
  591. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  592. try {
  593. #ifdef CARLA_OS_WIN
  594. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  595. #else
  596. return (::fsync(pData->pipeSend) == 0);
  597. #endif
  598. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  599. }
  600. // -------------------------------------------------------------------
  601. // internal
  602. const char* CarlaPipeCommon::readline() noexcept
  603. {
  604. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  605. char c;
  606. char* ptr = pData->tmpBuf;
  607. ssize_t ret;
  608. pData->tmpStr.clear();
  609. for (int i=0; i < 0xff; ++i)
  610. {
  611. try {
  612. #ifdef CARLA_OS_WIN
  613. ret = ::ReadFileNonBlock(pData->pipeRecv, pData->cancelEvent, &c, 1);
  614. #else
  615. ret = ::read(pData->pipeRecv, &c, 1);
  616. #endif
  617. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  618. if (ret == 1 && c != '\n')
  619. {
  620. if (c == '\r')
  621. c = '\n';
  622. *ptr++ = c;
  623. if (i+1 == 0xff)
  624. {
  625. i = 0;
  626. ptr = pData->tmpBuf;
  627. pData->tmpStr += pData->tmpBuf;
  628. }
  629. continue;
  630. }
  631. if (pData->tmpStr.isNotEmpty() || ptr != pData->tmpBuf || ret == 1)
  632. {
  633. if (ptr != pData->tmpBuf)
  634. {
  635. *ptr = '\0';
  636. pData->tmpStr += pData->tmpBuf;
  637. }
  638. try {
  639. return pData->tmpStr.dup();
  640. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  641. }
  642. break;
  643. }
  644. return nullptr;
  645. }
  646. const char* CarlaPipeCommon::readlineblock(const uint32_t timeOutMilliseconds) noexcept
  647. {
  648. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  649. for (;;)
  650. {
  651. if (const char* const msg = readline())
  652. return msg;
  653. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  654. break;
  655. carla_msleep(5);
  656. }
  657. carla_stderr("readlineblock timed out");
  658. return nullptr;
  659. }
  660. bool CarlaPipeCommon::writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  661. {
  662. // TESTING remove later (replace with trylock scope)
  663. if (pData->writeLock.tryLock())
  664. {
  665. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  666. pData->writeLock.unlock();
  667. return false;
  668. }
  669. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  670. ssize_t ret;
  671. try {
  672. #ifdef CARLA_OS_WIN
  673. ret = ::WriteFileNonBlock(pData->pipeSend, pData->cancelEvent, msg, size);
  674. #else
  675. ret = ::write(pData->pipeSend, msg, size);
  676. #endif
  677. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  678. return (ret == static_cast<ssize_t>(size));
  679. }
  680. // -----------------------------------------------------------------------
  681. CarlaPipeServer::CarlaPipeServer() noexcept
  682. : CarlaPipeCommon(),
  683. leakDetector_CarlaPipeServer()
  684. {
  685. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  686. }
  687. CarlaPipeServer::~CarlaPipeServer() noexcept
  688. {
  689. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  690. stop(5*1000);
  691. }
  692. // -----------------------------------------------------------------------
  693. bool CarlaPipeServer::start(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  694. {
  695. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  696. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  697. #ifdef CARLA_OS_WIN
  698. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == nullptr, false);
  699. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == nullptr, false);
  700. #else
  701. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  702. #endif
  703. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  704. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  705. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  706. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  707. const CarlaMutexLocker cml(pData->writeLock);
  708. //----------------------------------------------------------------
  709. // create pipes
  710. #ifdef CARLA_OS_WIN
  711. HANDLE pipe1[2]; // read by server, written by client
  712. HANDLE pipe2[2]; // read by client, written by server
  713. SECURITY_ATTRIBUTES sa;
  714. carla_zeroStruct(sa);
  715. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  716. sa.bInheritHandle = TRUE;
  717. std::srand(static_cast<uint>(std::time(nullptr)));
  718. char strBuf[0xff+1];
  719. strBuf[0xff] = '\0';
  720. static ulong sCounter = 0;
  721. ++sCounter;
  722. const int randint = std::rand();
  723. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  724. pipe1[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  725. pipe1[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  726. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  727. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  728. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  729. if (pipe1[0] == INVALID_HANDLE_VALUE || pipe1[1] == INVALID_HANDLE_VALUE || pipe2[0] == INVALID_HANDLE_VALUE || pipe2[1] == INVALID_HANDLE_VALUE)
  730. {
  731. if (pipe1[0] != INVALID_HANDLE_VALUE) {
  732. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  733. }
  734. if (pipe1[1] != INVALID_HANDLE_VALUE) {
  735. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  736. }
  737. if (pipe2[0] != INVALID_HANDLE_VALUE) {
  738. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  739. }
  740. if (pipe2[1] != INVALID_HANDLE_VALUE) {
  741. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  742. }
  743. fail("pipe creation failed");
  744. return false;
  745. }
  746. HANDLE pipeRecvServer = pipe1[0];
  747. HANDLE pipeRecvClient = pipe2[0];
  748. HANDLE pipeSendClient = pipe1[1];
  749. HANDLE pipeSendServer = pipe2[1];
  750. #else
  751. int pipe1[2]; // read by server, written by client
  752. int pipe2[2]; // read by client, written by server
  753. if (::pipe(pipe1) != 0)
  754. {
  755. fail("pipe1 creation failed");
  756. return false;
  757. }
  758. if (::pipe(pipe2) != 0)
  759. {
  760. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  761. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  762. fail("pipe2 creation failed");
  763. return false;
  764. }
  765. int pipeRecvServer = pipe1[0];
  766. int pipeRecvClient = pipe2[0];
  767. int pipeSendClient = pipe1[1];
  768. int pipeSendServer = pipe2[1];
  769. #endif
  770. //----------------------------------------------------------------
  771. // set arguments
  772. const char* argv[8];
  773. //----------------------------------------------------------------
  774. // argv[0] => filename
  775. argv[0] = filename;
  776. //----------------------------------------------------------------
  777. // argv[1-2] => args
  778. argv[1] = arg1;
  779. argv[2] = arg2;
  780. //----------------------------------------------------------------
  781. // argv[3-6] => pipes
  782. char pipeRecvServerStr[100+1];
  783. char pipeRecvClientStr[100+1];
  784. char pipeSendServerStr[100+1];
  785. char pipeSendClientStr[100+1];
  786. std::snprintf(pipeRecvServerStr, 100, P_INTPTR, (intptr_t)pipeRecvServer); // pipe1[0]
  787. std::snprintf(pipeRecvClientStr, 100, P_INTPTR, (intptr_t)pipeRecvClient); // pipe2[0]
  788. std::snprintf(pipeSendServerStr, 100, P_INTPTR, (intptr_t)pipeSendServer); // pipe2[1]
  789. std::snprintf(pipeSendClientStr, 100, P_INTPTR, (intptr_t)pipeSendClient); // pipe1[1]
  790. pipeRecvServerStr[100] = '\0';
  791. pipeRecvClientStr[100] = '\0';
  792. pipeSendServerStr[100] = '\0';
  793. pipeSendClientStr[100] = '\0';
  794. argv[3] = pipeRecvServerStr; // pipe1[0] close READ
  795. argv[4] = pipeRecvClientStr; // pipe2[0] READ
  796. argv[5] = pipeSendServerStr; // pipe2[1] close SEND
  797. argv[6] = pipeSendClientStr; // pipe1[1] SEND
  798. //----------------------------------------------------------------
  799. // argv[7] => null
  800. argv[7] = nullptr;
  801. //----------------------------------------------------------------
  802. // start process
  803. #ifdef CARLA_OS_WIN
  804. if (! startProcess(argv, pData->processInfo))
  805. {
  806. carla_zeroStruct(pData->processInfo);
  807. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  808. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  809. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  810. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  811. fail("startProcess() failed");
  812. return false;
  813. }
  814. // just to make sure
  815. CARLA_SAFE_ASSERT(pData->processInfo.hThread != nullptr);
  816. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != nullptr);
  817. #else
  818. if (! startProcess(argv, pData->pid))
  819. {
  820. pData->pid = -1;
  821. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  822. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  823. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  824. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  825. fail("startProcess() failed");
  826. return false;
  827. }
  828. #endif
  829. //----------------------------------------------------------------
  830. // close duplicated handles used by the client
  831. #ifdef CARLA_OS_WIN
  832. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  833. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  834. #else
  835. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  836. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  837. #endif
  838. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  839. #ifndef CARLA_OS_WIN
  840. //----------------------------------------------------------------
  841. // set non-block reading
  842. int ret = 0;
  843. try {
  844. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  845. } catch (...) {
  846. ret = -1;
  847. fail("failed to set pipe as non-block");
  848. }
  849. #endif
  850. //----------------------------------------------------------------
  851. // wait for client to say something
  852. #ifdef CARLA_OS_WIN
  853. struct { HANDLE handle; HANDLE cancel; } pipe;
  854. pipe.handle = pipeRecvClient;
  855. pipe.cancel = pData->cancelEvent;
  856. if ( waitForClientFirstMessage(pipe, 10*1000 /* 10 secs */))
  857. #else
  858. if (ret != -1 && waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  859. #endif
  860. {
  861. pData->pipeRecv = pipeRecvClient;
  862. pData->pipeSend = pipeSendClient;
  863. carla_stdout("ALL OK!");
  864. return true;
  865. }
  866. //----------------------------------------------------------------
  867. // failed to set non-block or get first child message, cannot continue
  868. #ifdef CARLA_OS_WIN
  869. if (TerminateProcess(pData->processInfo.hProcess, 0) != FALSE)
  870. {
  871. // wait for process to stop
  872. waitForProcessToStop(pData->processInfo, 2*1000);
  873. }
  874. // clear pData->processInfo
  875. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  876. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  877. carla_zeroStruct(pData->processInfo);
  878. #else
  879. if (::kill(pData->pid, SIGKILL) != -1)
  880. {
  881. // wait for killing to take place
  882. waitForChildToStop(pData->pid, 2*1000);
  883. }
  884. pData->pid = -1;
  885. #endif
  886. //----------------------------------------------------------------
  887. // close pipes
  888. #ifdef CARLA_OS_WIN
  889. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  890. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  891. #else
  892. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  893. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  894. #endif
  895. return false;
  896. }
  897. void CarlaPipeServer::stop(const uint32_t timeOutMilliseconds) noexcept
  898. {
  899. carla_debug("CarlaPipeServer::stop(%i)", timeOutMilliseconds);
  900. #ifdef CARLA_OS_WIN
  901. if (pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  902. {
  903. const CarlaMutexLocker cml(pData->writeLock);
  904. if (pData->pipeSend != INVALID_PIPE_VALUE)
  905. writeMsgBuffer("quit\n", 5);
  906. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  907. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  908. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  909. carla_zeroStruct(pData->processInfo);
  910. }
  911. #else
  912. if (pData->pid != -1)
  913. {
  914. const CarlaMutexLocker cml(pData->writeLock);
  915. if (pData->pipeSend != INVALID_PIPE_VALUE)
  916. writeMsgBuffer("quit\n", 5);
  917. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  918. pData->pid = -1;
  919. }
  920. #endif
  921. close();
  922. }
  923. void CarlaPipeServer::close() noexcept
  924. {
  925. carla_debug("CarlaPipeServer::close()");
  926. const CarlaMutexLocker cml(pData->writeLock);
  927. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  928. {
  929. #ifdef CARLA_OS_WIN
  930. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  931. #else
  932. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  933. #endif
  934. pData->pipeRecv = INVALID_PIPE_VALUE;
  935. }
  936. if (pData->pipeSend != INVALID_PIPE_VALUE)
  937. {
  938. #ifdef CARLA_OS_WIN
  939. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  940. #else
  941. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  942. #endif
  943. pData->pipeSend = INVALID_PIPE_VALUE;
  944. }
  945. }
  946. // -----------------------------------------------------------------------
  947. CarlaPipeClient::CarlaPipeClient() noexcept
  948. : CarlaPipeCommon(),
  949. leakDetector_CarlaPipeClient()
  950. {
  951. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  952. }
  953. CarlaPipeClient::~CarlaPipeClient() noexcept
  954. {
  955. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  956. close();
  957. }
  958. bool CarlaPipeClient::init(const char* argv[]) noexcept
  959. {
  960. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  961. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  962. const CarlaMutexLocker cml(pData->writeLock);
  963. //----------------------------------------------------------------
  964. // read arguments
  965. #ifdef CARLA_OS_WIN
  966. HANDLE pipeRecvServer = (HANDLE)std::atol(argv[3]); // READ
  967. HANDLE pipeRecvClient = (HANDLE)std::atol(argv[4]);
  968. HANDLE pipeSendServer = (HANDLE)std::atol(argv[5]); // SEND
  969. HANDLE pipeSendClient = (HANDLE)std::atol(argv[6]);
  970. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  971. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient != INVALID_HANDLE_VALUE, false);
  972. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  973. CARLA_SAFE_ASSERT_RETURN(pipeSendClient != INVALID_HANDLE_VALUE, false);
  974. #else
  975. int pipeRecvServer = std::atoi(argv[3]); // READ
  976. int pipeRecvClient = std::atoi(argv[4]);
  977. int pipeSendServer = std::atoi(argv[5]); // SEND
  978. int pipeSendClient = std::atoi(argv[6]);
  979. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  980. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  981. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  982. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  983. #endif
  984. //----------------------------------------------------------------
  985. // close duplicated handles used by the client
  986. #ifdef CARLA_OS_WIN
  987. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  988. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  989. #else
  990. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  991. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  992. #endif
  993. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  994. #ifndef CARLA_OS_WIN
  995. //----------------------------------------------------------------
  996. // set non-block reading
  997. int ret = 0;
  998. try {
  999. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  1000. } catch (...) {
  1001. ret = -1;
  1002. }
  1003. CARLA_SAFE_ASSERT_RETURN(ret != -1, false);
  1004. #endif
  1005. //----------------------------------------------------------------
  1006. // done
  1007. pData->pipeRecv = pipeRecvServer;
  1008. pData->pipeSend = pipeSendServer;
  1009. writeMsg("\n");
  1010. flush();
  1011. return true;
  1012. }
  1013. void CarlaPipeClient::close() noexcept
  1014. {
  1015. carla_debug("CarlaPipeClient::close()");
  1016. const CarlaMutexLocker cml(pData->writeLock);
  1017. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  1018. {
  1019. #ifdef CARLA_OS_WIN
  1020. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  1021. #else
  1022. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  1023. #endif
  1024. pData->pipeRecv = INVALID_PIPE_VALUE;
  1025. }
  1026. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1027. {
  1028. #ifdef CARLA_OS_WIN
  1029. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1030. #else
  1031. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1032. #endif
  1033. pData->pipeSend = INVALID_PIPE_VALUE;
  1034. }
  1035. }
  1036. // -----------------------------------------------------------------------
  1037. ScopedLocale::ScopedLocale() noexcept
  1038. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1039. {
  1040. ::setlocale(LC_NUMERIC, "C");
  1041. }
  1042. ScopedLocale::~ScopedLocale() noexcept
  1043. {
  1044. if (fLocale != nullptr)
  1045. {
  1046. ::setlocale(LC_NUMERIC, fLocale);
  1047. delete[] fLocale;
  1048. }
  1049. }
  1050. // -----------------------------------------------------------------------
  1051. #undef INVALID_PIPE_VALUE