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

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