Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CarlaPipeUtils.cpp 45KB

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