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

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