2 * Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
7 #define NACL_LOG_MODULE_NAME "Plugin_ServiceRuntime"
9 #include "ppapi/native_client/src/trusted/plugin/service_runtime.h"
16 #include "base/compiler_specific.h"
18 #include "native_client/src/include/checked_cast.h"
19 #include "native_client/src/include/portability_io.h"
20 #include "native_client/src/include/portability_string.h"
21 #include "native_client/src/include/nacl_macros.h"
22 #include "native_client/src/include/nacl_scoped_ptr.h"
23 #include "native_client/src/include/nacl_string.h"
24 #include "native_client/src/shared/platform/nacl_check.h"
25 #include "native_client/src/shared/platform/nacl_log.h"
26 #include "native_client/src/shared/platform/nacl_sync.h"
27 #include "native_client/src/shared/platform/nacl_sync_checked.h"
28 #include "native_client/src/shared/platform/nacl_sync_raii.h"
29 #include "native_client/src/shared/platform/scoped_ptr_refcount.h"
30 #include "native_client/src/trusted/desc/nacl_desc_imc.h"
31 // remove when we no longer need to cast the DescWrapper below.
32 #include "native_client/src/trusted/desc/nacl_desc_io.h"
33 #include "native_client/src/trusted/desc/nrd_xfer.h"
34 #include "native_client/src/trusted/nonnacl_util/sel_ldr_launcher.h"
36 // This is here due to a Windows API collision; plugin.h through
37 // file_downloader.h transitively includes Instance.h which defines a
38 // PostMessage method, so this undef must appear before any of those.
42 #include "native_client/src/public/imc_types.h"
43 #include "native_client/src/trusted/service_runtime/nacl_error_code.h"
44 #include "native_client/src/trusted/validator/nacl_file_info.h"
46 #include "ppapi/c/pp_errors.h"
47 #include "ppapi/cpp/core.h"
48 #include "ppapi/cpp/completion_callback.h"
50 #include "ppapi/native_client/src/trusted/plugin/manifest.h"
51 #include "ppapi/native_client/src/trusted/plugin/plugin.h"
52 #include "ppapi/native_client/src/trusted/plugin/plugin_error.h"
53 #include "ppapi/native_client/src/trusted/plugin/pnacl_options.h"
54 #include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
55 #include "ppapi/native_client/src/trusted/plugin/sel_ldr_launcher_chrome.h"
56 #include "ppapi/native_client/src/trusted/plugin/srpc_client.h"
57 #include "ppapi/native_client/src/trusted/weak_ref/call_on_main_thread.h"
61 // For doing crude quota enforcement on writes to temp files.
62 // We do not allow a temp file bigger than 128 MB for now.
63 // There is currently a limit of 32M for nexe text size, so 128M
64 // should be plenty for static data
65 const int64_t kMaxTempQuota = 0x8000000;
71 PluginReverseInterface::PluginReverseInterface(
72 nacl::WeakRefAnchor* anchor,
74 const Manifest* manifest,
75 ServiceRuntime* service_runtime,
76 pp::CompletionCallback init_done_cb,
77 pp::CompletionCallback crash_cb)
81 service_runtime_(service_runtime),
82 shutting_down_(false),
83 init_done_cb_(init_done_cb),
86 NaClXCondVarCtor(&cv_);
89 PluginReverseInterface::~PluginReverseInterface() {
90 NaClCondVarDtor(&cv_);
94 void PluginReverseInterface::ShutDown() {
95 NaClLog(4, "PluginReverseInterface::Shutdown: entered\n");
96 nacl::MutexLocker take(&mu_);
97 shutting_down_ = true;
98 NaClXCondVarBroadcast(&cv_);
99 NaClLog(4, "PluginReverseInterface::Shutdown: broadcasted, exiting\n");
102 void PluginReverseInterface::DoPostMessage(nacl::string message) {
103 PostMessageResource* continuation = new PostMessageResource(message);
104 CHECK(continuation != NULL);
105 NaClLog(4, "PluginReverseInterface::DoPostMessage(%s)\n", message.c_str());
106 plugin::WeakRefCallOnMainThread(
110 &plugin::PluginReverseInterface::PostMessage_MainThreadContinuation,
114 void PluginReverseInterface::StartupInitializationComplete() {
115 NaClLog(4, "PluginReverseInterface::StartupInitializationComplete\n");
116 if (init_done_cb_.pp_completion_callback().func != NULL) {
118 "PluginReverseInterface::StartupInitializationComplete:"
120 pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb_, PP_OK);
123 "PluginReverseInterface::StartupInitializationComplete:"
124 " init_done_cb_ not valid, skipping.\n");
128 void PluginReverseInterface::PostMessage_MainThreadContinuation(
129 PostMessageResource* p,
131 UNREFERENCED_PARAMETER(err);
133 "PluginReverseInterface::PostMessage_MainThreadContinuation(%s)\n",
135 plugin_->PostMessage(std::string("DEBUG_POSTMESSAGE:") + p->message);
138 bool PluginReverseInterface::EnumerateManifestKeys(
139 std::set<nacl::string>* out_keys) {
140 return manifest_->GetFileKeys(out_keys);
143 // TODO(bsy): OpenManifestEntry should use the manifest to ResolveKey
144 // and invoke StreamAsFile with a completion callback that invokes
146 bool PluginReverseInterface::OpenManifestEntry(nacl::string url_key,
147 struct NaClFileInfo* info) {
148 bool op_complete = false; // NB: mu_ and cv_ also controls access to this!
149 // The to_open object is owned by the weak ref callback. Because this function
150 // waits for the callback to finish, the to_open object will be deallocated on
151 // the main thread before this function can return. The pointers it contains
152 // to stack variables will not leak.
153 OpenManifestEntryResource* to_open =
154 new OpenManifestEntryResource(url_key, info, &op_complete);
155 CHECK(to_open != NULL);
156 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: %s\n",
158 // This assumes we are not on the main thread. If false, we deadlock.
159 plugin::WeakRefCallOnMainThread(
163 &plugin::PluginReverseInterface::OpenManifestEntry_MainThreadContinuation,
166 "PluginReverseInterface::OpenManifestEntry:"
167 " waiting on main thread\n");
170 nacl::MutexLocker take(&mu_);
171 while (!shutting_down_ && !op_complete)
172 NaClXCondVarWait(&cv_, &mu_);
173 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: done!\n");
174 if (shutting_down_) {
176 "PluginReverseInterface::OpenManifestEntry:"
177 " plugin is shutting down\n");
182 // info->desc has the returned descriptor if successful, else -1.
184 // The caller is responsible for not closing info->desc. If it is
185 // closed prematurely, then another open could re-use the OS
186 // descriptor, confusing the opened_ map. If the caller is going to
187 // want to make a NaClDesc object and transfer it etc., then the
188 // caller should DUP the descriptor (but remember the original
189 // value) for use by the NaClDesc object, which closes when the
190 // object is destroyed.
192 "PluginReverseInterface::OpenManifestEntry: info->desc = %d\n",
194 if (info->desc == -1) {
195 // TODO(bsy,ncbray): what else should we do with the error? This
196 // is a runtime error that may simply be a programming error in
197 // the untrusted code, or it may be something else wrong w/ the
199 NaClLog(4, "OpenManifestEntry: failed for key %s", url_key.c_str());
204 // Transfer point from OpenManifestEntry() which runs on the main thread
205 // (Some PPAPI actions -- like StreamAsFile -- can only run on the main thread).
206 // OpenManifestEntry() is waiting on a condvar for this continuation to
207 // complete. We Broadcast and awaken OpenManifestEntry() whenever we are done
208 // either here, or in a later MainThreadContinuation step, if there are
210 void PluginReverseInterface::OpenManifestEntry_MainThreadContinuation(
211 OpenManifestEntryResource* p,
213 UNREFERENCED_PARAMETER(err);
214 // CallOnMainThread continuations always called with err == PP_OK.
216 NaClLog(4, "Entered OpenManifestEntry_MainThreadContinuation\n");
218 std::string mapped_url;
219 PnaclOptions pnacl_options;
220 ErrorInfo error_info;
221 if (!manifest_->ResolveKey(p->url, &mapped_url,
222 &pnacl_options, &error_info)) {
223 NaClLog(4, "OpenManifestEntry_MainThreadContinuation: ResolveKey failed\n");
225 "Error code %d, string %s\n",
226 error_info.error_code(),
227 error_info.message().c_str());
228 // Failed, and error_info has the details on what happened. Wake
229 // up requesting thread -- we are done.
230 nacl::MutexLocker take(&mu_);
231 *p->op_complete_ptr = true; // done...
232 p->file_info->desc = -1; // but failed.
233 NaClXCondVarBroadcast(&cv_);
237 "OpenManifestEntry_MainThreadContinuation: "
238 "ResolveKey: %s -> %s (pnacl_translate(%d))\n",
239 p->url.c_str(), mapped_url.c_str(), pnacl_options.translate());
241 if (pnacl_options.translate()) {
242 // Requires PNaCl translation, but that's not supported.
244 "OpenManifestEntry_MainThreadContinuation: "
245 "Requires PNaCl translation -- not supported\n");
246 nacl::MutexLocker take(&mu_);
247 *p->op_complete_ptr = true; // done...
248 p->file_info->desc = -1; // but failed.
249 NaClXCondVarBroadcast(&cv_);
253 if (PnaclUrls::IsPnaclComponent(mapped_url)) {
254 // Special PNaCl support files, that are installed on the
256 int32_t fd = PnaclResources::GetPnaclFD(
258 PnaclUrls::PnaclComponentURLToFilename(mapped_url).c_str());
260 // We checked earlier if the pnacl component wasn't installed
261 // yet, so this shouldn't happen. At this point, we can't do much
262 // anymore, so just continue with an invalid fd.
264 "OpenManifestEntry_MainThreadContinuation: "
265 "GetReadonlyPnaclFd failed\n");
267 nacl::MutexLocker take(&mu_);
268 *p->op_complete_ptr = true; // done!
269 // TODO(ncbray): enable the fast loading and validation paths for this
271 p->file_info->desc = fd;
272 NaClXCondVarBroadcast(&cv_);
274 "OpenManifestEntry_MainThreadContinuation: GetPnaclFd okay\n");
278 // Hereafter, normal files.
280 // Because p is owned by the callback of this invocation, so it is necessary
281 // to create another instance.
282 OpenManifestEntryResource* open_cont = new OpenManifestEntryResource(*p);
283 open_cont->url = mapped_url;
284 pp::CompletionCallback stream_cc = WeakRefNewCallback(
287 &PluginReverseInterface::StreamAsFile_MainThreadContinuation,
290 if (!plugin_->StreamAsFile(mapped_url, stream_cc)) {
292 "OpenManifestEntry_MainThreadContinuation: "
293 "StreamAsFile failed\n");
294 // Here, StreamAsFile is failed and stream_cc is not called.
295 // However, open_cont will be released only by the invocation.
296 // So, we manually call it here with error.
297 stream_cc.Run(PP_ERROR_FAILED);
301 NaClLog(4, "OpenManifestEntry_MainThreadContinuation: StreamAsFile okay\n");
302 // p is deleted automatically
305 void PluginReverseInterface::StreamAsFile_MainThreadContinuation(
306 OpenManifestEntryResource* p,
309 "Entered StreamAsFile_MainThreadContinuation\n");
311 nacl::MutexLocker take(&mu_);
312 if (result == PP_OK) {
313 NaClLog(4, "StreamAsFile_MainThreadContinuation: GetFileInfo(%s)\n",
315 *p->file_info = plugin_->GetFileInfo(p->url);
318 "StreamAsFile_MainThreadContinuation: PP_OK, desc %d\n",
322 "StreamAsFile_MainThreadContinuation: !PP_OK, setting desc -1\n");
323 p->file_info->desc = -1;
325 *p->op_complete_ptr = true;
326 NaClXCondVarBroadcast(&cv_);
329 bool PluginReverseInterface::CloseManifestEntry(int32_t desc) {
330 bool op_complete = false;
332 CloseManifestEntryResource* to_close =
333 new CloseManifestEntryResource(desc, &op_complete, &op_result);
335 plugin::WeakRefCallOnMainThread(
339 &plugin::PluginReverseInterface::
340 CloseManifestEntry_MainThreadContinuation,
343 // wait for completion or surf-away.
345 nacl::MutexLocker take(&mu_);
346 while (!shutting_down_ && !op_complete)
347 NaClXCondVarWait(&cv_, &mu_);
352 // op_result true if close was successful; false otherwise (e.g., bad desc).
356 void PluginReverseInterface::CloseManifestEntry_MainThreadContinuation(
357 CloseManifestEntryResource* cls,
359 UNREFERENCED_PARAMETER(err);
361 nacl::MutexLocker take(&mu_);
362 // TODO(bsy): once the plugin has a reliable way to report that the
363 // file usage is done -- and sel_ldr uses this RPC call -- we should
364 // tell the plugin that the associated resources can be freed.
365 *cls->op_result_ptr = true;
366 *cls->op_complete_ptr = true;
367 NaClXCondVarBroadcast(&cv_);
368 // cls automatically deleted
371 void PluginReverseInterface::ReportCrash() {
372 NaClLog(4, "PluginReverseInterface::ReportCrash\n");
374 if (crash_cb_.pp_completion_callback().func != NULL) {
375 NaClLog(4, "PluginReverseInterface::ReportCrash: invoking CB\n");
376 pp::Module::Get()->core()->CallOnMainThread(0, crash_cb_, PP_OK);
379 "PluginReverseInterface::ReportCrash:"
380 " crash_cb_ not valid, skipping\n");
384 void PluginReverseInterface::ReportExitStatus(int exit_status) {
385 service_runtime_->set_exit_status(exit_status);
388 int64_t PluginReverseInterface::RequestQuotaForWrite(
389 nacl::string file_id, int64_t offset, int64_t bytes_to_write) {
391 "PluginReverseInterface::RequestQuotaForWrite:"
392 " (file_id='%s', offset=%" NACL_PRId64 ", bytes_to_write=%"
393 NACL_PRId64 ")\n", file_id.c_str(), offset, bytes_to_write);
394 uint64_t file_key = STRTOULL(file_id.c_str(), NULL, 10);
395 nacl::MutexLocker take(&mu_);
396 if (quota_files_.count(file_key) == 0) {
397 // Look up failed to find the requested quota managed resource.
398 NaClLog(4, "PluginReverseInterface::RequestQuotaForWrite: failed...\n");
402 // Because we now only support this interface for tempfiles which are not
403 // pepper objects, we can just do some crude quota enforcement here rather
404 // than calling out to pepper from the main thread.
405 if (offset + bytes_to_write >= kMaxTempQuota)
408 return bytes_to_write;
411 void PluginReverseInterface::AddTempQuotaManagedFile(
412 const nacl::string& file_id) {
413 NaClLog(4, "PluginReverseInterface::AddTempQuotaManagedFile: "
414 "(file_id='%s')\n", file_id.c_str());
415 uint64_t file_key = STRTOULL(file_id.c_str(), NULL, 10);
416 nacl::MutexLocker take(&mu_);
417 quota_files_.insert(file_key);
420 ServiceRuntime::ServiceRuntime(Plugin* plugin,
421 const Manifest* manifest,
422 bool main_service_runtime,
423 bool uses_nonsfi_mode,
424 pp::CompletionCallback init_done_cb,
425 pp::CompletionCallback crash_cb)
427 main_service_runtime_(main_service_runtime),
428 uses_nonsfi_mode_(uses_nonsfi_mode),
429 reverse_service_(NULL),
430 anchor_(new nacl::WeakRefAnchor()),
431 rev_interface_(new PluginReverseInterface(anchor_, plugin,
434 init_done_cb, crash_cb)),
436 start_sel_ldr_done_(false),
437 callback_factory_(this) {
438 NaClSrpcChannelInitialize(&command_channel_);
439 NaClXMutexCtor(&mu_);
440 NaClXCondVarCtor(&cond_);
443 bool ServiceRuntime::SetupCommandChannel(ErrorInfo* error_info) {
444 NaClLog(4, "ServiceRuntime::SetupCommand (this=%p, subprocess=%p)\n",
445 static_cast<void*>(this),
446 static_cast<void*>(subprocess_.get()));
447 if (!subprocess_->SetupCommand(&command_channel_)) {
448 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
449 "ServiceRuntime: command channel creation failed");
455 bool ServiceRuntime::LoadModule(nacl::DescWrapper* nacl_desc,
456 ErrorInfo* error_info) {
457 NaClLog(4, "ServiceRuntime::LoadModule"
458 " (this=%p, subprocess=%p)\n",
459 static_cast<void*>(this),
460 static_cast<void*>(subprocess_.get()));
462 if (!subprocess_->LoadModule(&command_channel_, nacl_desc)) {
463 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
464 "ServiceRuntime: load module failed");
470 bool ServiceRuntime::InitReverseService(ErrorInfo* error_info) {
471 if (uses_nonsfi_mode_) {
472 // In non-SFI mode, open_resource() is not yet supported, so we do not
473 // need the reverse service. So, skip the initialization (with calling
474 // the completion callback).
475 // Note that there is on going work to replace SRPC by Chrome IPC (not only
476 // for non-SFI mode, but also for SFI mode) (crbug.com/333950),
477 // and non-SFI mode will use Chrome IPC for open_resource() after the
478 // refactoring is done.
479 rev_interface_->StartupInitializationComplete();
483 // Hook up the reverse service channel. We are the IMC client, but
484 // provide SRPC service.
485 NaClDesc* out_conn_cap;
486 NaClSrpcResultCodes rpc_result =
487 NaClSrpcInvokeBySignature(&command_channel_,
491 if (NACL_SRPC_RESULT_OK != rpc_result) {
492 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SETUP,
493 "ServiceRuntime: reverse setup rpc failed");
496 // Get connection capability to service runtime where the IMC
497 // server/SRPC client is waiting for a rendezvous.
498 NaClLog(4, "ServiceRuntime: got 0x%" NACL_PRIxPTR "\n",
499 (uintptr_t) out_conn_cap);
500 nacl::DescWrapper* conn_cap = plugin_->wrapper_factory()->MakeGenericCleanup(
502 if (conn_cap == NULL) {
503 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_WRAPPER,
504 "ServiceRuntime: wrapper allocation failure");
507 out_conn_cap = NULL; // ownership passed
508 NaClLog(4, "ServiceRuntime::InitReverseService: starting reverse service\n");
509 reverse_service_ = new nacl::ReverseService(conn_cap, rev_interface_->Ref());
510 if (!reverse_service_->Start()) {
511 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SERVICE,
512 "ServiceRuntime: starting reverse services failed");
518 bool ServiceRuntime::StartModule(ErrorInfo* error_info) {
519 // start the module. otherwise we cannot connect for multimedia
520 // subsystem since that is handled by user-level code (not secure!)
522 int load_status = -1;
523 if (uses_nonsfi_mode_) {
524 // In non-SFI mode, we don't need to call start_module SRPC to launch
526 load_status = LOAD_OK;
528 NaClSrpcResultCodes rpc_result =
529 NaClSrpcInvokeBySignature(&command_channel_,
533 if (NACL_SRPC_RESULT_OK != rpc_result) {
534 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_START_MODULE,
535 "ServiceRuntime: could not start nacl module");
540 NaClLog(4, "ServiceRuntime::StartModule (load_status=%d)\n", load_status);
541 if (main_service_runtime_) {
542 plugin_->ReportSelLdrLoadStatus(load_status);
544 if (LOAD_OK != load_status) {
545 error_info->SetReport(
546 PP_NACL_ERROR_SEL_LDR_START_STATUS,
547 NaClErrorString(static_cast<NaClErrorCode>(load_status)));
553 void ServiceRuntime::StartSelLdr(const SelLdrStartParams& params,
554 pp::CompletionCallback callback) {
555 NaClLog(4, "ServiceRuntime::Start\n");
557 nacl::scoped_ptr<SelLdrLauncherChrome>
558 tmp_subprocess(new SelLdrLauncherChrome());
559 if (NULL == tmp_subprocess.get()) {
560 NaClLog(LOG_ERROR, "ServiceRuntime::Start (subprocess create failed)\n");
561 if (main_service_runtime_) {
562 ErrorInfo error_info;
563 error_info.SetReport(
564 PP_NACL_ERROR_SEL_LDR_CREATE_LAUNCHER,
565 "ServiceRuntime: failed to create sel_ldr launcher");
566 plugin_->ReportLoadError(error_info);
568 pp::Module::Get()->core()->CallOnMainThread(0, callback, PP_ERROR_FAILED);
571 pp::CompletionCallback internal_callback =
572 callback_factory_.NewCallback(&ServiceRuntime::StartSelLdrContinuation,
575 tmp_subprocess->Start(plugin_->pp_instance(),
579 params.uses_nonsfi_mode,
580 params.enable_dev_interfaces,
581 params.enable_dyncode_syscalls,
582 params.enable_exception_handling,
583 params.enable_crash_throttling,
584 &start_sel_ldr_error_message_,
586 subprocess_.reset(tmp_subprocess.release());
589 void ServiceRuntime::StartSelLdrContinuation(int32_t pp_error,
590 pp::CompletionCallback callback) {
591 if (pp_error != PP_OK) {
592 NaClLog(LOG_ERROR, "ServiceRuntime::StartSelLdrContinuation "
593 " (start failed)\n");
594 if (main_service_runtime_) {
595 std::string error_message;
596 pp::Var var_error_message_cpp(pp::PASS_REF, start_sel_ldr_error_message_);
597 if (var_error_message_cpp.is_string()) {
598 error_message = var_error_message_cpp.AsString();
600 ErrorInfo error_info;
601 error_info.SetReportWithConsoleOnlyError(
602 PP_NACL_ERROR_SEL_LDR_LAUNCH,
603 "ServiceRuntime: failed to start",
605 plugin_->ReportLoadError(error_info);
608 pp::Module::Get()->core()->CallOnMainThread(0, callback, pp_error);
611 bool ServiceRuntime::WaitForSelLdrStart() {
612 // Time to wait on condvar (for browser to create a new sel_ldr process on
613 // our behalf). Use 6 seconds to be *fairly* conservative.
615 // On surfaway, the CallOnMainThread above may never get scheduled
616 // to unblock this condvar, or the IPC reply from the browser to renderer
617 // might get canceled/dropped. However, it is currently important to
618 // avoid waiting indefinitely because ~PnaclCoordinator will attempt to
619 // join() the PnaclTranslateThread, and the PnaclTranslateThread is waiting
620 // for the signal before exiting.
621 static int64_t const kWaitTimeMicrosecs = 6 * NACL_MICROS_PER_UNIT;
622 int64_t left_to_wait = kWaitTimeMicrosecs;
623 int64_t deadline = NaClGetTimeOfDayMicroseconds() + left_to_wait;
624 nacl::MutexLocker take(&mu_);
625 while(!start_sel_ldr_done_ && left_to_wait > 0) {
626 struct nacl_abi_timespec left_timespec;
627 left_timespec.tv_sec = left_to_wait / NACL_MICROS_PER_UNIT;
628 left_timespec.tv_nsec =
629 (left_to_wait % NACL_MICROS_PER_UNIT) * NACL_NANOS_PER_MICRO;
630 NaClXCondVarTimedWaitRelative(&cond_, &mu_, &left_timespec);
631 int64_t now = NaClGetTimeOfDayMicroseconds();
632 left_to_wait = deadline - now;
634 return start_sel_ldr_done_;
637 void ServiceRuntime::SignalStartSelLdrDone() {
638 nacl::MutexLocker take(&mu_);
639 start_sel_ldr_done_ = true;
640 NaClXCondVarSignal(&cond_);
643 bool ServiceRuntime::LoadNexeAndStart(nacl::DescWrapper* nacl_desc,
644 const pp::CompletionCallback& crash_cb) {
645 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (nacl_desc=%p)\n",
646 reinterpret_cast<void*>(nacl_desc));
647 ErrorInfo error_info;
649 bool ok = SetupCommandChannel(&error_info) &&
650 InitReverseService(&error_info) &&
651 LoadModule(nacl_desc, &error_info) &&
652 StartModule(&error_info);
654 if (main_service_runtime_) {
655 plugin_->ReportLoadError(error_info);
657 // On a load failure the service runtime does not crash itself to
658 // avoid a race where the no-more-senders error on the reverse
659 // channel esrvice thread might cause the crash-detection logic to
660 // kick in before the start_module RPC reply has been received. So
661 // we induce a service runtime crash here. We do not release
662 // subprocess_ since it's needed to collect crash log output after
663 // the error is reported.
664 Log(LOG_FATAL, "reap logs");
665 if (NULL == reverse_service_) {
666 // No crash detector thread.
667 NaClLog(LOG_ERROR, "scheduling to get crash log\n");
668 pp::Module::Get()->core()->CallOnMainThread(0, crash_cb, PP_OK);
669 NaClLog(LOG_ERROR, "should fire soon\n");
671 NaClLog(LOG_ERROR, "Reverse service thread will pick up crash log\n");
676 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (return 1)\n");
680 SrpcClient* ServiceRuntime::SetupAppChannel() {
681 NaClLog(4, "ServiceRuntime::SetupAppChannel (subprocess_=%p)\n",
682 reinterpret_cast<void*>(subprocess_.get()));
683 nacl::DescWrapper* connect_desc = subprocess_->socket_addr()->Connect();
684 if (NULL == connect_desc) {
685 NaClLog(LOG_ERROR, "ServiceRuntime::SetupAppChannel (connect failed)\n");
688 NaClLog(4, "ServiceRuntime::SetupAppChannel (conect_desc=%p)\n",
689 static_cast<void*>(connect_desc));
690 SrpcClient* srpc_client = SrpcClient::New(connect_desc);
691 NaClLog(4, "ServiceRuntime::SetupAppChannel (srpc_client=%p)\n",
692 static_cast<void*>(srpc_client));
698 bool ServiceRuntime::Log(int severity, const nacl::string& msg) {
699 NaClSrpcResultCodes rpc_result =
700 NaClSrpcInvokeBySignature(&command_channel_,
703 strdup(msg.c_str()));
704 return (NACL_SRPC_RESULT_OK == rpc_result);
707 void ServiceRuntime::Shutdown() {
708 rev_interface_->ShutDown();
710 // Abandon callbacks, tell service threads to quit if they were
711 // blocked waiting for main thread operations to finish. Note that
712 // some callbacks must still await their completion event, e.g.,
713 // CallOnMainThread must still wait for the time out, or I/O events
714 // must finish, so resources associated with pending events cannot
717 // Note that this does waitpid() to get rid of any zombie subprocess.
718 subprocess_.reset(NULL);
720 NaClSrpcDtor(&command_channel_);
722 // subprocess_ has been shut down, but threads waiting on messages
723 // from the service runtime may not have noticed yet. The low-level
724 // NaClSimpleRevService code takes care to refcount the data objects
725 // that it needs, and reverse_service_ is also refcounted. We wait
726 // for the service threads to get their EOF indications.
727 if (reverse_service_ != NULL) {
728 reverse_service_->WaitForServiceThreadsToExit();
729 reverse_service_->Unref();
730 reverse_service_ = NULL;
734 ServiceRuntime::~ServiceRuntime() {
735 NaClLog(4, "ServiceRuntime::~ServiceRuntime (this=%p)\n",
736 static_cast<void*>(this));
737 // We do this just in case Shutdown() was not called.
738 subprocess_.reset(NULL);
739 if (reverse_service_ != NULL) {
740 reverse_service_->Unref();
743 rev_interface_->Unref();
746 NaClCondVarDtor(&cond_);
750 void ServiceRuntime::set_exit_status(int exit_status) {
751 nacl::MutexLocker take(&mu_);
752 if (main_service_runtime_)
753 plugin_->set_exit_status(exit_status & 0xff);
756 nacl::string ServiceRuntime::GetCrashLogOutput() {
757 if (NULL != subprocess_.get()) {
758 return subprocess_->GetCrashLogOutput();
760 return std::string();
764 } // namespace plugin