llpluginprocessparent.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. /**
  2. * @file llpluginprocessparent.cpp
  3. * @brief LLPluginProcessParent handles the parent side of the external-process plugin API.
  4. *
  5. * $LicenseInfo:firstyear=2008&license=viewergpl$
  6. *
  7. * Copyright (c) 2008-2009, Linden Research, Inc.
  8. * Copyright (c) 2009-2024, Henri Beauchamp.
  9. *
  10. * Second Life Viewer Source Code
  11. * The source code in this file ("Source Code") is provided by Linden Lab
  12. * to you under the terms of the GNU General Public License, version 2.0
  13. * ("GPL"), unless you have obtained a separate licensing agreement
  14. * ("Other License"), formally executed by you and Linden Lab. Terms of
  15. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  16. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  17. *
  18. * There are special exceptions to the terms and conditions of the GPL as
  19. * it is applied to this Source Code. View the full text of the exception
  20. * in the file doc/FLOSS-exception.txt in this software distribution, or
  21. * online at
  22. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  23. *
  24. * By copying, modifying or distributing this software, you acknowledge
  25. * that you have read and understood your obligations described above,
  26. * and agree to abide by those obligations.
  27. *
  28. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  29. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  30. * COMPLETENESS OR PERFORMANCE.
  31. * $/LicenseInfo$
  32. */
  33. #include "linden_common.h"
  34. #include "llpluginprocessparent.h"
  35. #include "llapp.h"
  36. #include "llapr.h"
  37. #include "llpluginmessagepipe.h"
  38. #include "llpluginmessageclasses.h"
  39. #include "llsdserialize.h"
  40. #include "llworkqueue.h"
  41. // Used in mPluginName to distinguish plugin instances in log messages. HB
  42. static U32 sPluginNumber = 0;
  43. std::string LLPluginProcessParent::sMediaBrowserVersion;
  44. apr_pollset_t* LLPluginProcessParent::sPollSet = NULL;
  45. bool LLPluginProcessParent::sPollsetNeedsRebuild = false;
  46. bool LLPluginProcessParent::sUseReadThread = false;
  47. LLThread* LLPluginProcessParent::sReadThread = NULL;
  48. LLMutex LLPluginProcessParent::sInstancesMutex;
  49. LLPluginProcessParent::instances_map_t LLPluginProcessParent::sInstances;
  50. class LLPluginProcessParentPollThread final : public LLThread
  51. {
  52. public:
  53. LLPluginProcessParentPollThread()
  54. : LLThread("LLPluginProcessParentPollThread")
  55. {
  56. }
  57. protected:
  58. // Inherited from LLThread
  59. void run() override
  60. {
  61. while (!isQuitting() && LLPluginProcessParent::getUseReadThread())
  62. {
  63. bool active = LLPluginProcessParent::poll(0.1f);
  64. checkPause();
  65. ms_sleep(active ? 1 : 10); // Do not eat-up a full CPU core !!!
  66. }
  67. // Final poll to clean up the pollset, etc.
  68. LLPluginProcessParent::poll(0.f);
  69. }
  70. // Inherited from LLThread
  71. LL_INLINE bool runCondition() override
  72. {
  73. return LLPluginProcessParent::canPollThreadRun();
  74. }
  75. };
  76. //static
  77. LLPluginProcessParent::ptr_t LLPluginProcessParent::create(LLPluginProcessParentOwner* ownerp)
  78. {
  79. ptr_t self(new LLPluginProcessParent(ownerp));
  80. // Do not add to the global list until fully constructed.
  81. sInstancesMutex.lock();
  82. sInstances.emplace(self.get(), self);
  83. sInstancesMutex.unlock();
  84. return self;
  85. }
  86. //static
  87. void LLPluginProcessParent::shutdown()
  88. {
  89. sInstancesMutex.lock();
  90. if (!sInstances.empty())
  91. {
  92. for (instances_map_t::iterator it = sInstances.begin();
  93. it != sInstances.end(); ++it)
  94. {
  95. if (it->second->mState.get() < STATE_GOODBYE)
  96. {
  97. it->second->requestShutdown();
  98. }
  99. }
  100. sInstances.clear();
  101. }
  102. sInstancesMutex.unlock();
  103. }
  104. LLPluginProcessParent::LLPluginProcessParent(LLPluginProcessParentOwner* ownerp)
  105. : mOwner(ownerp),
  106. mState(STATE_UNINITIALIZED),
  107. mBoundPort(0),
  108. mSleepTime(0.01),
  109. mCPUUsage(0.0),
  110. mPluginLaunchTimeout(60.f),
  111. mPluginLockupTimeout(15.f),
  112. mProcessStartRequested(false),
  113. mProcessStarted(false),
  114. mDisableTimeout(false),
  115. mPolledInput(false),
  116. mBlocked(false),
  117. mDebug(false)
  118. {
  119. llassert_always(mOwner);
  120. mPollFD.client_data = NULL;
  121. // Do not start the timer here: start it when we actually launch the plugin
  122. // process.
  123. mHeartbeat.stop();
  124. }
  125. LLPluginProcessParent::~LLPluginProcessParent()
  126. {
  127. LL_DEBUGS("Plugin") << "Destructor called" << LL_ENDL;
  128. // Destroy any remaining shared memory regions
  129. shared_mem_regions_t::iterator iter;
  130. while ((iter = mSharedMemoryRegions.begin()) != mSharedMemoryRegions.end())
  131. {
  132. // Destroy the shared memory region
  133. iter->second->destroy();
  134. delete iter->second;
  135. iter->second = NULL;
  136. // And remove it from our map
  137. mSharedMemoryRegions.erase(iter);
  138. }
  139. mProcess.kill();
  140. if (!LLApp::isQuitting())
  141. {
  142. // If we are quitting, the sockets will already have been destroyed.
  143. killSockets();
  144. }
  145. if (mPolling.connected())
  146. {
  147. mPolling.disconnect();
  148. }
  149. }
  150. void LLPluginProcessParent::requestShutdown()
  151. {
  152. setState(STATE_GOODBYE);
  153. mOwner = NULL;
  154. if (LLApp::isError())
  155. {
  156. if (mPolling.connected())
  157. {
  158. mPolling.disconnect();
  159. }
  160. // If we are crashing, run the idle once more since there will be no
  161. // polling.
  162. idle();
  163. removeFromProcessing();
  164. return;
  165. }
  166. // *HACK: after this method has been called, our previous owner will no
  167. // longer call our idle() method. Tie into the main event loop here to do
  168. // that until we are good and finished.
  169. static S32 count = 0;
  170. std::string name = llformat("LLPluginProcessParentListener%d", ++count);
  171. LL_DEBUGS("Plugin") << "Listening on 'mainloop' for: " << name << LL_ENDL;
  172. LLEventPump& pump = gEventPumps.obtain("mainloop");
  173. mPolling = pump.listen(name,
  174. boost::bind(&LLPluginProcessParent::pollTick,
  175. this));
  176. }
  177. bool LLPluginProcessParent::pollTick()
  178. {
  179. if (mState.get() != STATE_DONE)
  180. {
  181. idle();
  182. return false;
  183. }
  184. // This grabs a copy of the smart pointer to ourselves to ensure that we do
  185. // not get destroyed until after this method returns.
  186. ptr_t self;
  187. sInstancesMutex.lock();
  188. instances_map_t::iterator it = sInstances.find(this);
  189. if (it != sInstances.end())
  190. {
  191. self = it->second;
  192. }
  193. sInstancesMutex.unlock();
  194. removeFromProcessing();
  195. return true;
  196. }
  197. // Removes our instance from the global list before beginning destruction.
  198. void LLPluginProcessParent::removeFromProcessing()
  199. {
  200. // Make sure to get the global mutex _first_ here, to avoid a possible
  201. // deadlock against LLPluginProcessParent::poll()
  202. sInstancesMutex.lock();
  203. {
  204. mIncomingQueueMutex.lock();
  205. sInstances.erase(this);
  206. mIncomingQueueMutex.unlock();
  207. }
  208. sInstancesMutex.unlock();
  209. }
  210. bool LLPluginProcessParent::wantsPolling() const
  211. {
  212. return mState.get() != STATE_DONE && mPollFD.client_data;
  213. }
  214. void LLPluginProcessParent::killSockets()
  215. {
  216. mIncomingQueueMutex.lock();
  217. killMessagePipe();
  218. mIncomingQueueMutex.unlock();
  219. mListenSocket.reset();
  220. mSocket.reset();
  221. }
  222. std::string LLPluginProcessParent::state2string(U32 state)
  223. {
  224. std::string result = "UNKNOWN";
  225. // Prevent copy-paste errors when updating this list...
  226. #define CASE(x) case x: result = #x; break
  227. switch (state)
  228. {
  229. CASE(STATE_UNINITIALIZED);
  230. CASE(STATE_INITIALIZED);
  231. CASE(STATE_LISTENING);
  232. CASE(STATE_LAUNCHED);
  233. CASE(STATE_CONNECTED);
  234. CASE(STATE_HELLO);
  235. CASE(STATE_LOADING);
  236. CASE(STATE_RUNNING);
  237. CASE(STATE_GOODBYE);
  238. CASE(STATE_LAUNCH_FAILURE);
  239. CASE(STATE_ERROR);
  240. CASE(STATE_CLEANUP);
  241. CASE(STATE_EXITING);
  242. CASE(STATE_DONE);
  243. default:
  244. break;
  245. }
  246. #undef CASE
  247. return result;
  248. }
  249. void LLPluginProcessParent::errorState()
  250. {
  251. if (mState.get() < STATE_RUNNING)
  252. {
  253. llwarns << "Launching failure in state " << state2string(mState.get())
  254. << " with: " << mPluginName << llendl;
  255. setState(STATE_LAUNCH_FAILURE);
  256. }
  257. else
  258. {
  259. llwarns << "Error encountered in state " << state2string(mState.get())
  260. << " with: " << mPluginName << llendl;
  261. setState(STATE_ERROR);
  262. }
  263. }
  264. void LLPluginProcessParent::init(const std::string& launcher_filename,
  265. const std::string& plugin_dir,
  266. const std::string& plugin_filename,
  267. bool debug)
  268. {
  269. mProcess.setExecutable(launcher_filename);
  270. mProcess.setWorkingDirectory(plugin_dir);
  271. mPluginFile = mPluginName = plugin_filename;
  272. // Remove the file extension from the name. HB
  273. size_t i = mPluginName.rfind('.');
  274. if (i != std::string::npos)
  275. {
  276. mPluginName.erase(i);
  277. }
  278. // Remove the directory path from the name. HB
  279. #if LL_WINDOWS
  280. i = mPluginName.rfind('\\');
  281. #else
  282. i = mPluginName.rfind('/');
  283. #endif
  284. if (i != std::string::npos)
  285. {
  286. mPluginName = mPluginName.substr(i + 1);
  287. }
  288. mPluginName += llformat(" #%d", ++sPluginNumber);
  289. mPluginDir = plugin_dir;
  290. mCPUUsage = 0.0;
  291. mDebug = debug;
  292. setState(STATE_INITIALIZED);
  293. }
  294. bool LLPluginProcessParent::accept()
  295. {
  296. if (!mListenSocket)
  297. {
  298. return false;
  299. }
  300. apr_socket_t* new_socket = NULL;
  301. apr_status_t status = apr_socket_accept(&new_socket,
  302. mListenSocket->getSocket(),
  303. gAPRPoolp);
  304. if (status == APR_SUCCESS)
  305. {
  306. LL_DEBUGS("Plugin") << mPluginName << ": APR SUCCESS" << LL_ENDL;
  307. // Success. Create a message pipe on the new socket
  308. // We MUST create a new pool for the LLSocket, since it will take
  309. // ownership of it and delete it in its destructor!
  310. apr_pool_t* new_pool = NULL;
  311. status = apr_pool_create(&new_pool, gAPRPoolp);
  312. mSocket = LLSocket::create(new_socket, new_pool);
  313. new LLPluginMessagePipe(this, mSocket);
  314. return true;
  315. }
  316. if (APR_STATUS_IS_EAGAIN(status))
  317. {
  318. LL_DEBUGS("Plugin") << mPluginName << ": APR EAGAIN" << LL_ENDL;
  319. // No incoming connections. This is not an error.
  320. status = APR_SUCCESS;
  321. }
  322. else
  323. {
  324. LL_DEBUGS("Plugin") << mPluginName << ": APR Error:" << LL_ENDL;
  325. ll_apr_warn_status(status);
  326. // Some other error.
  327. errorState();
  328. }
  329. return false;
  330. }
  331. bool LLPluginProcessParent::createPluginProcess()
  332. {
  333. if (!mProcessStarted)
  334. {
  335. // Only argument to the launcher is the port number we are listening
  336. // on
  337. std::stringstream stream;
  338. stream << mBoundPort;
  339. mProcess.addArgument(stream.str());
  340. mProcessStarted = mProcess.launch() == 0;
  341. }
  342. return mProcessStarted;
  343. }
  344. void LLPluginProcessParent::idle()
  345. {
  346. bool idle_again;
  347. do
  348. {
  349. // Process queued messages
  350. // Inside main thread, it is preferable not to block it on mutex.
  351. bool locked = mIncomingQueueMutex.trylock();
  352. while (locked && !mIncomingQueue.empty())
  353. {
  354. LLPluginMessage message = mIncomingQueue.front();
  355. mIncomingQueue.pop();
  356. mIncomingQueueMutex.unlock();
  357. receiveMessage(message);
  358. locked = mIncomingQueueMutex.trylock();
  359. }
  360. if (locked)
  361. {
  362. mIncomingQueueMutex.unlock();
  363. }
  364. // Give time to network processing
  365. if (mMessagePipe)
  366. {
  367. // Drain any queued outgoing messages
  368. mMessagePipe->pumpOutput();
  369. // Only do input processing here if this instance is not in a
  370. // pollset. Also, if we are shutting down the plugin (STATE_GOODBYE
  371. // or later) or the viewer, we cannot handle the pumping.
  372. if (!mPolledInput && mState.get() < STATE_GOODBYE &&
  373. !LLApp::isExiting())
  374. {
  375. mMessagePipe->pumpInput();
  376. }
  377. }
  378. if (mState.get() <= STATE_RUNNING)
  379. {
  380. if (APR_STATUS_IS_EOF(mSocketError))
  381. {
  382. // Plugin socket was closed. This covers both normal plugin
  383. // termination and plugin crashes.
  384. errorState();
  385. }
  386. else if (mSocketError != APR_SUCCESS)
  387. {
  388. // The socket is in an error state -- the plugin is gone.
  389. llwarns << "Socket hit an error state (" << mSocketError << ")"
  390. << llendl;
  391. errorState();
  392. }
  393. }
  394. // If a state needs to go directly to another state (as a performance
  395. // enhancement), it can set idle_again to true after calling
  396. // setState().
  397. // USE THIS CAREFULLY, since it can starve other code. Specifically
  398. // make sure there is no way to get into a closed cycle and never
  399. // return. When in doubt, do not do it.
  400. idle_again = false;
  401. switch (mState.get())
  402. {
  403. case STATE_UNINITIALIZED:
  404. break;
  405. case STATE_INITIALIZED:
  406. {
  407. apr_status_t status = APR_SUCCESS;
  408. apr_sockaddr_t* addr = NULL;
  409. mListenSocket = LLSocket::create(gAPRPoolp,
  410. LLSocket::STREAM_TCP);
  411. mBoundPort = 0;
  412. if (!mListenSocket)
  413. {
  414. killSockets();
  415. errorState();
  416. break;
  417. }
  418. // This code is based on parts of LLSocket::create() in
  419. // lliosocket.cpp.
  420. status = apr_sockaddr_info_get(&addr, "127.0.0.1", APR_INET,
  421. // port 0 = ephemeral
  422. // ("find me a port")
  423. 0, 0, gAPRPoolp);
  424. if (ll_apr_warn_status(status))
  425. {
  426. killSockets();
  427. errorState();
  428. break;
  429. }
  430. // This allows us to reuse the address on quick down/up. This
  431. // is unlikely to create problems.
  432. ll_apr_warn_status(apr_socket_opt_set(mListenSocket->getSocket(),
  433. APR_SO_REUSEADDR, 1));
  434. status = apr_socket_bind(mListenSocket->getSocket(), addr);
  435. if (ll_apr_warn_status(status))
  436. {
  437. killSockets();
  438. errorState();
  439. break;
  440. }
  441. // Get the actual port the socket was bound to
  442. {
  443. apr_sockaddr_t* bound_addr = NULL;
  444. if (ll_apr_warn_status(apr_socket_addr_get(&bound_addr,
  445. APR_LOCAL,
  446. mListenSocket->getSocket())))
  447. {
  448. killSockets();
  449. errorState();
  450. break;
  451. }
  452. mBoundPort = bound_addr->port;
  453. if (mBoundPort == 0)
  454. {
  455. llwarns << "Bound port number unknown, bailing out."
  456. << llendl;
  457. killSockets();
  458. errorState();
  459. break;
  460. }
  461. }
  462. LL_DEBUGS("Plugin") << mPluginName
  463. << " - Bound tcp socket to port: "
  464. << addr->port << LL_ENDL;
  465. // Make the listen socket non-blocking
  466. status = apr_socket_opt_set(mListenSocket->getSocket(),
  467. APR_SO_NONBLOCK, 1);
  468. if (ll_apr_warn_status(status))
  469. {
  470. killSockets();
  471. errorState();
  472. break;
  473. }
  474. apr_socket_timeout_set(mListenSocket->getSocket(), 0);
  475. if (ll_apr_warn_status(status))
  476. {
  477. killSockets();
  478. errorState();
  479. break;
  480. }
  481. // If it is a stream based socket, we need to tell the OS to
  482. // keep a queue of incoming connections for ACCEPT.
  483. // FIXME: 10 is a magic number for queue size...
  484. status = apr_socket_listen(mListenSocket->getSocket(), 10);
  485. if (ll_apr_warn_status(status))
  486. {
  487. killSockets();
  488. errorState();
  489. break;
  490. }
  491. // If we got here, we are listening.
  492. setState(STATE_LISTENING);
  493. break;
  494. }
  495. case STATE_LISTENING:
  496. {
  497. // Launch the plugin process.
  498. if (mDebug && !mProcessStarted && !mProcessStartRequested)
  499. {
  500. if (!createPluginProcess())
  501. {
  502. errorState();
  503. }
  504. }
  505. else if (!mProcessStarted && !mProcessStartRequested)
  506. {
  507. LLWorkQueue::ptr_t genq =
  508. LLWorkQueue::getNamedInstance("General");
  509. LLWorkQueue::ptr_t mainq =
  510. LLWorkQueue::getNamedInstance("mainloop");
  511. mProcessStartRequested =
  512. mainq->postTo(genq,
  513. // Work done on general queue
  514. [this]() mutable
  515. {
  516. ptr_t self;
  517. sInstancesMutex.lock();
  518. instances_map_t::iterator it =
  519. sInstances.find(this);
  520. if (it != sInstances.end())
  521. {
  522. // Increment shared_ptr reference
  523. // count to avoid any spurious
  524. // destruction until we are done.
  525. self = it->second;
  526. }
  527. sInstancesMutex.unlock();
  528. return self && createPluginProcess();
  529. },
  530. // Callback done on main thread
  531. [this](bool success) mutable
  532. {
  533. ptr_t self;
  534. sInstancesMutex.lock();
  535. instances_map_t::iterator it =
  536. sInstances.find(this);
  537. if (it != sInstances.end())
  538. {
  539. // Increment shared_ptr reference
  540. // count to avoid any spurious
  541. // destruction until we are done.
  542. self = it->second;
  543. }
  544. sInstancesMutex.unlock();
  545. if (!self)
  546. {
  547. return;
  548. }
  549. if (success)
  550. {
  551. mProcessStarted = true;
  552. }
  553. else
  554. {
  555. errorState();
  556. }
  557. mProcessStartRequested = false;
  558. });
  559. if (!mProcessStartRequested)
  560. {
  561. llwarns << "Failed to create the process via the thread pool"
  562. << llendl;
  563. // Try to create it directly.
  564. if (!createPluginProcess())
  565. {
  566. errorState();
  567. }
  568. }
  569. }
  570. if (mProcessStarted)
  571. {
  572. #if LL_DARWIN
  573. if (mDebug)
  574. {
  575. // If we are set to debug, start up a gdb instance in a
  576. // new terminal window and have it attach to the plugin
  577. // process and continue.
  578. // The command we are constructing would look like this
  579. // on the command line:
  580. // osascript -e 'tell application "Terminal"' -e 'set win to do script "gdb -pid 12345"' -e 'do script "continue" in win' -e 'end tell'
  581. std::stringstream cmd;
  582. mDebugger.setExecutable("/usr/bin/osascript");
  583. mDebugger.addArgument("-e");
  584. mDebugger.addArgument("tell application \"Terminal\"");
  585. mDebugger.addArgument("-e");
  586. cmd << "set win to do script \"gdb -pid "
  587. << mProcess.getProcessID() << "\"";
  588. mDebugger.addArgument(cmd.str());
  589. mDebugger.addArgument("-e");
  590. mDebugger.addArgument("do script \"continue\" in win");
  591. mDebugger.addArgument("-e");
  592. mDebugger.addArgument("end tell");
  593. mDebugger.launch();
  594. }
  595. #endif
  596. // This will allow us to time out if the process never starts.
  597. mHeartbeat.start();
  598. mHeartbeat.setTimerExpirySec(mPluginLaunchTimeout);
  599. setState(STATE_LAUNCHED);
  600. }
  601. break;
  602. }
  603. case STATE_LAUNCHED:
  604. {
  605. // Waiting for the plugin to connect
  606. if (pluginLockedUpOrQuit())
  607. {
  608. errorState();
  609. }
  610. // Check for the incoming connection.
  611. else if (accept())
  612. {
  613. // Stop listening on the server port
  614. mListenSocket.reset();
  615. setState(STATE_CONNECTED);
  616. }
  617. break;
  618. }
  619. case STATE_CONNECTED:
  620. {
  621. // Waiting for hello message from the plugin
  622. if (pluginLockedUpOrQuit())
  623. {
  624. errorState();
  625. }
  626. break;
  627. }
  628. case STATE_HELLO:
  629. {
  630. LL_DEBUGS("Plugin") << mPluginName << ": received hello message"
  631. << LL_ENDL;
  632. // Send the message to load the plugin
  633. {
  634. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL,
  635. "load_plugin");
  636. message.setValue("file", mPluginFile);
  637. message.setValue("dir", mPluginDir);
  638. sendMessage(message);
  639. }
  640. setState(STATE_LOADING);
  641. break;
  642. }
  643. case STATE_LOADING:
  644. {
  645. // The load_plugin_response message will kick us from here into
  646. // STATE_RUNNING
  647. if (pluginLockedUpOrQuit())
  648. {
  649. errorState();
  650. }
  651. break;
  652. }
  653. case STATE_RUNNING:
  654. {
  655. if (pluginLockedUpOrQuit())
  656. {
  657. errorState();
  658. }
  659. break;
  660. }
  661. case STATE_GOODBYE:
  662. {
  663. {
  664. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL,
  665. "shutdown_plugin");
  666. sendMessage(message);
  667. }
  668. setState(STATE_EXITING);
  669. break;
  670. }
  671. case STATE_EXITING:
  672. {
  673. if (!mProcess.isRunning())
  674. {
  675. setState(STATE_CLEANUP);
  676. }
  677. else if (pluginLockedUp())
  678. {
  679. llwarns << mPluginName
  680. << ": timeout in exiting state, bailing out."
  681. << llendl;
  682. errorState();
  683. }
  684. break;
  685. }
  686. case STATE_LAUNCH_FAILURE:
  687. {
  688. if (mOwner)
  689. {
  690. mOwner->pluginLaunchFailed();
  691. }
  692. setState(STATE_CLEANUP);
  693. break;
  694. }
  695. case STATE_ERROR:
  696. {
  697. if (mOwner)
  698. {
  699. mOwner->pluginDied();
  700. }
  701. setState(STATE_CLEANUP);
  702. break;
  703. }
  704. case STATE_CLEANUP:
  705. {
  706. mProcess.kill();
  707. killSockets();
  708. setState(STATE_DONE);
  709. dirtyPollSet();
  710. break;
  711. }
  712. case STATE_DONE:
  713. // Just sit here.
  714. break;
  715. }
  716. }
  717. while (idle_again);
  718. }
  719. void LLPluginProcessParent::setSleepTime(F64 sleep_time, bool force_send)
  720. {
  721. if (force_send || sleep_time != mSleepTime)
  722. {
  723. // Cache the time locally
  724. mSleepTime = sleep_time;
  725. if (canSendMessage())
  726. {
  727. // And send to the plugin.
  728. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL,
  729. "sleep_time");
  730. message.setValueReal("time", mSleepTime);
  731. sendMessage(message);
  732. }
  733. #if 0
  734. else
  735. {
  736. // Too early to send -- the load_plugin_response message will
  737. // trigger us to send mSleepTime later.
  738. }
  739. #endif
  740. }
  741. }
  742. void LLPluginProcessParent::sendMessage(const LLPluginMessage& message)
  743. {
  744. if (message.hasValue("blocking_response"))
  745. {
  746. mBlocked = false;
  747. // Reset the heartbeat timer, since there will have been no heartbeats
  748. // while the plugin was blocked.
  749. mHeartbeat.setTimerExpirySec(mPluginLockupTimeout);
  750. }
  751. std::string buffer = message.generate();
  752. LL_DEBUGS("PluginMessage") << mPluginName << " - Sending: " << buffer
  753. << LL_ENDL;
  754. writeMessageRaw(buffer);
  755. // Try to send message immediately.
  756. if (mMessagePipe)
  757. {
  758. mMessagePipe->pumpOutput();
  759. }
  760. }
  761. //virtual
  762. void LLPluginProcessParent::setMessagePipe(LLPluginMessagePipe* message_pipe)
  763. {
  764. bool update_pollset = false;
  765. if (mMessagePipe)
  766. {
  767. // Unsetting an existing message pipe: remove from the pollset
  768. mPollFD.client_data = NULL;
  769. // Poll set needs an update
  770. update_pollset = true;
  771. }
  772. if (message_pipe != NULL)
  773. {
  774. // Set up the apr_pollfd_t
  775. mPollFD.p = gAPRPoolp;
  776. mPollFD.desc_type = APR_POLL_SOCKET;
  777. mPollFD.reqevents = APR_POLLIN|APR_POLLERR|APR_POLLHUP;
  778. mPollFD.rtnevents = 0;
  779. mPollFD.desc.s = mSocket->getSocket();
  780. mPollFD.client_data = (void*)this;
  781. // Poll set needs an update
  782. update_pollset = true;
  783. }
  784. mMessagePipe = message_pipe;
  785. if (update_pollset)
  786. {
  787. dirtyPollSet();
  788. }
  789. }
  790. //static
  791. void LLPluginProcessParent::dirtyPollSet()
  792. {
  793. sPollsetNeedsRebuild = true;
  794. if (sReadThread)
  795. {
  796. LL_DEBUGS("PluginPoll") <<"Unpausing read thread." << LL_ENDL;
  797. sReadThread->unpause();
  798. }
  799. }
  800. void LLPluginProcessParent::updatePollset()
  801. {
  802. sInstancesMutex.lock();
  803. if (sInstances.empty())
  804. {
  805. // No instance, so there is no work to do.
  806. sInstancesMutex.unlock();
  807. return;
  808. }
  809. if (sPollSet)
  810. {
  811. LL_DEBUGS("PluginPoll") << "Destroying pollset: " << sPollSet
  812. << LL_ENDL;
  813. // Delete the existing pollset.
  814. apr_pollset_destroy(sPollSet);
  815. sPollSet = NULL;
  816. }
  817. // Count the number of instances that want to be in the pollset
  818. S32 count = 0;
  819. for (instances_map_t::iterator iter = sInstances.begin(),
  820. end = sInstances.end();
  821. iter != end; ++iter)
  822. {
  823. iter->second->mPolledInput = false;
  824. if (iter->second->wantsPolling())
  825. {
  826. // This instance has a socket that needs to be polled.
  827. ++count;
  828. }
  829. }
  830. if (sUseReadThread && sReadThread && !sReadThread->isQuitting())
  831. {
  832. if (!sPollSet && count > 0)
  833. {
  834. #ifdef APR_POLLSET_NOCOPY
  835. // The pollset does not exist yet. Create it now.
  836. apr_status_t status = apr_pollset_create(&sPollSet, count,
  837. gAPRPoolp,
  838. APR_POLLSET_NOCOPY);
  839. if (status != APR_SUCCESS)
  840. {
  841. #endif // APR_POLLSET_NOCOPY
  842. llwarns <<"Could not create pollset. Falling back to non-pollset mode."
  843. << llendl;
  844. sPollSet = NULL;
  845. #ifdef APR_POLLSET_NOCOPY
  846. }
  847. else
  848. {
  849. LL_DEBUGS("PluginPoll") << "Created pollset: " << sPollSet
  850. << LL_ENDL;
  851. // Pollset was created, add all instances to it.
  852. for (instances_map_t::iterator iter = sInstances.begin(),
  853. end = sInstances.end();
  854. iter != end; ++iter)
  855. {
  856. if (!iter->second->wantsPolling())
  857. {
  858. continue;
  859. }
  860. status = apr_pollset_add(sPollSet,
  861. &(iter->second->mPollFD));
  862. if (status == APR_SUCCESS)
  863. {
  864. iter->second->mPolledInput = true;
  865. }
  866. else
  867. {
  868. llwarns << "apr_pollset_add failed with status: "
  869. << status << llendl;
  870. }
  871. }
  872. }
  873. #endif // APR_POLLSET_NOCOPY
  874. }
  875. }
  876. sInstancesMutex.unlock();
  877. }
  878. void LLPluginProcessParent::setUseReadThread(bool use_read_thread)
  879. {
  880. if (sUseReadThread != use_read_thread)
  881. {
  882. sUseReadThread = use_read_thread;
  883. if (sUseReadThread)
  884. {
  885. if (!sReadThread)
  886. {
  887. // Start up the read thread
  888. llinfos << "Creating read thread" << llendl;
  889. // Make sure the pollset gets rebuilt.
  890. sPollsetNeedsRebuild = true;
  891. sReadThread = new LLPluginProcessParentPollThread;
  892. sReadThread->start();
  893. }
  894. }
  895. else if (sReadThread)
  896. {
  897. // Shut down the read thread
  898. llinfos << "Destroying read thread" << llendl;
  899. delete sReadThread;
  900. sReadThread = NULL;
  901. }
  902. }
  903. }
  904. //static
  905. bool LLPluginProcessParent::poll(F64 timeout)
  906. {
  907. sInstancesMutex.lock();
  908. if (sInstances.empty())
  909. {
  910. // No instance, so there is no work to do.
  911. sInstancesMutex.unlock();
  912. return false;
  913. }
  914. sInstancesMutex.unlock();
  915. bool active = false;
  916. if (sPollsetNeedsRebuild || !sUseReadThread)
  917. {
  918. sPollsetNeedsRebuild = false;
  919. updatePollset();
  920. }
  921. if (sPollSet)
  922. {
  923. apr_int32_t count;
  924. const apr_pollfd_t* descriptors;
  925. apr_status_t status =
  926. apr_pollset_poll(sPollSet,
  927. (apr_interval_time_t)(timeout * 1000000),
  928. &count, &descriptors);
  929. if (status == APR_SUCCESS)
  930. {
  931. // One or more of the descriptors signalled. Call them.
  932. for (S32 i = 0; i < count; ++i)
  933. {
  934. ptr_t self;
  935. sInstancesMutex.lock();
  936. instances_map_t::iterator it =
  937. sInstances.find((void*)descriptors[i].client_data);
  938. if (it != sInstances.end())
  939. {
  940. self = it->second;
  941. }
  942. sInstancesMutex.unlock();
  943. if (self)
  944. {
  945. self->mIncomingQueueMutex.lock();
  946. self->servicePoll();
  947. self->mIncomingQueueMutex.unlock();
  948. }
  949. }
  950. active = true; // Plugin is active
  951. }
  952. else if (APR_STATUS_IS_TIMEUP(status))
  953. {
  954. // Timed out with no incoming data. Just return.
  955. }
  956. else if (APR_STATUS_IS_EBADF(status))
  957. {
  958. // This happens when one of the file descriptors in the pollset is
  959. // destroyed, which happens whenever a plugin's socket is closed.
  960. // The pollset has been or will be recreated, so just return.
  961. LL_DEBUGS("PluginPoll") << "apr_pollset_poll returned EBADF"
  962. << LL_ENDL;
  963. }
  964. else if (status != APR_SUCCESS)
  965. {
  966. llwarns <<"apr_pollset_poll failed with status: " << status
  967. << llendl;
  968. }
  969. }
  970. // Remove instances in the done state from the sInstances map.
  971. sInstancesMutex.lock();
  972. instances_map_t::iterator it = sInstances.begin();
  973. while (it != sInstances.end())
  974. {
  975. if (it->second->isDone())
  976. {
  977. it = sInstances.erase(it);
  978. }
  979. else
  980. {
  981. ++it;
  982. }
  983. }
  984. sInstancesMutex.unlock();
  985. return active;
  986. }
  987. void LLPluginProcessParent::servicePoll()
  988. {
  989. // Poll signalled on this object's socket. Try to process incoming
  990. // messages.
  991. if (mMessagePipe && !mMessagePipe->pumpInput(0.f))
  992. {
  993. llinfos << mPluginName
  994. << ": read error on message input pipe (closed ?)" << llendl;
  995. // We got a read error on input: remove this pipe from the pollset...
  996. apr_pollset_remove(sPollSet, &mPollFD);
  997. // ... and tell the code not to re-add it
  998. mPollFD.client_data = NULL;
  999. }
  1000. }
  1001. void LLPluginProcessParent::receiveMessageRaw(const std::string& message)
  1002. {
  1003. LL_DEBUGS("PluginMessage") << mPluginName << " - Received: " << message
  1004. << LL_ENDL;
  1005. LLPluginMessage parsed;
  1006. if (parsed.parse(message) != LLSDParser::PARSE_FAILURE)
  1007. {
  1008. if (parsed.hasValue("blocking_request"))
  1009. {
  1010. mBlocked = true;
  1011. }
  1012. if (mPolledInput)
  1013. {
  1014. // This is being called on the polling thread: do only do minimal
  1015. // processing/queueing.
  1016. receiveMessageEarly(parsed);
  1017. }
  1018. else
  1019. {
  1020. // This is not being called on the polling thread: do full message
  1021. // processing at this time.
  1022. receiveMessage(parsed);
  1023. }
  1024. }
  1025. }
  1026. void LLPluginProcessParent::receiveMessageEarly(const LLPluginMessage& message)
  1027. {
  1028. // NOTE: this function will be called from the polling thread. It will be
  1029. // called with mIncomingQueueMutex _already locked_.
  1030. bool handled = false;
  1031. std::string message_class = message.getClass();
  1032. // No internal messages need to be handled early.
  1033. if (message_class != LLPLUGIN_MESSAGE_CLASS_INTERNAL)
  1034. {
  1035. // Call out to the owner and see if they to reply
  1036. // *TODO: Should this only happen when blocked ?
  1037. if (mOwner)
  1038. {
  1039. handled = mOwner->receivePluginMessageEarly(message);
  1040. }
  1041. }
  1042. if (!handled)
  1043. {
  1044. // Any message that was not handled early needs to be queued.
  1045. mIncomingQueue.emplace(message);
  1046. }
  1047. }
  1048. void LLPluginProcessParent::receiveMessage(const LLPluginMessage& message)
  1049. {
  1050. std::string message_class = message.getClass();
  1051. if (message_class == LLPLUGIN_MESSAGE_CLASS_INTERNAL)
  1052. {
  1053. // Internal messages should be handled here
  1054. std::string message_name = message.getName();
  1055. if (message_name == "hello")
  1056. {
  1057. if (mState.get() == STATE_CONNECTED)
  1058. {
  1059. LL_DEBUGS("Plugin") << mPluginName << ": plugin host launched."
  1060. << LL_ENDL;
  1061. // Plugin host has launched. Tell it which plugin to load.
  1062. setState(STATE_HELLO);
  1063. }
  1064. else
  1065. {
  1066. llwarns << "Received hello message in wrong state: bailing out."
  1067. << llendl;
  1068. errorState();
  1069. }
  1070. }
  1071. else if (message_name == "load_plugin_response")
  1072. {
  1073. if (mState.get() == STATE_LOADING)
  1074. {
  1075. // Plugin has been loaded.
  1076. mPluginVersionString = message.getValue("plugin_version");
  1077. llinfos << "Plugin version string: " << mPluginVersionString
  1078. << llendl;
  1079. // Check which message classes/versions the plugin supports.
  1080. // *TODO: check against current versions
  1081. // *TODO: kill plugin on major mismatches?
  1082. std::string msg_class;
  1083. mMessageClassVersions = message.getValueLLSD("versions");
  1084. for (LLSD::map_iterator
  1085. iter = mMessageClassVersions.beginMap(),
  1086. end = mMessageClassVersions.endMap();
  1087. iter != end; ++iter)
  1088. {
  1089. msg_class = iter->first;
  1090. llinfos << "Message class: " << msg_class
  1091. << " -> version: " << iter->second.asString()
  1092. << llendl;
  1093. if (msg_class == "media_browser")
  1094. {
  1095. // Remember the media browser version, for reporting
  1096. // it in the About floater. HB
  1097. sMediaBrowserVersion = mPluginVersionString;
  1098. }
  1099. }
  1100. // Send initial sleep time
  1101. setSleepTime(llmin(0.01, mSleepTime), true);
  1102. setState(STATE_RUNNING);
  1103. }
  1104. else
  1105. {
  1106. llwarns << mPluginName
  1107. << ": received load_plugin_response message in wrong state, bailing out"
  1108. << llendl;
  1109. errorState();
  1110. }
  1111. }
  1112. else if (message_name == "heartbeat")
  1113. {
  1114. // This resets our timer.
  1115. mHeartbeat.setTimerExpirySec(mPluginLockupTimeout);
  1116. mCPUUsage = message.getValueReal("cpu_usage");
  1117. LL_DEBUGS("PluginPoll") << mPluginName
  1118. << ": CPU usage reported as " << mCPUUsage
  1119. << LL_ENDL;
  1120. }
  1121. else if (message_name == "shm_add_response")
  1122. {
  1123. // Nothing to do here.
  1124. }
  1125. else if (message_name == "shm_remove_response")
  1126. {
  1127. std::string name = message.getValue("name");
  1128. shared_mem_regions_t::iterator iter =
  1129. mSharedMemoryRegions.find(name);
  1130. if (iter != mSharedMemoryRegions.end())
  1131. {
  1132. // Destroy the shared memory region
  1133. iter->second->destroy();
  1134. delete iter->second;
  1135. iter->second = NULL;
  1136. // And remove it from our map
  1137. mSharedMemoryRegions.erase(iter);
  1138. }
  1139. }
  1140. else
  1141. {
  1142. llwarns << mPluginName
  1143. << " - Unknown internal message from child: "
  1144. << message_name << llendl;
  1145. }
  1146. }
  1147. else if (mOwner)
  1148. {
  1149. mOwner->receivePluginMessage(message);
  1150. }
  1151. }
  1152. std::string LLPluginProcessParent::addSharedMemory(size_t size)
  1153. {
  1154. std::string name;
  1155. LLPluginSharedMemory* regionp = new LLPluginSharedMemory;
  1156. if (regionp->create(size)) // This is a new region
  1157. {
  1158. name = regionp->getName();
  1159. mSharedMemoryRegions[name] = regionp;
  1160. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "shm_add");
  1161. message.setValue("name", name);
  1162. message.setValueS32("size", (S32)size);
  1163. sendMessage(message);
  1164. }
  1165. else
  1166. {
  1167. llwarns << mPluginName
  1168. << ": could not create a shared memory segment !" << llendl;
  1169. delete regionp;
  1170. }
  1171. return name;
  1172. }
  1173. void LLPluginProcessParent::removeSharedMemory(const std::string& name)
  1174. {
  1175. if (!mSharedMemoryRegions.count(name))
  1176. {
  1177. llwarns << mPluginName
  1178. << ": request to remove an unknown shared memory segment."
  1179. << llendl;
  1180. return;
  1181. }
  1182. // This segment exists. Send the message to the child to unmap it. The
  1183. // response will cause the parent to unmap our end.
  1184. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "shm_remove");
  1185. message.setValue("name", name);
  1186. sendMessage(message);
  1187. }
  1188. size_t LLPluginProcessParent::getSharedMemorySize(const std::string& name)
  1189. {
  1190. shared_mem_regions_t::iterator it = mSharedMemoryRegions.find(name);
  1191. return it == mSharedMemoryRegions.end() ? 0 : it->second->getSize();
  1192. }
  1193. void* LLPluginProcessParent::getSharedMemoryAddress(const std::string& name)
  1194. {
  1195. void* addrp = NULL;
  1196. shared_mem_regions_t::iterator it = mSharedMemoryRegions.find(name);
  1197. if (it != mSharedMemoryRegions.end())
  1198. {
  1199. addrp = it->second->getMappedAddress();
  1200. }
  1201. return addrp;
  1202. }
  1203. std::string LLPluginProcessParent::getMessageClassVersion(const std::string& mclass)
  1204. {
  1205. std::string result;
  1206. if (mMessageClassVersions.has(mclass))
  1207. {
  1208. result = mMessageClassVersions[mclass].asString();
  1209. }
  1210. return result;
  1211. }
  1212. void LLPluginProcessParent::setState(U32 state)
  1213. {
  1214. LL_DEBUGS("Plugin") << mPluginName << " - Setting state to "
  1215. << state2string(state) << LL_ENDL;
  1216. mState = state;
  1217. }
  1218. bool LLPluginProcessParent::pluginLockedUpOrQuit()
  1219. {
  1220. if (!mProcess.isRunning())
  1221. {
  1222. llwarns << mPluginName << ": child exited in state "
  1223. << state2string(mState.get()) << llendl;
  1224. return true;
  1225. }
  1226. return pluginLockedUp();
  1227. }
  1228. bool LLPluginProcessParent::pluginLockedUp()
  1229. {
  1230. if (mDisableTimeout || mDebug || mBlocked)
  1231. {
  1232. // Never time out a plugin process in these cases.
  1233. return false;
  1234. }
  1235. bool lockedup = mHeartbeat.getStarted() && mHeartbeat.hasExpired();
  1236. if (lockedup)
  1237. {
  1238. llwarns << mPluginName << ": timeout in state "
  1239. << state2string(mState.get()) << llendl;
  1240. }
  1241. // If the timer is running and has expired, the plugin has locked up.
  1242. return lockedup;
  1243. }