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.

CarlaPipeUtils.cpp 44KB

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