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 45KB

10 years ago
9 years ago
10 years ago
9 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  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. #include "juce_core.h"
  21. // needed for atom-util
  22. #ifndef nullptr
  23. # undef NULL
  24. # define NULL nullptr
  25. #endif
  26. #include "lv2/atom-util.h"
  27. #include <clocale>
  28. #ifdef CARLA_OS_WIN
  29. # include <ctime>
  30. #else
  31. # include <cerrno>
  32. # include <fcntl.h>
  33. # include <signal.h>
  34. # include <sys/wait.h>
  35. #endif
  36. #ifdef CARLA_OS_WIN
  37. # define INVALID_PIPE_VALUE INVALID_HANDLE_VALUE
  38. #else
  39. # define INVALID_PIPE_VALUE -1
  40. #endif
  41. #ifdef CARLA_OS_WIN
  42. // -----------------------------------------------------------------------
  43. // win32 stuff
  44. struct OverlappedEvent {
  45. OVERLAPPED over;
  46. OverlappedEvent()
  47. : over()
  48. {
  49. carla_zeroStruct(over);
  50. over.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
  51. }
  52. ~OverlappedEvent()
  53. {
  54. ::CloseHandle(over.hEvent);
  55. }
  56. CARLA_DECLARE_NON_COPY_STRUCT(OverlappedEvent)
  57. };
  58. // -----------------------------------------------------------------------
  59. // ReadFile
  60. static inline
  61. ssize_t ReadFileBlock(const HANDLE pipeh, void* const buf, const std::size_t numBytes)
  62. {
  63. DWORD dsize;
  64. if (::ReadFile(pipeh, buf, numBytes, &dsize, nullptr) != FALSE)
  65. return static_cast<ssize_t>(dsize);
  66. return -1;
  67. }
  68. static inline
  69. ssize_t ReadFileNonBlock(const HANDLE pipeh, const HANDLE cancelh, void* const buf, const std::size_t numBytes)
  70. {
  71. DWORD dsize = numBytes;
  72. OverlappedEvent over;
  73. if (::ReadFile(pipeh, buf, numBytes, nullptr /*&dsize*/, &over.over) != FALSE)
  74. return static_cast<ssize_t>(dsize);
  75. if (::GetLastError() == ERROR_IO_PENDING)
  76. {
  77. HANDLE handles[] = { over.over.hEvent, cancelh };
  78. if (::WaitForMultipleObjects(2, handles, FALSE, 0) != WAIT_OBJECT_0)
  79. {
  80. ::CancelIo(pipeh);
  81. return -1;
  82. }
  83. if (::GetOverlappedResult(pipeh, &over.over, nullptr /*&dsize*/, FALSE) != FALSE)
  84. return static_cast<ssize_t>(dsize);
  85. }
  86. return -1;
  87. }
  88. // -----------------------------------------------------------------------
  89. // WriteFile
  90. static inline
  91. ssize_t WriteFileBlock(const HANDLE pipeh, const void* const buf, const std::size_t numBytes)
  92. {
  93. DWORD dsize;
  94. if (::WriteFile(pipeh, buf, numBytes, &dsize, nullptr) != FALSE)
  95. return static_cast<ssize_t>(dsize);
  96. return -1;
  97. }
  98. static inline
  99. ssize_t WriteFileNonBlock(const HANDLE pipeh, const HANDLE cancelh, const void* const buf, const std::size_t numBytes)
  100. {
  101. DWORD dsize = numBytes;
  102. OverlappedEvent over;
  103. if (::WriteFile(pipeh, buf, numBytes, nullptr /*&dsize*/, &over.over) != FALSE)
  104. return static_cast<ssize_t>(dsize);
  105. if (::GetLastError() == ERROR_IO_PENDING)
  106. {
  107. HANDLE handles[] = { over.over.hEvent, cancelh };
  108. if (::WaitForMultipleObjects(2, handles, FALSE, 0) != WAIT_OBJECT_0)
  109. {
  110. ::CancelIo(pipeh);
  111. return -1;
  112. }
  113. if (::GetOverlappedResult(pipeh, &over.over, &dsize, FALSE) != FALSE)
  114. return static_cast<ssize_t>(dsize);
  115. }
  116. return -1;
  117. }
  118. #endif // CARLA_OS_WIN
  119. // -----------------------------------------------------------------------
  120. // startProcess
  121. #ifdef CARLA_OS_WIN
  122. static inline
  123. bool startProcess(const char* const argv[], PROCESS_INFORMATION* const processInfo)
  124. {
  125. CARLA_SAFE_ASSERT_RETURN(processInfo != nullptr, false);
  126. using juce::String;
  127. String command;
  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. ScopedEnvVar::ScopedEnvVar(const char* const key, const char* const value) noexcept
  1241. : fKey(nullptr),
  1242. fOrigValue(nullptr)
  1243. {
  1244. CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',);
  1245. fKey = carla_strdup_safe(key);
  1246. CARLA_SAFE_ASSERT_RETURN(fKey != nullptr,);
  1247. if (const char* const origValue = std::getenv(key))
  1248. {
  1249. fOrigValue = carla_strdup_safe(origValue);
  1250. CARLA_SAFE_ASSERT_RETURN(fOrigValue != nullptr,);
  1251. }
  1252. if (value != nullptr)
  1253. carla_setenv(key, value);
  1254. else if (fOrigValue != nullptr)
  1255. carla_unsetenv(key);
  1256. }
  1257. ScopedEnvVar::~ScopedEnvVar() noexcept
  1258. {
  1259. bool hasOrigValue = false;
  1260. if (fOrigValue != nullptr)
  1261. {
  1262. hasOrigValue = true;
  1263. carla_setenv(fKey, fOrigValue);
  1264. delete[] fOrigValue;
  1265. fOrigValue = nullptr;
  1266. }
  1267. if (fKey != nullptr)
  1268. {
  1269. if (! hasOrigValue)
  1270. carla_unsetenv(fKey);
  1271. delete[] fKey;
  1272. fKey = nullptr;
  1273. }
  1274. }
  1275. // -----------------------------------------------------------------------
  1276. ScopedLocale::ScopedLocale() noexcept
  1277. : fLocale(carla_strdup_safe(::setlocale(LC_NUMERIC, nullptr)))
  1278. {
  1279. ::setlocale(LC_NUMERIC, "C");
  1280. }
  1281. ScopedLocale::~ScopedLocale() noexcept
  1282. {
  1283. if (fLocale != nullptr)
  1284. {
  1285. ::setlocale(LC_NUMERIC, fLocale);
  1286. delete[] fLocale;
  1287. }
  1288. }
  1289. // -----------------------------------------------------------------------
  1290. #undef INVALID_PIPE_VALUE