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.

1270 lines
35KB

  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) const 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. bool CarlaPipeCommon::flush() const noexcept
  559. {
  560. // TESTING remove later (replace with trylock scope)
  561. if (pData->writeLock.tryLock())
  562. {
  563. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  564. pData->writeLock.unlock();
  565. return false;
  566. }
  567. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  568. try {
  569. #ifdef CARLA_OS_WIN
  570. return (::FlushFileBuffers(pData->pipeSend) != FALSE);
  571. #else
  572. return (::fsync(pData->pipeSend) == 0);
  573. #endif
  574. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  575. }
  576. // -------------------------------------------------------------------
  577. // internal
  578. const char* CarlaPipeCommon::readline() noexcept
  579. {
  580. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv != INVALID_PIPE_VALUE, nullptr);
  581. char c;
  582. char* ptr = pData->tmpBuf;
  583. ssize_t ret;
  584. pData->tmpStr.clear();
  585. for (int i=0; i < 0xff; ++i)
  586. {
  587. try {
  588. #ifdef CARLA_OS_WIN
  589. ret = ::ReadFileNonBlock(pData->pipeRecv, pData->cancelEvent, &c, 1);
  590. #else
  591. ret = ::read(pData->pipeRecv, &c, 1);
  592. #endif
  593. } CARLA_SAFE_EXCEPTION_BREAK("CarlaPipeCommon::readline() - read");
  594. if (ret == 1 && c != '\n')
  595. {
  596. if (c == '\r')
  597. c = '\n';
  598. *ptr++ = c;
  599. if (i+1 == 0xff)
  600. {
  601. i = 0;
  602. ptr = pData->tmpBuf;
  603. pData->tmpStr += pData->tmpBuf;
  604. }
  605. continue;
  606. }
  607. if (pData->tmpStr.isNotEmpty() || ptr != pData->tmpBuf || ret == 1)
  608. {
  609. if (ptr != pData->tmpBuf)
  610. {
  611. *ptr = '\0';
  612. pData->tmpStr += pData->tmpBuf;
  613. }
  614. try {
  615. return pData->tmpStr.dup();
  616. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::readline() - dup", nullptr);
  617. }
  618. break;
  619. }
  620. return nullptr;
  621. }
  622. const char* CarlaPipeCommon::readlineblock(const uint32_t timeOutMilliseconds) noexcept
  623. {
  624. const uint32_t timeoutEnd(juce::Time::getMillisecondCounter() + timeOutMilliseconds);
  625. for (;;)
  626. {
  627. if (const char* const msg = readline())
  628. return msg;
  629. if (juce::Time::getMillisecondCounter() >= timeoutEnd)
  630. break;
  631. carla_msleep(5);
  632. }
  633. carla_stderr("readlineblock timed out");
  634. return nullptr;
  635. }
  636. bool CarlaPipeCommon::writeMsgBuffer(const char* const msg, const std::size_t size) const noexcept
  637. {
  638. // TESTING remove later (replace with trylock scope)
  639. if (pData->writeLock.tryLock())
  640. {
  641. carla_safe_assert("! pData->writeLock.tryLock()", __FILE__, __LINE__);
  642. pData->writeLock.unlock();
  643. return false;
  644. }
  645. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend != INVALID_PIPE_VALUE, false);
  646. try {
  647. #ifdef CARLA_OS_WIN
  648. return (::WriteFile(pData->pipeSend, msg, size, nullptr, nullptr) != FALSE);
  649. #else
  650. return (::write(pData->pipeSend, msg, size) == static_cast<ssize_t>(size));
  651. #endif
  652. } CARLA_SAFE_EXCEPTION_RETURN("CarlaPipeCommon::writeMsgBuffer", false);
  653. }
  654. // -----------------------------------------------------------------------
  655. CarlaPipeServer::CarlaPipeServer() noexcept
  656. : CarlaPipeCommon(),
  657. leakDetector_CarlaPipeServer()
  658. {
  659. carla_debug("CarlaPipeServer::CarlaPipeServer()");
  660. }
  661. CarlaPipeServer::~CarlaPipeServer() noexcept
  662. {
  663. carla_debug("CarlaPipeServer::~CarlaPipeServer()");
  664. stop(5*1000);
  665. }
  666. // -----------------------------------------------------------------------
  667. bool CarlaPipeServer::start(const char* const filename, const char* const arg1, const char* const arg2) noexcept
  668. {
  669. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  670. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  671. #ifdef CARLA_OS_WIN
  672. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hThread == nullptr, false);
  673. CARLA_SAFE_ASSERT_RETURN(pData->processInfo.hProcess == nullptr, false);
  674. #else
  675. CARLA_SAFE_ASSERT_RETURN(pData->pid == -1, false);
  676. #endif
  677. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', false);
  678. CARLA_SAFE_ASSERT_RETURN(arg1 != nullptr, false);
  679. CARLA_SAFE_ASSERT_RETURN(arg2 != nullptr, false);
  680. carla_debug("CarlaPipeServer::start(\"%s\", \"%s\", \"%s\")", filename, arg1, arg2);
  681. const CarlaMutexLocker cml(pData->writeLock);
  682. //----------------------------------------------------------------
  683. // create pipes
  684. #ifdef CARLA_OS_WIN
  685. HANDLE pipe1[2]; // read by server, written by client
  686. HANDLE pipe2[2]; // read by client, written by server
  687. SECURITY_ATTRIBUTES sa;
  688. carla_zeroStruct(sa);
  689. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  690. sa.bInheritHandle = TRUE;
  691. std::srand(static_cast<uint>(std::time(nullptr)));
  692. char strBuf[0xff+1];
  693. strBuf[0xff] = '\0';
  694. static ulong sCounter = 0;
  695. ++sCounter;
  696. const int randint = std::rand();
  697. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe1-%i-%li", randint, sCounter);
  698. pipe1[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  699. pipe1[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  700. std::snprintf(strBuf, 0xff, "\\\\.\\pipe\\carla-pipe2-%i-%li", randint, sCounter);
  701. pipe2[0] = ::CreateNamedPipeA(strBuf, PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE|PIPE_WAIT, 1, 4096, 4096, 120*1000, &sa);
  702. pipe2[1] = ::CreateFileA(strBuf, GENERIC_WRITE, 0x0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, nullptr);
  703. if (pipe1[0] == INVALID_HANDLE_VALUE || pipe1[1] == INVALID_HANDLE_VALUE || pipe2[0] == INVALID_HANDLE_VALUE || pipe2[1] == INVALID_HANDLE_VALUE)
  704. {
  705. if (pipe1[0] != INVALID_HANDLE_VALUE) {
  706. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  707. }
  708. if (pipe1[1] != INVALID_HANDLE_VALUE) {
  709. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  710. }
  711. if (pipe2[0] != INVALID_HANDLE_VALUE) {
  712. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  713. }
  714. if (pipe2[1] != INVALID_HANDLE_VALUE) {
  715. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  716. }
  717. fail("pipe creation failed");
  718. return false;
  719. }
  720. HANDLE pipeRecvServer = pipe1[0];
  721. HANDLE pipeRecvClient = pipe2[0];
  722. HANDLE pipeSendClient = pipe1[1];
  723. HANDLE pipeSendServer = pipe2[1];
  724. #else
  725. int pipe1[2]; // read by server, written by client
  726. int pipe2[2]; // read by client, written by server
  727. if (::pipe(pipe1) != 0)
  728. {
  729. fail("pipe1 creation failed");
  730. return false;
  731. }
  732. if (::pipe(pipe2) != 0)
  733. {
  734. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  735. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  736. fail("pipe2 creation failed");
  737. return false;
  738. }
  739. int pipeRecvServer = pipe1[0];
  740. int pipeRecvClient = pipe2[0];
  741. int pipeSendClient = pipe1[1];
  742. int pipeSendServer = pipe2[1];
  743. #endif
  744. //----------------------------------------------------------------
  745. // set arguments
  746. const char* argv[8];
  747. //----------------------------------------------------------------
  748. // argv[0] => filename
  749. argv[0] = filename;
  750. //----------------------------------------------------------------
  751. // argv[1-2] => args
  752. argv[1] = arg1;
  753. argv[2] = arg2;
  754. //----------------------------------------------------------------
  755. // argv[3-6] => pipes
  756. char pipeRecvServerStr[100+1];
  757. char pipeRecvClientStr[100+1];
  758. char pipeSendServerStr[100+1];
  759. char pipeSendClientStr[100+1];
  760. std::snprintf(pipeRecvServerStr, 100, P_INTPTR, (intptr_t)pipeRecvServer); // pipe1[0]
  761. std::snprintf(pipeRecvClientStr, 100, P_INTPTR, (intptr_t)pipeRecvClient); // pipe2[0]
  762. std::snprintf(pipeSendServerStr, 100, P_INTPTR, (intptr_t)pipeSendServer); // pipe2[1]
  763. std::snprintf(pipeSendClientStr, 100, P_INTPTR, (intptr_t)pipeSendClient); // pipe1[1]
  764. pipeRecvServerStr[100] = '\0';
  765. pipeRecvClientStr[100] = '\0';
  766. pipeSendServerStr[100] = '\0';
  767. pipeSendClientStr[100] = '\0';
  768. argv[3] = pipeRecvServerStr; // pipe1[0] close READ
  769. argv[4] = pipeRecvClientStr; // pipe2[0] READ
  770. argv[5] = pipeSendServerStr; // pipe2[1] close SEND
  771. argv[6] = pipeSendClientStr; // pipe1[1] SEND
  772. //----------------------------------------------------------------
  773. // argv[7] => null
  774. argv[7] = nullptr;
  775. //----------------------------------------------------------------
  776. // start process
  777. #ifdef CARLA_OS_WIN
  778. if (! startProcess(argv, pData->processInfo))
  779. {
  780. carla_zeroStruct(pData->processInfo);
  781. try { ::CloseHandle(pipe1[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[0])");
  782. try { ::CloseHandle(pipe1[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe1[1])");
  783. try { ::CloseHandle(pipe2[0]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[0])");
  784. try { ::CloseHandle(pipe2[1]); } CARLA_SAFE_EXCEPTION("CloseHandle(pipe2[1])");
  785. fail("startProcess() failed");
  786. return false;
  787. }
  788. // just to make sure
  789. CARLA_SAFE_ASSERT(pData->processInfo.hThread != nullptr);
  790. CARLA_SAFE_ASSERT(pData->processInfo.hProcess != nullptr);
  791. #else
  792. if (! startProcess(argv, pData->pid))
  793. {
  794. pData->pid = -1;
  795. try { ::close(pipe1[0]); } CARLA_SAFE_EXCEPTION("close(pipe1[0])");
  796. try { ::close(pipe1[1]); } CARLA_SAFE_EXCEPTION("close(pipe1[1])");
  797. try { ::close(pipe2[0]); } CARLA_SAFE_EXCEPTION("close(pipe2[0])");
  798. try { ::close(pipe2[1]); } CARLA_SAFE_EXCEPTION("close(pipe2[1])");
  799. fail("startProcess() failed");
  800. return false;
  801. }
  802. #endif
  803. //----------------------------------------------------------------
  804. // close duplicated handles used by the client
  805. #ifdef CARLA_OS_WIN
  806. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  807. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  808. #else
  809. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  810. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  811. #endif
  812. pipeRecvServer = pipeSendServer = INVALID_PIPE_VALUE;
  813. #ifndef CARLA_OS_WIN
  814. //----------------------------------------------------------------
  815. // set non-block reading
  816. int ret = 0;
  817. try {
  818. ret = ::fcntl(pipeRecvClient, F_SETFL, ::fcntl(pipeRecvClient, F_GETFL) | O_NONBLOCK);
  819. } catch (...) {
  820. ret = -1;
  821. fail("failed to set pipe as non-block");
  822. }
  823. #endif
  824. //----------------------------------------------------------------
  825. // wait for client to say something
  826. #ifdef CARLA_OS_WIN
  827. struct { HANDLE handle; HANDLE cancel; } pipe;
  828. pipe.handle = pipeRecvClient;
  829. pipe.cancel = pData->cancelEvent;
  830. if ( waitForClientFirstMessage(pipe, 10*1000 /* 10 secs */))
  831. #else
  832. if (ret != -1 && waitForClientFirstMessage(pipeRecvClient, 10*1000 /* 10 secs */))
  833. #endif
  834. {
  835. pData->pipeRecv = pipeRecvClient;
  836. pData->pipeSend = pipeSendClient;
  837. carla_stdout("ALL OK!");
  838. return true;
  839. }
  840. //----------------------------------------------------------------
  841. // failed to set non-block or get first child message, cannot continue
  842. #ifdef CARLA_OS_WIN
  843. if (TerminateProcess(pData->processInfo.hProcess, 0) != FALSE)
  844. {
  845. // wait for process to stop
  846. waitForProcessToStop(pData->processInfo, 2*1000);
  847. }
  848. // clear pData->processInfo
  849. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  850. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  851. carla_zeroStruct(pData->processInfo);
  852. #else
  853. if (::kill(pData->pid, SIGKILL) != -1)
  854. {
  855. // wait for killing to take place
  856. waitForChildToStop(pData->pid, 2*1000);
  857. }
  858. pData->pid = -1;
  859. #endif
  860. //----------------------------------------------------------------
  861. // close pipes
  862. #ifdef CARLA_OS_WIN
  863. try { ::CloseHandle(pipeRecvServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvServer)");
  864. try { ::CloseHandle(pipeSendServer); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendServer)");
  865. #else
  866. try { ::close (pipeRecvServer); } CARLA_SAFE_EXCEPTION("close(pipeRecvServer)");
  867. try { ::close (pipeSendServer); } CARLA_SAFE_EXCEPTION("close(pipeSendServer)");
  868. #endif
  869. return false;
  870. }
  871. void CarlaPipeServer::stop(const uint32_t timeOutMilliseconds) noexcept
  872. {
  873. carla_debug("CarlaPipeServer::stop(%i)", timeOutMilliseconds);
  874. #ifdef CARLA_OS_WIN
  875. if (pData->processInfo.hProcess != INVALID_HANDLE_VALUE)
  876. {
  877. const CarlaMutexLocker cml(pData->writeLock);
  878. if (pData->pipeSend != INVALID_PIPE_VALUE)
  879. writeMsgBuffer("quit\n", 5);
  880. waitForProcessToStopOrKillIt(pData->processInfo, timeOutMilliseconds);
  881. try { CloseHandle(pData->processInfo.hThread); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hThread)");
  882. try { CloseHandle(pData->processInfo.hProcess); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->processInfo.hProcess)");
  883. carla_zeroStruct(pData->processInfo);
  884. }
  885. #else
  886. if (pData->pid != -1)
  887. {
  888. const CarlaMutexLocker cml(pData->writeLock);
  889. if (pData->pipeSend != INVALID_PIPE_VALUE)
  890. writeMsgBuffer("quit\n", 5);
  891. waitForChildToStopOrKillIt(pData->pid, timeOutMilliseconds);
  892. pData->pid = -1;
  893. }
  894. #endif
  895. close();
  896. }
  897. void CarlaPipeServer::close() noexcept
  898. {
  899. carla_debug("CarlaPipeServer::close()");
  900. const CarlaMutexLocker cml(pData->writeLock);
  901. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  902. {
  903. #ifdef CARLA_OS_WIN
  904. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  905. #else
  906. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  907. #endif
  908. pData->pipeRecv = INVALID_PIPE_VALUE;
  909. }
  910. if (pData->pipeSend != INVALID_PIPE_VALUE)
  911. {
  912. #ifdef CARLA_OS_WIN
  913. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  914. #else
  915. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  916. #endif
  917. pData->pipeSend = INVALID_PIPE_VALUE;
  918. }
  919. }
  920. // -----------------------------------------------------------------------
  921. CarlaPipeClient::CarlaPipeClient() noexcept
  922. : CarlaPipeCommon(),
  923. leakDetector_CarlaPipeClient()
  924. {
  925. carla_debug("CarlaPipeClient::CarlaPipeClient()");
  926. }
  927. CarlaPipeClient::~CarlaPipeClient() noexcept
  928. {
  929. carla_debug("CarlaPipeClient::~CarlaPipeClient()");
  930. close();
  931. }
  932. bool CarlaPipeClient::init(char* argv[]) noexcept
  933. {
  934. CARLA_SAFE_ASSERT_RETURN(pData->pipeRecv == INVALID_PIPE_VALUE, false);
  935. CARLA_SAFE_ASSERT_RETURN(pData->pipeSend == INVALID_PIPE_VALUE, false);
  936. const CarlaMutexLocker cml(pData->writeLock);
  937. //----------------------------------------------------------------
  938. // read arguments
  939. #ifdef CARLA_OS_WIN
  940. HANDLE pipeRecvServer = (HANDLE)std::atol(argv[3]); // READ
  941. HANDLE pipeRecvClient = (HANDLE)std::atol(argv[4]);
  942. HANDLE pipeSendServer = (HANDLE)std::atol(argv[5]); // SEND
  943. HANDLE pipeSendClient = (HANDLE)std::atol(argv[6]);
  944. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer != INVALID_HANDLE_VALUE, false);
  945. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient != INVALID_HANDLE_VALUE, false);
  946. CARLA_SAFE_ASSERT_RETURN(pipeSendServer != INVALID_HANDLE_VALUE, false);
  947. CARLA_SAFE_ASSERT_RETURN(pipeSendClient != INVALID_HANDLE_VALUE, false);
  948. #else
  949. int pipeRecvServer = std::atoi(argv[3]); // READ
  950. int pipeRecvClient = std::atoi(argv[4]);
  951. int pipeSendServer = std::atoi(argv[5]); // SEND
  952. int pipeSendClient = std::atoi(argv[6]);
  953. CARLA_SAFE_ASSERT_RETURN(pipeRecvServer > 0, false);
  954. CARLA_SAFE_ASSERT_RETURN(pipeRecvClient > 0, false);
  955. CARLA_SAFE_ASSERT_RETURN(pipeSendServer > 0, false);
  956. CARLA_SAFE_ASSERT_RETURN(pipeSendClient > 0, false);
  957. #endif
  958. //----------------------------------------------------------------
  959. // close duplicated handles used by the client
  960. #ifdef CARLA_OS_WIN
  961. try { ::CloseHandle(pipeRecvClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeRecvClient)");
  962. try { ::CloseHandle(pipeSendClient); } CARLA_SAFE_EXCEPTION("CloseHandle(pipeSendClient)");
  963. #else
  964. try { ::close (pipeRecvClient); } CARLA_SAFE_EXCEPTION("close(pipeRecvClient)");
  965. try { ::close (pipeSendClient); } CARLA_SAFE_EXCEPTION("close(pipeSendClient)");
  966. #endif
  967. pipeRecvClient = pipeSendClient = INVALID_PIPE_VALUE;
  968. #ifndef CARLA_OS_WIN
  969. //----------------------------------------------------------------
  970. // set non-block reading
  971. int ret = 0;
  972. try {
  973. ret = ::fcntl(pipeRecvServer, F_SETFL, ::fcntl(pipeRecvServer, F_GETFL) | O_NONBLOCK);
  974. } catch (...) {
  975. ret = -1;
  976. }
  977. CARLA_SAFE_ASSERT_RETURN(ret != -1, false);
  978. #endif
  979. //----------------------------------------------------------------
  980. // done
  981. pData->pipeRecv = pipeRecvServer;
  982. pData->pipeSend = pipeSendServer;
  983. writeMsg("\n");
  984. flush();
  985. return true;
  986. }
  987. void CarlaPipeClient::close() noexcept
  988. {
  989. carla_debug("CarlaPipeClient::close()");
  990. const CarlaMutexLocker cml(pData->writeLock);
  991. if (pData->pipeRecv != INVALID_PIPE_VALUE)
  992. {
  993. #ifdef CARLA_OS_WIN
  994. try { ::CloseHandle(pData->pipeRecv); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeRecv)");
  995. #else
  996. try { ::close (pData->pipeRecv); } CARLA_SAFE_EXCEPTION("close(pData->pipeRecv)");
  997. #endif
  998. pData->pipeRecv = INVALID_PIPE_VALUE;
  999. }
  1000. if (pData->pipeSend != INVALID_PIPE_VALUE)
  1001. {
  1002. #ifdef CARLA_OS_WIN
  1003. try { ::CloseHandle(pData->pipeSend); } CARLA_SAFE_EXCEPTION("CloseHandle(pData->pipeSend)");
  1004. #else
  1005. try { ::close (pData->pipeSend); } CARLA_SAFE_EXCEPTION("close(pData->pipeSend)");
  1006. #endif
  1007. pData->pipeSend = INVALID_PIPE_VALUE;
  1008. }
  1009. }
  1010. // -----------------------------------------------------------------------
  1011. ScopedLocale::ScopedLocale() noexcept
  1012. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1013. {
  1014. ::setlocale(LC_NUMERIC, "C");
  1015. }
  1016. ScopedLocale::~ScopedLocale() noexcept
  1017. {
  1018. if (fLocale != nullptr)
  1019. {
  1020. ::setlocale(LC_NUMERIC, fLocale);
  1021. delete[] fLocale;
  1022. }
  1023. }
  1024. // -----------------------------------------------------------------------
  1025. #undef INVALID_PIPE_VALUE