PageRenderTime 150ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/indra/llplugin/llpluginprocessparent.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 1105 lines | 803 code | 169 blank | 133 comment | 150 complexity | 316fa129904c7ec4bed9f7bb2dc0be1a MD5 | raw file
Possible License(s): LGPL-2.1
  1. /**
  2. * @file llpluginprocessparent.cpp
  3. * @brief LLPluginProcessParent handles the parent side of the external-process plugin API.
  4. *
  5. * @cond
  6. * $LicenseInfo:firstyear=2008&license=viewerlgpl$
  7. * Second Life Viewer Source Code
  8. * Copyright (C) 2010, Linden Research, Inc.
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation;
  13. * version 2.1 of the License only.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this library; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. *
  24. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  25. * $/LicenseInfo$
  26. * @endcond
  27. */
  28. #include "linden_common.h"
  29. #include "llpluginprocessparent.h"
  30. #include "llpluginmessagepipe.h"
  31. #include "llpluginmessageclasses.h"
  32. #include "llapr.h"
  33. //virtual
  34. LLPluginProcessParentOwner::~LLPluginProcessParentOwner()
  35. {
  36. }
  37. bool LLPluginProcessParent::sUseReadThread = false;
  38. apr_pollset_t *LLPluginProcessParent::sPollSet = NULL;
  39. bool LLPluginProcessParent::sPollsetNeedsRebuild = false;
  40. LLMutex *LLPluginProcessParent::sInstancesMutex;
  41. std::list<LLPluginProcessParent*> LLPluginProcessParent::sInstances;
  42. LLThread *LLPluginProcessParent::sReadThread = NULL;
  43. class LLPluginProcessParentPollThread: public LLThread
  44. {
  45. public:
  46. LLPluginProcessParentPollThread() :
  47. LLThread("LLPluginProcessParentPollThread", gAPRPoolp)
  48. {
  49. }
  50. protected:
  51. // Inherited from LLThread
  52. /*virtual*/ void run(void)
  53. {
  54. while(!isQuitting() && LLPluginProcessParent::getUseReadThread())
  55. {
  56. LLPluginProcessParent::poll(0.1f);
  57. checkPause();
  58. }
  59. // Final poll to clean up the pollset, etc.
  60. LLPluginProcessParent::poll(0.0f);
  61. }
  62. // Inherited from LLThread
  63. /*virtual*/ bool runCondition(void)
  64. {
  65. return(LLPluginProcessParent::canPollThreadRun());
  66. }
  67. };
  68. LLPluginProcessParent::LLPluginProcessParent(LLPluginProcessParentOwner *owner):
  69. mIncomingQueueMutex(gAPRPoolp)
  70. {
  71. if(!sInstancesMutex)
  72. {
  73. sInstancesMutex = new LLMutex(gAPRPoolp);
  74. }
  75. mOwner = owner;
  76. mBoundPort = 0;
  77. mState = STATE_UNINITIALIZED;
  78. mSleepTime = 0.0;
  79. mCPUUsage = 0.0;
  80. mDisableTimeout = false;
  81. mDebug = false;
  82. mBlocked = false;
  83. mPolledInput = false;
  84. mPollFD.client_data = NULL;
  85. mPluginLaunchTimeout = 60.0f;
  86. mPluginLockupTimeout = 15.0f;
  87. // Don't start the timer here -- start it when we actually launch the plugin process.
  88. mHeartbeat.stop();
  89. // Don't add to the global list until fully constructed.
  90. {
  91. LLMutexLock lock(sInstancesMutex);
  92. sInstances.push_back(this);
  93. }
  94. }
  95. LLPluginProcessParent::~LLPluginProcessParent()
  96. {
  97. LL_DEBUGS("Plugin") << "destructor" << LL_ENDL;
  98. // Remove from the global list before beginning destruction.
  99. {
  100. // Make sure to get the global mutex _first_ here, to avoid a possible deadlock against LLPluginProcessParent::poll()
  101. LLMutexLock lock(sInstancesMutex);
  102. {
  103. LLMutexLock lock2(&mIncomingQueueMutex);
  104. sInstances.remove(this);
  105. }
  106. }
  107. // Destroy any remaining shared memory regions
  108. sharedMemoryRegionsType::iterator iter;
  109. while((iter = mSharedMemoryRegions.begin()) != mSharedMemoryRegions.end())
  110. {
  111. // destroy the shared memory region
  112. iter->second->destroy();
  113. // and remove it from our map
  114. mSharedMemoryRegions.erase(iter);
  115. }
  116. mProcess.kill();
  117. killSockets();
  118. }
  119. void LLPluginProcessParent::killSockets(void)
  120. {
  121. {
  122. LLMutexLock lock(&mIncomingQueueMutex);
  123. killMessagePipe();
  124. }
  125. mListenSocket.reset();
  126. mSocket.reset();
  127. }
  128. void LLPluginProcessParent::errorState(void)
  129. {
  130. if(mState < STATE_RUNNING)
  131. setState(STATE_LAUNCH_FAILURE);
  132. else
  133. setState(STATE_ERROR);
  134. }
  135. void LLPluginProcessParent::init(const std::string &launcher_filename, const std::string &plugin_dir, const std::string &plugin_filename, bool debug)
  136. {
  137. mProcess.setExecutable(launcher_filename);
  138. mProcess.setWorkingDirectory(plugin_dir);
  139. mPluginFile = plugin_filename;
  140. mPluginDir = plugin_dir;
  141. mCPUUsage = 0.0f;
  142. mDebug = debug;
  143. setState(STATE_INITIALIZED);
  144. }
  145. bool LLPluginProcessParent::accept()
  146. {
  147. bool result = false;
  148. apr_status_t status = APR_EGENERAL;
  149. apr_socket_t *new_socket = NULL;
  150. status = apr_socket_accept(
  151. &new_socket,
  152. mListenSocket->getSocket(),
  153. gAPRPoolp);
  154. if(status == APR_SUCCESS)
  155. {
  156. // llinfos << "SUCCESS" << llendl;
  157. // Success. Create a message pipe on the new socket
  158. // we MUST create a new pool for the LLSocket, since it will take ownership of it and delete it in its destructor!
  159. apr_pool_t* new_pool = NULL;
  160. status = apr_pool_create(&new_pool, gAPRPoolp);
  161. mSocket = LLSocket::create(new_socket, new_pool);
  162. new LLPluginMessagePipe(this, mSocket);
  163. result = true;
  164. }
  165. else if(APR_STATUS_IS_EAGAIN(status))
  166. {
  167. // llinfos << "EAGAIN" << llendl;
  168. // No incoming connections. This is not an error.
  169. status = APR_SUCCESS;
  170. }
  171. else
  172. {
  173. // llinfos << "Error:" << llendl;
  174. ll_apr_warn_status(status);
  175. // Some other error.
  176. errorState();
  177. }
  178. return result;
  179. }
  180. void LLPluginProcessParent::idle(void)
  181. {
  182. bool idle_again;
  183. do
  184. {
  185. // process queued messages
  186. mIncomingQueueMutex.lock();
  187. while(!mIncomingQueue.empty())
  188. {
  189. LLPluginMessage message = mIncomingQueue.front();
  190. mIncomingQueue.pop();
  191. mIncomingQueueMutex.unlock();
  192. receiveMessage(message);
  193. mIncomingQueueMutex.lock();
  194. }
  195. mIncomingQueueMutex.unlock();
  196. // Give time to network processing
  197. if(mMessagePipe)
  198. {
  199. // Drain any queued outgoing messages
  200. mMessagePipe->pumpOutput();
  201. // Only do input processing here if this instance isn't in a pollset.
  202. if(!mPolledInput)
  203. {
  204. mMessagePipe->pumpInput();
  205. }
  206. }
  207. if(mState <= STATE_RUNNING)
  208. {
  209. if(APR_STATUS_IS_EOF(mSocketError))
  210. {
  211. // Plugin socket was closed. This covers both normal plugin termination and plugin crashes.
  212. errorState();
  213. }
  214. else if(mSocketError != APR_SUCCESS)
  215. {
  216. // The socket is in an error state -- the plugin is gone.
  217. LL_WARNS("Plugin") << "Socket hit an error state (" << mSocketError << ")" << LL_ENDL;
  218. errorState();
  219. }
  220. }
  221. // If a state needs to go directly to another state (as a performance enhancement), it can set idle_again to true after calling setState().
  222. // USE THIS CAREFULLY, since it can starve other code. Specifically make sure there's no way to get into a closed cycle and never return.
  223. // When in doubt, don't do it.
  224. idle_again = false;
  225. switch(mState)
  226. {
  227. case STATE_UNINITIALIZED:
  228. break;
  229. case STATE_INITIALIZED:
  230. {
  231. apr_status_t status = APR_SUCCESS;
  232. apr_sockaddr_t* addr = NULL;
  233. mListenSocket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
  234. mBoundPort = 0;
  235. // This code is based on parts of LLSocket::create() in lliosocket.cpp.
  236. status = apr_sockaddr_info_get(
  237. &addr,
  238. "127.0.0.1",
  239. APR_INET,
  240. 0, // port 0 = ephemeral ("find me a port")
  241. 0,
  242. gAPRPoolp);
  243. if(ll_apr_warn_status(status))
  244. {
  245. killSockets();
  246. errorState();
  247. break;
  248. }
  249. // This allows us to reuse the address on quick down/up. This is unlikely to create problems.
  250. ll_apr_warn_status(apr_socket_opt_set(mListenSocket->getSocket(), APR_SO_REUSEADDR, 1));
  251. status = apr_socket_bind(mListenSocket->getSocket(), addr);
  252. if(ll_apr_warn_status(status))
  253. {
  254. killSockets();
  255. errorState();
  256. break;
  257. }
  258. // Get the actual port the socket was bound to
  259. {
  260. apr_sockaddr_t* bound_addr = NULL;
  261. if(ll_apr_warn_status(apr_socket_addr_get(&bound_addr, APR_LOCAL, mListenSocket->getSocket())))
  262. {
  263. killSockets();
  264. errorState();
  265. break;
  266. }
  267. mBoundPort = bound_addr->port;
  268. if(mBoundPort == 0)
  269. {
  270. LL_WARNS("Plugin") << "Bound port number unknown, bailing out." << LL_ENDL;
  271. killSockets();
  272. errorState();
  273. break;
  274. }
  275. }
  276. LL_DEBUGS("Plugin") << "Bound tcp socket to port: " << addr->port << LL_ENDL;
  277. // Make the listen socket non-blocking
  278. status = apr_socket_opt_set(mListenSocket->getSocket(), APR_SO_NONBLOCK, 1);
  279. if(ll_apr_warn_status(status))
  280. {
  281. killSockets();
  282. errorState();
  283. break;
  284. }
  285. apr_socket_timeout_set(mListenSocket->getSocket(), 0);
  286. if(ll_apr_warn_status(status))
  287. {
  288. killSockets();
  289. errorState();
  290. break;
  291. }
  292. // If it's a stream based socket, we need to tell the OS
  293. // to keep a queue of incoming connections for ACCEPT.
  294. status = apr_socket_listen(
  295. mListenSocket->getSocket(),
  296. 10); // FIXME: Magic number for queue size
  297. if(ll_apr_warn_status(status))
  298. {
  299. killSockets();
  300. errorState();
  301. break;
  302. }
  303. // If we got here, we're listening.
  304. setState(STATE_LISTENING);
  305. }
  306. break;
  307. case STATE_LISTENING:
  308. {
  309. // Launch the plugin process.
  310. // Only argument to the launcher is the port number we're listening on
  311. std::stringstream stream;
  312. stream << mBoundPort;
  313. mProcess.addArgument(stream.str());
  314. if(mProcess.launch() != 0)
  315. {
  316. errorState();
  317. }
  318. else
  319. {
  320. if(mDebug)
  321. {
  322. #if LL_DARWIN
  323. // If we're set to debug, start up a gdb instance in a new terminal window and have it attach to the plugin process and continue.
  324. // The command we're constructing would look like this on the command line:
  325. // osascript -e 'tell application "Terminal"' -e 'set win to do script "gdb -pid 12345"' -e 'do script "continue" in win' -e 'end tell'
  326. std::stringstream cmd;
  327. mDebugger.setExecutable("/usr/bin/osascript");
  328. mDebugger.addArgument("-e");
  329. mDebugger.addArgument("tell application \"Terminal\"");
  330. mDebugger.addArgument("-e");
  331. cmd << "set win to do script \"gdb -pid " << mProcess.getProcessID() << "\"";
  332. mDebugger.addArgument(cmd.str());
  333. mDebugger.addArgument("-e");
  334. mDebugger.addArgument("do script \"continue\" in win");
  335. mDebugger.addArgument("-e");
  336. mDebugger.addArgument("end tell");
  337. mDebugger.launch();
  338. #endif
  339. }
  340. // This will allow us to time out if the process never starts.
  341. mHeartbeat.start();
  342. mHeartbeat.setTimerExpirySec(mPluginLaunchTimeout);
  343. setState(STATE_LAUNCHED);
  344. }
  345. }
  346. break;
  347. case STATE_LAUNCHED:
  348. // waiting for the plugin to connect
  349. if(pluginLockedUpOrQuit())
  350. {
  351. errorState();
  352. }
  353. else
  354. {
  355. // Check for the incoming connection.
  356. if(accept())
  357. {
  358. // Stop listening on the server port
  359. mListenSocket.reset();
  360. setState(STATE_CONNECTED);
  361. }
  362. }
  363. break;
  364. case STATE_CONNECTED:
  365. // waiting for hello message from the plugin
  366. if(pluginLockedUpOrQuit())
  367. {
  368. errorState();
  369. }
  370. break;
  371. case STATE_HELLO:
  372. LL_DEBUGS("Plugin") << "received hello message" << LL_ENDL;
  373. // Send the message to load the plugin
  374. {
  375. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "load_plugin");
  376. message.setValue("file", mPluginFile);
  377. message.setValue("dir", mPluginDir);
  378. sendMessage(message);
  379. }
  380. setState(STATE_LOADING);
  381. break;
  382. case STATE_LOADING:
  383. // The load_plugin_response message will kick us from here into STATE_RUNNING
  384. if(pluginLockedUpOrQuit())
  385. {
  386. errorState();
  387. }
  388. break;
  389. case STATE_RUNNING:
  390. if(pluginLockedUpOrQuit())
  391. {
  392. errorState();
  393. }
  394. break;
  395. case STATE_EXITING:
  396. if(!mProcess.isRunning())
  397. {
  398. setState(STATE_CLEANUP);
  399. }
  400. else if(pluginLockedUp())
  401. {
  402. LL_WARNS("Plugin") << "timeout in exiting state, bailing out" << LL_ENDL;
  403. errorState();
  404. }
  405. break;
  406. case STATE_LAUNCH_FAILURE:
  407. if(mOwner != NULL)
  408. {
  409. mOwner->pluginLaunchFailed();
  410. }
  411. setState(STATE_CLEANUP);
  412. break;
  413. case STATE_ERROR:
  414. if(mOwner != NULL)
  415. {
  416. mOwner->pluginDied();
  417. }
  418. setState(STATE_CLEANUP);
  419. break;
  420. case STATE_CLEANUP:
  421. mProcess.kill();
  422. killSockets();
  423. setState(STATE_DONE);
  424. break;
  425. case STATE_DONE:
  426. // just sit here.
  427. break;
  428. }
  429. } while (idle_again);
  430. }
  431. bool LLPluginProcessParent::isLoading(void)
  432. {
  433. bool result = false;
  434. if(mState <= STATE_LOADING)
  435. result = true;
  436. return result;
  437. }
  438. bool LLPluginProcessParent::isRunning(void)
  439. {
  440. bool result = false;
  441. if(mState == STATE_RUNNING)
  442. result = true;
  443. return result;
  444. }
  445. bool LLPluginProcessParent::isDone(void)
  446. {
  447. bool result = false;
  448. if(mState == STATE_DONE)
  449. result = true;
  450. return result;
  451. }
  452. void LLPluginProcessParent::setSleepTime(F64 sleep_time, bool force_send)
  453. {
  454. if(force_send || (sleep_time != mSleepTime))
  455. {
  456. // Cache the time locally
  457. mSleepTime = sleep_time;
  458. if(canSendMessage())
  459. {
  460. // and send to the plugin.
  461. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "sleep_time");
  462. message.setValueReal("time", mSleepTime);
  463. sendMessage(message);
  464. }
  465. else
  466. {
  467. // Too early to send -- the load_plugin_response message will trigger us to send mSleepTime later.
  468. }
  469. }
  470. }
  471. void LLPluginProcessParent::sendMessage(const LLPluginMessage &message)
  472. {
  473. if(message.hasValue("blocking_response"))
  474. {
  475. mBlocked = false;
  476. // reset the heartbeat timer, since there will have been no heartbeats while the plugin was blocked.
  477. mHeartbeat.setTimerExpirySec(mPluginLockupTimeout);
  478. }
  479. std::string buffer = message.generate();
  480. LL_DEBUGS("Plugin") << "Sending: " << buffer << LL_ENDL;
  481. writeMessageRaw(buffer);
  482. // Try to send message immediately.
  483. if(mMessagePipe)
  484. {
  485. mMessagePipe->pumpOutput();
  486. }
  487. }
  488. //virtual
  489. void LLPluginProcessParent::setMessagePipe(LLPluginMessagePipe *message_pipe)
  490. {
  491. bool update_pollset = false;
  492. if(mMessagePipe)
  493. {
  494. // Unsetting an existing message pipe -- remove from the pollset
  495. mPollFD.client_data = NULL;
  496. // pollset needs an update
  497. update_pollset = true;
  498. }
  499. if(message_pipe != NULL)
  500. {
  501. // Set up the apr_pollfd_t
  502. mPollFD.p = gAPRPoolp;
  503. mPollFD.desc_type = APR_POLL_SOCKET;
  504. mPollFD.reqevents = APR_POLLIN|APR_POLLERR|APR_POLLHUP;
  505. mPollFD.rtnevents = 0;
  506. mPollFD.desc.s = mSocket->getSocket();
  507. mPollFD.client_data = (void*)this;
  508. // pollset needs an update
  509. update_pollset = true;
  510. }
  511. mMessagePipe = message_pipe;
  512. if(update_pollset)
  513. {
  514. dirtyPollSet();
  515. }
  516. }
  517. //static
  518. void LLPluginProcessParent::dirtyPollSet()
  519. {
  520. sPollsetNeedsRebuild = true;
  521. if(sReadThread)
  522. {
  523. LL_DEBUGS("PluginPoll") << "unpausing read thread " << LL_ENDL;
  524. sReadThread->unpause();
  525. }
  526. }
  527. void LLPluginProcessParent::updatePollset()
  528. {
  529. if(!sInstancesMutex)
  530. {
  531. // No instances have been created yet. There's no work to do.
  532. return;
  533. }
  534. LLMutexLock lock(sInstancesMutex);
  535. if(sPollSet)
  536. {
  537. LL_DEBUGS("PluginPoll") << "destroying pollset " << sPollSet << LL_ENDL;
  538. // delete the existing pollset.
  539. apr_pollset_destroy(sPollSet);
  540. sPollSet = NULL;
  541. }
  542. std::list<LLPluginProcessParent*>::iterator iter;
  543. int count = 0;
  544. // Count the number of instances that want to be in the pollset
  545. for(iter = sInstances.begin(); iter != sInstances.end(); iter++)
  546. {
  547. (*iter)->mPolledInput = false;
  548. if((*iter)->mPollFD.client_data)
  549. {
  550. // This instance has a socket that needs to be polled.
  551. ++count;
  552. }
  553. }
  554. if(sUseReadThread && sReadThread && !sReadThread->isQuitting())
  555. {
  556. if(!sPollSet && (count > 0))
  557. {
  558. #ifdef APR_POLLSET_NOCOPY
  559. // The pollset doesn't exist yet. Create it now.
  560. apr_status_t status = apr_pollset_create(&sPollSet, count, gAPRPoolp, APR_POLLSET_NOCOPY);
  561. if(status != APR_SUCCESS)
  562. {
  563. #endif // APR_POLLSET_NOCOPY
  564. LL_WARNS("PluginPoll") << "Couldn't create pollset. Falling back to non-pollset mode." << LL_ENDL;
  565. sPollSet = NULL;
  566. #ifdef APR_POLLSET_NOCOPY
  567. }
  568. else
  569. {
  570. LL_DEBUGS("PluginPoll") << "created pollset " << sPollSet << LL_ENDL;
  571. // Pollset was created, add all instances to it.
  572. for(iter = sInstances.begin(); iter != sInstances.end(); iter++)
  573. {
  574. if((*iter)->mPollFD.client_data)
  575. {
  576. status = apr_pollset_add(sPollSet, &((*iter)->mPollFD));
  577. if(status == APR_SUCCESS)
  578. {
  579. (*iter)->mPolledInput = true;
  580. }
  581. else
  582. {
  583. LL_WARNS("PluginPoll") << "apr_pollset_add failed with status " << status << LL_ENDL;
  584. }
  585. }
  586. }
  587. }
  588. #endif // APR_POLLSET_NOCOPY
  589. }
  590. }
  591. }
  592. void LLPluginProcessParent::setUseReadThread(bool use_read_thread)
  593. {
  594. if(sUseReadThread != use_read_thread)
  595. {
  596. sUseReadThread = use_read_thread;
  597. if(sUseReadThread)
  598. {
  599. if(!sReadThread)
  600. {
  601. // start up the read thread
  602. LL_INFOS("PluginPoll") << "creating read thread " << LL_ENDL;
  603. // make sure the pollset gets rebuilt.
  604. sPollsetNeedsRebuild = true;
  605. sReadThread = new LLPluginProcessParentPollThread;
  606. sReadThread->start();
  607. }
  608. }
  609. else
  610. {
  611. if(sReadThread)
  612. {
  613. // shut down the read thread
  614. LL_INFOS("PluginPoll") << "destroying read thread " << LL_ENDL;
  615. delete sReadThread;
  616. sReadThread = NULL;
  617. }
  618. }
  619. }
  620. }
  621. void LLPluginProcessParent::poll(F64 timeout)
  622. {
  623. if(sPollsetNeedsRebuild || !sUseReadThread)
  624. {
  625. sPollsetNeedsRebuild = false;
  626. updatePollset();
  627. }
  628. if(sPollSet)
  629. {
  630. apr_status_t status;
  631. apr_int32_t count;
  632. const apr_pollfd_t *descriptors;
  633. status = apr_pollset_poll(sPollSet, (apr_interval_time_t)(timeout * 1000000), &count, &descriptors);
  634. if(status == APR_SUCCESS)
  635. {
  636. // One or more of the descriptors signalled. Call them.
  637. for(int i = 0; i < count; i++)
  638. {
  639. LLPluginProcessParent *self = (LLPluginProcessParent *)(descriptors[i].client_data);
  640. // NOTE: the descriptor returned here is actually a COPY of the original (even though we create the pollset with APR_POLLSET_NOCOPY).
  641. // This means that even if the parent has set its mPollFD.client_data to NULL, the old pointer may still there in this descriptor.
  642. // It's even possible that the old pointer no longer points to a valid LLPluginProcessParent.
  643. // This means that we can't safely dereference the 'self' pointer here without some extra steps...
  644. if(self)
  645. {
  646. // Make sure this pointer is still in the instances list
  647. bool valid = false;
  648. {
  649. LLMutexLock lock(sInstancesMutex);
  650. for(std::list<LLPluginProcessParent*>::iterator iter = sInstances.begin(); iter != sInstances.end(); ++iter)
  651. {
  652. if(*iter == self)
  653. {
  654. // Lock the instance's mutex before unlocking the global mutex.
  655. // This avoids a possible race condition where the instance gets deleted between this check and the servicePoll() call.
  656. self->mIncomingQueueMutex.lock();
  657. valid = true;
  658. break;
  659. }
  660. }
  661. }
  662. if(valid)
  663. {
  664. // The instance is still valid.
  665. // Pull incoming messages off the socket
  666. self->servicePoll();
  667. self->mIncomingQueueMutex.unlock();
  668. }
  669. else
  670. {
  671. LL_DEBUGS("PluginPoll") << "detected deleted instance " << self << LL_ENDL;
  672. }
  673. }
  674. }
  675. }
  676. else if(APR_STATUS_IS_TIMEUP(status))
  677. {
  678. // timed out with no incoming data. Just return.
  679. }
  680. else if(status == EBADF)
  681. {
  682. // This happens when one of the file descriptors in the pollset is destroyed, which happens whenever a plugin's socket is closed.
  683. // The pollset has been or will be recreated, so just return.
  684. LL_DEBUGS("PluginPoll") << "apr_pollset_poll returned EBADF" << LL_ENDL;
  685. }
  686. else if(status != APR_SUCCESS)
  687. {
  688. LL_WARNS("PluginPoll") << "apr_pollset_poll failed with status " << status << LL_ENDL;
  689. }
  690. }
  691. }
  692. void LLPluginProcessParent::servicePoll()
  693. {
  694. bool result = true;
  695. // poll signalled on this object's socket. Try to process incoming messages.
  696. if(mMessagePipe)
  697. {
  698. result = mMessagePipe->pumpInput(0.0f);
  699. }
  700. if(!result)
  701. {
  702. // If we got a read error on input, remove this pipe from the pollset
  703. apr_pollset_remove(sPollSet, &mPollFD);
  704. // and tell the code not to re-add it
  705. mPollFD.client_data = NULL;
  706. }
  707. }
  708. void LLPluginProcessParent::receiveMessageRaw(const std::string &message)
  709. {
  710. LL_DEBUGS("Plugin") << "Received: " << message << LL_ENDL;
  711. LLPluginMessage parsed;
  712. if(parsed.parse(message) != -1)
  713. {
  714. if(parsed.hasValue("blocking_request"))
  715. {
  716. mBlocked = true;
  717. }
  718. if(mPolledInput)
  719. {
  720. // This is being called on the polling thread -- only do minimal processing/queueing.
  721. receiveMessageEarly(parsed);
  722. }
  723. else
  724. {
  725. // This is not being called on the polling thread -- do full message processing at this time.
  726. receiveMessage(parsed);
  727. }
  728. }
  729. }
  730. void LLPluginProcessParent::receiveMessageEarly(const LLPluginMessage &message)
  731. {
  732. // NOTE: this function will be called from the polling thread. It will be called with mIncomingQueueMutex _already locked_.
  733. bool handled = false;
  734. std::string message_class = message.getClass();
  735. if(message_class == LLPLUGIN_MESSAGE_CLASS_INTERNAL)
  736. {
  737. // no internal messages need to be handled early.
  738. }
  739. else
  740. {
  741. // Call out to the owner and see if they to reply
  742. // TODO: Should this only happen when blocked?
  743. if(mOwner != NULL)
  744. {
  745. handled = mOwner->receivePluginMessageEarly(message);
  746. }
  747. }
  748. if(!handled)
  749. {
  750. // any message that wasn't handled early needs to be queued.
  751. mIncomingQueue.push(message);
  752. }
  753. }
  754. void LLPluginProcessParent::receiveMessage(const LLPluginMessage &message)
  755. {
  756. std::string message_class = message.getClass();
  757. if(message_class == LLPLUGIN_MESSAGE_CLASS_INTERNAL)
  758. {
  759. // internal messages should be handled here
  760. std::string message_name = message.getName();
  761. if(message_name == "hello")
  762. {
  763. if(mState == STATE_CONNECTED)
  764. {
  765. // Plugin host has launched. Tell it which plugin to load.
  766. setState(STATE_HELLO);
  767. }
  768. else
  769. {
  770. LL_WARNS("Plugin") << "received hello message in wrong state -- bailing out" << LL_ENDL;
  771. errorState();
  772. }
  773. }
  774. else if(message_name == "load_plugin_response")
  775. {
  776. if(mState == STATE_LOADING)
  777. {
  778. // Plugin has been loaded.
  779. mPluginVersionString = message.getValue("plugin_version");
  780. LL_INFOS("Plugin") << "plugin version string: " << mPluginVersionString << LL_ENDL;
  781. // Check which message classes/versions the plugin supports.
  782. // TODO: check against current versions
  783. // TODO: kill plugin on major mismatches?
  784. mMessageClassVersions = message.getValueLLSD("versions");
  785. LLSD::map_iterator iter;
  786. for(iter = mMessageClassVersions.beginMap(); iter != mMessageClassVersions.endMap(); iter++)
  787. {
  788. LL_INFOS("Plugin") << "message class: " << iter->first << " -> version: " << iter->second.asString() << LL_ENDL;
  789. }
  790. // Send initial sleep time
  791. llassert_always(mSleepTime != 0.f);
  792. setSleepTime(mSleepTime, true);
  793. setState(STATE_RUNNING);
  794. }
  795. else
  796. {
  797. LL_WARNS("Plugin") << "received load_plugin_response message in wrong state -- bailing out" << LL_ENDL;
  798. errorState();
  799. }
  800. }
  801. else if(message_name == "heartbeat")
  802. {
  803. // this resets our timer.
  804. mHeartbeat.setTimerExpirySec(mPluginLockupTimeout);
  805. mCPUUsage = message.getValueReal("cpu_usage");
  806. LL_DEBUGS("Plugin") << "cpu usage reported as " << mCPUUsage << LL_ENDL;
  807. }
  808. else if(message_name == "shm_add_response")
  809. {
  810. // Nothing to do here.
  811. }
  812. else if(message_name == "shm_remove_response")
  813. {
  814. std::string name = message.getValue("name");
  815. sharedMemoryRegionsType::iterator iter = mSharedMemoryRegions.find(name);
  816. if(iter != mSharedMemoryRegions.end())
  817. {
  818. // destroy the shared memory region
  819. iter->second->destroy();
  820. // and remove it from our map
  821. mSharedMemoryRegions.erase(iter);
  822. }
  823. }
  824. else
  825. {
  826. LL_WARNS("Plugin") << "Unknown internal message from child: " << message_name << LL_ENDL;
  827. }
  828. }
  829. else
  830. {
  831. if(mOwner != NULL)
  832. {
  833. mOwner->receivePluginMessage(message);
  834. }
  835. }
  836. }
  837. std::string LLPluginProcessParent::addSharedMemory(size_t size)
  838. {
  839. std::string name;
  840. LLPluginSharedMemory *region = new LLPluginSharedMemory;
  841. // This is a new region
  842. if(region->create(size))
  843. {
  844. name = region->getName();
  845. mSharedMemoryRegions.insert(sharedMemoryRegionsType::value_type(name, region));
  846. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "shm_add");
  847. message.setValue("name", name);
  848. message.setValueS32("size", (S32)size);
  849. sendMessage(message);
  850. }
  851. else
  852. {
  853. LL_WARNS("Plugin") << "Couldn't create a shared memory segment!" << LL_ENDL;
  854. // Don't leak
  855. delete region;
  856. }
  857. return name;
  858. }
  859. void LLPluginProcessParent::removeSharedMemory(const std::string &name)
  860. {
  861. sharedMemoryRegionsType::iterator iter = mSharedMemoryRegions.find(name);
  862. if(iter != mSharedMemoryRegions.end())
  863. {
  864. // This segment exists. Send the message to the child to unmap it. The response will cause the parent to unmap our end.
  865. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "shm_remove");
  866. message.setValue("name", name);
  867. sendMessage(message);
  868. }
  869. else
  870. {
  871. LL_WARNS("Plugin") << "Request to remove an unknown shared memory segment." << LL_ENDL;
  872. }
  873. }
  874. size_t LLPluginProcessParent::getSharedMemorySize(const std::string &name)
  875. {
  876. size_t result = 0;
  877. sharedMemoryRegionsType::iterator iter = mSharedMemoryRegions.find(name);
  878. if(iter != mSharedMemoryRegions.end())
  879. {
  880. result = iter->second->getSize();
  881. }
  882. return result;
  883. }
  884. void *LLPluginProcessParent::getSharedMemoryAddress(const std::string &name)
  885. {
  886. void *result = NULL;
  887. sharedMemoryRegionsType::iterator iter = mSharedMemoryRegions.find(name);
  888. if(iter != mSharedMemoryRegions.end())
  889. {
  890. result = iter->second->getMappedAddress();
  891. }
  892. return result;
  893. }
  894. std::string LLPluginProcessParent::getMessageClassVersion(const std::string &message_class)
  895. {
  896. std::string result;
  897. if(mMessageClassVersions.has(message_class))
  898. {
  899. result = mMessageClassVersions[message_class].asString();
  900. }
  901. return result;
  902. }
  903. std::string LLPluginProcessParent::getPluginVersion(void)
  904. {
  905. return mPluginVersionString;
  906. }
  907. void LLPluginProcessParent::setState(EState state)
  908. {
  909. LL_DEBUGS("Plugin") << "setting state to " << state << LL_ENDL;
  910. mState = state;
  911. };
  912. bool LLPluginProcessParent::pluginLockedUpOrQuit()
  913. {
  914. bool result = false;
  915. if(!mProcess.isRunning())
  916. {
  917. LL_WARNS("Plugin") << "child exited" << LL_ENDL;
  918. result = true;
  919. }
  920. else if(pluginLockedUp())
  921. {
  922. LL_WARNS("Plugin") << "timeout" << LL_ENDL;
  923. result = true;
  924. }
  925. return result;
  926. }
  927. bool LLPluginProcessParent::pluginLockedUp()
  928. {
  929. if(mDisableTimeout || mDebug || mBlocked)
  930. {
  931. // Never time out a plugin process in these cases.
  932. return false;
  933. }
  934. // If the timer is running and has expired, the plugin has locked up.
  935. return (mHeartbeat.getStarted() && mHeartbeat.hasExpired());
  936. }