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/plugin.h"
51 #include "ppapi/native_client/src/trusted/plugin/plugin_error.h"
52 #include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
53 #include "ppapi/native_client/src/trusted/plugin/sel_ldr_launcher_chrome.h"
54 #include "ppapi/native_client/src/trusted/plugin/srpc_client.h"
55 #include "ppapi/native_client/src/trusted/weak_ref/call_on_main_thread.h"
59 class OpenManifestEntryAsyncCallback {
61 OpenManifestEntryAsyncCallback(PP_OpenResourceCompletionCallback callback,
62 void* callback_user_data)
63 : callback_(callback), callback_user_data_(callback_user_data) {
66 ~OpenManifestEntryAsyncCallback() {
68 callback_(callback_user_data_, PP_kInvalidFileHandle);
71 void Run(int32_t pp_error) {
73 // Currently, this is used only for non-SFI mode, and now the mode is not
74 // supported on windows.
75 // TODO(hidehiko): Support it on Windows when we switch to use
76 // ManifestService also in SFI-mode.
78 #elif defined(OS_POSIX)
79 // On posix, PlatformFile is the file descriptor.
80 callback_(callback_user_data_, (pp_error == PP_OK) ? info_.desc : -1);
85 NaClFileInfo* mutable_info() { return &info_; }
89 PP_OpenResourceCompletionCallback callback_;
90 void* callback_user_data_;
91 DISALLOW_COPY_AND_ASSIGN(OpenManifestEntryAsyncCallback);
96 // For doing crude quota enforcement on writes to temp files.
97 // We do not allow a temp file bigger than 128 MB for now.
98 // There is currently a limit of 32M for nexe text size, so 128M
99 // should be plenty for static data
100 const int64_t kMaxTempQuota = 0x8000000;
102 class ManifestService {
104 ManifestService(nacl::WeakRefAnchor* anchor,
105 PluginReverseInterface* plugin_reverse)
107 plugin_reverse_(plugin_reverse) {
119 bool StartupInitializationComplete() {
120 // Release this instance if the ServiceRuntime is already destructed.
121 if (anchor_->is_abandoned()) {
126 plugin_reverse_->StartupInitializationComplete();
130 bool OpenResource(const char* entry_key,
131 PP_OpenResourceCompletionCallback callback,
132 void* callback_user_data) {
133 // Release this instance if the ServiceRuntime is already destructed.
134 if (anchor_->is_abandoned()) {
135 callback(callback_user_data, PP_kInvalidFileHandle);
140 OpenManifestEntryAsyncCallback* open_manifest_callback =
141 new OpenManifestEntryAsyncCallback(callback, callback_user_data);
142 plugin_reverse_->OpenManifestEntryAsync(
144 open_manifest_callback->mutable_info(),
145 open_manifest_callback);
149 static PP_Bool QuitTrampoline(void* user_data) {
150 return PP_FromBool(static_cast<ManifestService*>(user_data)->Quit());
153 static PP_Bool StartupInitializationCompleteTrampoline(void* user_data) {
154 return PP_FromBool(static_cast<ManifestService*>(user_data)->
155 StartupInitializationComplete());
158 static PP_Bool OpenResourceTrampoline(
160 const char* entry_key,
161 PP_OpenResourceCompletionCallback callback,
162 void* callback_user_data) {
163 return PP_FromBool(static_cast<ManifestService*>(user_data)->OpenResource(
164 entry_key, callback, callback_user_data));
168 // Weak reference to check if plugin_reverse is legally accessible or not.
169 nacl::WeakRefAnchor* anchor_;
170 PluginReverseInterface* plugin_reverse_;
172 DISALLOW_COPY_AND_ASSIGN(ManifestService);
175 // Vtable to pass functions to LaunchSelLdr.
176 const PPP_ManifestService kManifestServiceVTable = {
177 &ManifestService::QuitTrampoline,
178 &ManifestService::StartupInitializationCompleteTrampoline,
179 &ManifestService::OpenResourceTrampoline,
184 OpenManifestEntryResource::~OpenManifestEntryResource() {
185 MaybeRunCallback(PP_ERROR_ABORTED);
188 void OpenManifestEntryResource::MaybeRunCallback(int32_t pp_error) {
192 callback->Run(pp_error);
197 PluginReverseInterface::PluginReverseInterface(
198 nacl::WeakRefAnchor* anchor,
201 ServiceRuntime* service_runtime,
202 pp::CompletionCallback init_done_cb,
203 pp::CompletionCallback crash_cb)
206 manifest_id_(manifest_id),
207 service_runtime_(service_runtime),
208 shutting_down_(false),
209 init_done_cb_(init_done_cb),
210 crash_cb_(crash_cb) {
211 NaClXMutexCtor(&mu_);
212 NaClXCondVarCtor(&cv_);
215 PluginReverseInterface::~PluginReverseInterface() {
216 NaClCondVarDtor(&cv_);
220 void PluginReverseInterface::ShutDown() {
221 NaClLog(4, "PluginReverseInterface::Shutdown: entered\n");
222 nacl::MutexLocker take(&mu_);
223 shutting_down_ = true;
224 NaClXCondVarBroadcast(&cv_);
225 NaClLog(4, "PluginReverseInterface::Shutdown: broadcasted, exiting\n");
228 void PluginReverseInterface::DoPostMessage(nacl::string message) {
229 PostMessageResource* continuation = new PostMessageResource(message);
230 CHECK(continuation != NULL);
231 NaClLog(4, "PluginReverseInterface::DoPostMessage(%s)\n", message.c_str());
232 plugin::WeakRefCallOnMainThread(
236 &plugin::PluginReverseInterface::PostMessage_MainThreadContinuation,
240 void PluginReverseInterface::StartupInitializationComplete() {
241 NaClLog(4, "PluginReverseInterface::StartupInitializationComplete\n");
242 if (init_done_cb_.pp_completion_callback().func != NULL) {
244 "PluginReverseInterface::StartupInitializationComplete:"
246 pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb_, PP_OK);
249 "PluginReverseInterface::StartupInitializationComplete:"
250 " init_done_cb_ not valid, skipping.\n");
254 void PluginReverseInterface::PostMessage_MainThreadContinuation(
255 PostMessageResource* p,
257 UNREFERENCED_PARAMETER(err);
259 "PluginReverseInterface::PostMessage_MainThreadContinuation(%s)\n",
261 plugin_->PostMessage(std::string("DEBUG_POSTMESSAGE:") + p->message);
264 // TODO(bsy): OpenManifestEntry should use the manifest to ResolveKey
265 // and invoke StreamAsFile with a completion callback that invokes
267 bool PluginReverseInterface::OpenManifestEntry(nacl::string url_key,
268 struct NaClFileInfo* info) {
269 bool op_complete = false; // NB: mu_ and cv_ also controls access to this!
270 // The to_open object is owned by the weak ref callback. Because this function
271 // waits for the callback to finish, the to_open object will be deallocated on
272 // the main thread before this function can return. The pointers it contains
273 // to stack variables will not leak.
274 OpenManifestEntryResource* to_open =
275 new OpenManifestEntryResource(url_key, info, &op_complete, NULL);
276 CHECK(to_open != NULL);
277 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: %s\n",
279 // This assumes we are not on the main thread. If false, we deadlock.
280 plugin::WeakRefCallOnMainThread(
284 &plugin::PluginReverseInterface::OpenManifestEntry_MainThreadContinuation,
287 "PluginReverseInterface::OpenManifestEntry:"
288 " waiting on main thread\n");
291 nacl::MutexLocker take(&mu_);
292 while (!shutting_down_ && !op_complete)
293 NaClXCondVarWait(&cv_, &mu_);
294 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: done!\n");
295 if (shutting_down_) {
297 "PluginReverseInterface::OpenManifestEntry:"
298 " plugin is shutting down\n");
303 // info->desc has the returned descriptor if successful, else -1.
305 // The caller is responsible for not closing info->desc. If it is
306 // closed prematurely, then another open could re-use the OS
307 // descriptor, confusing the opened_ map. If the caller is going to
308 // want to make a NaClDesc object and transfer it etc., then the
309 // caller should DUP the descriptor (but remember the original
310 // value) for use by the NaClDesc object, which closes when the
311 // object is destroyed.
313 "PluginReverseInterface::OpenManifestEntry: info->desc = %d\n",
315 if (info->desc == -1) {
316 // TODO(bsy,ncbray): what else should we do with the error? This
317 // is a runtime error that may simply be a programming error in
318 // the untrusted code, or it may be something else wrong w/ the
320 NaClLog(4, "OpenManifestEntry: failed for key %s", url_key.c_str());
325 void PluginReverseInterface::OpenManifestEntryAsync(
326 const nacl::string& entry_key,
327 struct NaClFileInfo* info,
328 OpenManifestEntryAsyncCallback* callback) {
329 bool op_complete = false;
330 OpenManifestEntryResource to_open(
331 entry_key, info, &op_complete, callback);
332 OpenManifestEntry_MainThreadContinuation(&to_open, PP_OK);
335 // Transfer point from OpenManifestEntry() which runs on the main thread
336 // (Some PPAPI actions -- like StreamAsFile -- can only run on the main thread).
337 // OpenManifestEntry() is waiting on a condvar for this continuation to
338 // complete. We Broadcast and awaken OpenManifestEntry() whenever we are done
339 // either here, or in a later MainThreadContinuation step, if there are
341 void PluginReverseInterface::OpenManifestEntry_MainThreadContinuation(
342 OpenManifestEntryResource* p,
344 UNREFERENCED_PARAMETER(err);
345 // CallOnMainThread continuations always called with err == PP_OK.
347 NaClLog(4, "Entered OpenManifestEntry_MainThreadContinuation\n");
349 PP_Var pp_mapped_url;
350 PP_PNaClOptions pnacl_options = {PP_FALSE, PP_FALSE, 2};
351 if (!GetNaClInterface()->ManifestResolveKey(plugin_->pp_instance(),
356 NaClLog(4, "OpenManifestEntry_MainThreadContinuation: ResolveKey failed\n");
357 // Failed, and error_info has the details on what happened. Wake
358 // up requesting thread -- we are done.
360 nacl::MutexLocker take(&mu_);
361 *p->op_complete_ptr = true; // done...
362 p->file_info->desc = -1; // but failed.
363 NaClXCondVarBroadcast(&cv_);
365 p->MaybeRunCallback(PP_OK);
368 nacl::string mapped_url = pp::Var(pp_mapped_url).AsString();
370 "OpenManifestEntry_MainThreadContinuation: "
371 "ResolveKey: %s -> %s (pnacl_translate(%d))\n",
372 p->url.c_str(), mapped_url.c_str(), pnacl_options.translate);
374 if (pnacl_options.translate) {
375 // Requires PNaCl translation, but that's not supported.
377 "OpenManifestEntry_MainThreadContinuation: "
378 "Requires PNaCl translation -- not supported\n");
380 nacl::MutexLocker take(&mu_);
381 *p->op_complete_ptr = true; // done...
382 p->file_info->desc = -1; // but failed.
383 NaClXCondVarBroadcast(&cv_);
385 p->MaybeRunCallback(PP_OK);
389 if (PnaclUrls::IsPnaclComponent(mapped_url)) {
390 // Special PNaCl support files, that are installed on the
392 int32_t fd = PnaclResources::GetPnaclFD(
394 PnaclUrls::PnaclComponentURLToFilename(mapped_url).c_str());
396 // We checked earlier if the pnacl component wasn't installed
397 // yet, so this shouldn't happen. At this point, we can't do much
398 // anymore, so just continue with an invalid fd.
400 "OpenManifestEntry_MainThreadContinuation: "
401 "GetReadonlyPnaclFd failed\n");
404 nacl::MutexLocker take(&mu_);
405 *p->op_complete_ptr = true; // done!
406 // TODO(ncbray): enable the fast loading and validation paths for this
408 p->file_info->desc = fd;
409 NaClXCondVarBroadcast(&cv_);
412 "OpenManifestEntry_MainThreadContinuation: GetPnaclFd okay\n");
413 p->MaybeRunCallback(PP_OK);
417 // Hereafter, normal files.
419 // Because p is owned by the callback of this invocation, so it is necessary
420 // to create another instance.
421 OpenManifestEntryResource* open_cont = new OpenManifestEntryResource(*p);
422 open_cont->url = mapped_url;
423 // Callback is now delegated from p to open_cont. So, here we manually clear
424 // complete callback.
426 pp::CompletionCallback stream_cc = WeakRefNewCallback(
429 &PluginReverseInterface::StreamAsFile_MainThreadContinuation,
432 if (!plugin_->StreamAsFile(mapped_url, stream_cc)) {
434 "OpenManifestEntry_MainThreadContinuation: "
435 "StreamAsFile failed\n");
436 // Here, StreamAsFile is failed and stream_cc is not called.
437 // However, open_cont will be released only by the invocation.
438 // So, we manually call it here with error.
439 stream_cc.Run(PP_ERROR_FAILED);
443 NaClLog(4, "OpenManifestEntry_MainThreadContinuation: StreamAsFile okay\n");
444 // p is deleted automatically
447 void PluginReverseInterface::StreamAsFile_MainThreadContinuation(
448 OpenManifestEntryResource* p,
451 "Entered StreamAsFile_MainThreadContinuation\n");
454 nacl::MutexLocker take(&mu_);
455 if (result == PP_OK) {
456 NaClLog(4, "StreamAsFile_MainThreadContinuation: GetFileInfo(%s)\n",
458 *p->file_info = plugin_->GetFileInfo(p->url);
461 "StreamAsFile_MainThreadContinuation: PP_OK, desc %d\n",
466 "StreamAsFile_MainThreadContinuation: !PP_OK, setting desc -1\n");
467 p->file_info->desc = -1;
469 *p->op_complete_ptr = true;
470 NaClXCondVarBroadcast(&cv_);
472 p->MaybeRunCallback(PP_OK);
475 bool PluginReverseInterface::CloseManifestEntry(int32_t desc) {
476 bool op_complete = false;
478 CloseManifestEntryResource* to_close =
479 new CloseManifestEntryResource(desc, &op_complete, &op_result);
481 plugin::WeakRefCallOnMainThread(
485 &plugin::PluginReverseInterface::
486 CloseManifestEntry_MainThreadContinuation,
489 // wait for completion or surf-away.
491 nacl::MutexLocker take(&mu_);
492 while (!shutting_down_ && !op_complete)
493 NaClXCondVarWait(&cv_, &mu_);
498 // op_result true if close was successful; false otherwise (e.g., bad desc).
502 void PluginReverseInterface::CloseManifestEntry_MainThreadContinuation(
503 CloseManifestEntryResource* cls,
505 UNREFERENCED_PARAMETER(err);
507 nacl::MutexLocker take(&mu_);
508 // TODO(bsy): once the plugin has a reliable way to report that the
509 // file usage is done -- and sel_ldr uses this RPC call -- we should
510 // tell the plugin that the associated resources can be freed.
511 *cls->op_result_ptr = true;
512 *cls->op_complete_ptr = true;
513 NaClXCondVarBroadcast(&cv_);
514 // cls automatically deleted
517 void PluginReverseInterface::ReportCrash() {
518 NaClLog(4, "PluginReverseInterface::ReportCrash\n");
520 if (crash_cb_.pp_completion_callback().func != NULL) {
521 NaClLog(4, "PluginReverseInterface::ReportCrash: invoking CB\n");
522 pp::Module::Get()->core()->CallOnMainThread(0, crash_cb_, PP_OK);
525 "PluginReverseInterface::ReportCrash:"
526 " crash_cb_ not valid, skipping\n");
530 void PluginReverseInterface::ReportExitStatus(int exit_status) {
531 service_runtime_->set_exit_status(exit_status);
534 int64_t PluginReverseInterface::RequestQuotaForWrite(
535 nacl::string file_id, int64_t offset, int64_t bytes_to_write) {
537 "PluginReverseInterface::RequestQuotaForWrite:"
538 " (file_id='%s', offset=%" NACL_PRId64 ", bytes_to_write=%"
539 NACL_PRId64 ")\n", file_id.c_str(), offset, bytes_to_write);
540 uint64_t file_key = STRTOULL(file_id.c_str(), NULL, 10);
541 nacl::MutexLocker take(&mu_);
542 if (quota_files_.count(file_key) == 0) {
543 // Look up failed to find the requested quota managed resource.
544 NaClLog(4, "PluginReverseInterface::RequestQuotaForWrite: failed...\n");
548 // Because we now only support this interface for tempfiles which are not
549 // pepper objects, we can just do some crude quota enforcement here rather
550 // than calling out to pepper from the main thread.
551 if (offset + bytes_to_write >= kMaxTempQuota)
554 return bytes_to_write;
557 void PluginReverseInterface::AddTempQuotaManagedFile(
558 const nacl::string& file_id) {
559 NaClLog(4, "PluginReverseInterface::AddTempQuotaManagedFile: "
560 "(file_id='%s')\n", file_id.c_str());
561 uint64_t file_key = STRTOULL(file_id.c_str(), NULL, 10);
562 nacl::MutexLocker take(&mu_);
563 quota_files_.insert(file_key);
566 ServiceRuntime::ServiceRuntime(Plugin* plugin,
568 bool main_service_runtime,
569 bool uses_nonsfi_mode,
570 pp::CompletionCallback init_done_cb,
571 pp::CompletionCallback crash_cb)
573 main_service_runtime_(main_service_runtime),
574 uses_nonsfi_mode_(uses_nonsfi_mode),
575 reverse_service_(NULL),
576 anchor_(new nacl::WeakRefAnchor()),
577 rev_interface_(new PluginReverseInterface(anchor_, plugin,
580 init_done_cb, crash_cb)),
582 start_sel_ldr_done_(false),
583 callback_factory_(this) {
584 NaClSrpcChannelInitialize(&command_channel_);
585 NaClXMutexCtor(&mu_);
586 NaClXCondVarCtor(&cond_);
589 bool ServiceRuntime::SetupCommandChannel(ErrorInfo* error_info) {
590 NaClLog(4, "ServiceRuntime::SetupCommand (this=%p, subprocess=%p)\n",
591 static_cast<void*>(this),
592 static_cast<void*>(subprocess_.get()));
593 if (!subprocess_->SetupCommand(&command_channel_)) {
594 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
595 "ServiceRuntime: command channel creation failed");
601 bool ServiceRuntime::LoadModule(nacl::DescWrapper* nacl_desc,
602 ErrorInfo* error_info) {
603 NaClLog(4, "ServiceRuntime::LoadModule"
604 " (this=%p, subprocess=%p)\n",
605 static_cast<void*>(this),
606 static_cast<void*>(subprocess_.get()));
608 if (!subprocess_->LoadModule(&command_channel_, nacl_desc)) {
609 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
610 "ServiceRuntime: load module failed");
616 bool ServiceRuntime::InitReverseService(ErrorInfo* error_info) {
617 if (uses_nonsfi_mode_) {
618 // In non-SFI mode, no reverse service is set up. Just returns success.
622 // Hook up the reverse service channel. We are the IMC client, but
623 // provide SRPC service.
624 NaClDesc* out_conn_cap;
625 NaClSrpcResultCodes rpc_result =
626 NaClSrpcInvokeBySignature(&command_channel_,
630 if (NACL_SRPC_RESULT_OK != rpc_result) {
631 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SETUP,
632 "ServiceRuntime: reverse setup rpc failed");
635 // Get connection capability to service runtime where the IMC
636 // server/SRPC client is waiting for a rendezvous.
637 NaClLog(4, "ServiceRuntime: got 0x%" NACL_PRIxPTR "\n",
638 (uintptr_t) out_conn_cap);
639 nacl::DescWrapper* conn_cap = plugin_->wrapper_factory()->MakeGenericCleanup(
641 if (conn_cap == NULL) {
642 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_WRAPPER,
643 "ServiceRuntime: wrapper allocation failure");
646 out_conn_cap = NULL; // ownership passed
647 NaClLog(4, "ServiceRuntime::InitReverseService: starting reverse service\n");
648 reverse_service_ = new nacl::ReverseService(conn_cap, rev_interface_->Ref());
649 if (!reverse_service_->Start()) {
650 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SERVICE,
651 "ServiceRuntime: starting reverse services failed");
657 bool ServiceRuntime::StartModule(ErrorInfo* error_info) {
658 // start the module. otherwise we cannot connect for multimedia
659 // subsystem since that is handled by user-level code (not secure!)
661 int load_status = -1;
662 if (uses_nonsfi_mode_) {
663 // In non-SFI mode, we don't need to call start_module SRPC to launch
665 load_status = LOAD_OK;
667 NaClSrpcResultCodes rpc_result =
668 NaClSrpcInvokeBySignature(&command_channel_,
672 if (NACL_SRPC_RESULT_OK != rpc_result) {
673 error_info->SetReport(PP_NACL_ERROR_SEL_LDR_START_MODULE,
674 "ServiceRuntime: could not start nacl module");
679 NaClLog(4, "ServiceRuntime::StartModule (load_status=%d)\n", load_status);
680 if (main_service_runtime_) {
681 plugin_->ReportSelLdrLoadStatus(load_status);
683 if (LOAD_OK != load_status) {
684 error_info->SetReport(
685 PP_NACL_ERROR_SEL_LDR_START_STATUS,
686 NaClErrorString(static_cast<NaClErrorCode>(load_status)));
692 void ServiceRuntime::StartSelLdr(const SelLdrStartParams& params,
693 pp::CompletionCallback callback) {
694 NaClLog(4, "ServiceRuntime::Start\n");
696 nacl::scoped_ptr<SelLdrLauncherChrome>
697 tmp_subprocess(new SelLdrLauncherChrome());
698 if (NULL == tmp_subprocess.get()) {
699 NaClLog(LOG_ERROR, "ServiceRuntime::Start (subprocess create failed)\n");
700 if (main_service_runtime_) {
701 ErrorInfo error_info;
702 error_info.SetReport(
703 PP_NACL_ERROR_SEL_LDR_CREATE_LAUNCHER,
704 "ServiceRuntime: failed to create sel_ldr launcher");
705 plugin_->ReportLoadError(error_info);
707 pp::Module::Get()->core()->CallOnMainThread(0, callback, PP_ERROR_FAILED);
710 pp::CompletionCallback internal_callback =
711 callback_factory_.NewCallback(&ServiceRuntime::StartSelLdrContinuation,
714 ManifestService* manifest_service =
715 new ManifestService(anchor_->Ref(), rev_interface_);
716 tmp_subprocess->Start(plugin_->pp_instance(),
720 params.uses_nonsfi_mode,
721 params.enable_dev_interfaces,
722 params.enable_dyncode_syscalls,
723 params.enable_exception_handling,
724 params.enable_crash_throttling,
725 &kManifestServiceVTable,
727 &start_sel_ldr_error_message_,
729 subprocess_.reset(tmp_subprocess.release());
732 void ServiceRuntime::StartSelLdrContinuation(int32_t pp_error,
733 pp::CompletionCallback callback) {
734 if (pp_error != PP_OK) {
735 NaClLog(LOG_ERROR, "ServiceRuntime::StartSelLdrContinuation "
736 " (start failed)\n");
737 if (main_service_runtime_) {
738 std::string error_message;
739 pp::Var var_error_message_cpp(pp::PASS_REF, start_sel_ldr_error_message_);
740 if (var_error_message_cpp.is_string()) {
741 error_message = var_error_message_cpp.AsString();
743 ErrorInfo error_info;
744 error_info.SetReportWithConsoleOnlyError(
745 PP_NACL_ERROR_SEL_LDR_LAUNCH,
746 "ServiceRuntime: failed to start",
748 plugin_->ReportLoadError(error_info);
751 pp::Module::Get()->core()->CallOnMainThread(0, callback, pp_error);
754 bool ServiceRuntime::WaitForSelLdrStart() {
755 // Time to wait on condvar (for browser to create a new sel_ldr process on
756 // our behalf). Use 6 seconds to be *fairly* conservative.
758 // On surfaway, the CallOnMainThread above may never get scheduled
759 // to unblock this condvar, or the IPC reply from the browser to renderer
760 // might get canceled/dropped. However, it is currently important to
761 // avoid waiting indefinitely because ~PnaclCoordinator will attempt to
762 // join() the PnaclTranslateThread, and the PnaclTranslateThread is waiting
763 // for the signal before exiting.
764 static int64_t const kWaitTimeMicrosecs = 6 * NACL_MICROS_PER_UNIT;
765 int64_t left_to_wait = kWaitTimeMicrosecs;
766 int64_t deadline = NaClGetTimeOfDayMicroseconds() + left_to_wait;
767 nacl::MutexLocker take(&mu_);
768 while(!start_sel_ldr_done_ && left_to_wait > 0) {
769 struct nacl_abi_timespec left_timespec;
770 left_timespec.tv_sec = left_to_wait / NACL_MICROS_PER_UNIT;
771 left_timespec.tv_nsec =
772 (left_to_wait % NACL_MICROS_PER_UNIT) * NACL_NANOS_PER_MICRO;
773 NaClXCondVarTimedWaitRelative(&cond_, &mu_, &left_timespec);
774 int64_t now = NaClGetTimeOfDayMicroseconds();
775 left_to_wait = deadline - now;
777 return start_sel_ldr_done_;
780 void ServiceRuntime::SignalStartSelLdrDone() {
781 nacl::MutexLocker take(&mu_);
782 start_sel_ldr_done_ = true;
783 NaClXCondVarSignal(&cond_);
786 bool ServiceRuntime::LoadNexeAndStart(nacl::DescWrapper* nacl_desc,
787 const pp::CompletionCallback& crash_cb) {
788 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (nacl_desc=%p)\n",
789 reinterpret_cast<void*>(nacl_desc));
790 ErrorInfo error_info;
792 bool ok = SetupCommandChannel(&error_info) &&
793 InitReverseService(&error_info) &&
794 LoadModule(nacl_desc, &error_info) &&
795 StartModule(&error_info);
797 if (main_service_runtime_) {
798 plugin_->ReportLoadError(error_info);
800 // On a load failure the service runtime does not crash itself to
801 // avoid a race where the no-more-senders error on the reverse
802 // channel esrvice thread might cause the crash-detection logic to
803 // kick in before the start_module RPC reply has been received. So
804 // we induce a service runtime crash here. We do not release
805 // subprocess_ since it's needed to collect crash log output after
806 // the error is reported.
807 Log(LOG_FATAL, "reap logs");
808 if (NULL == reverse_service_) {
809 // No crash detector thread.
810 NaClLog(LOG_ERROR, "scheduling to get crash log\n");
811 pp::Module::Get()->core()->CallOnMainThread(0, crash_cb, PP_OK);
812 NaClLog(LOG_ERROR, "should fire soon\n");
814 NaClLog(LOG_ERROR, "Reverse service thread will pick up crash log\n");
819 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (return 1)\n");
823 SrpcClient* ServiceRuntime::SetupAppChannel() {
824 NaClLog(4, "ServiceRuntime::SetupAppChannel (subprocess_=%p)\n",
825 reinterpret_cast<void*>(subprocess_.get()));
826 nacl::DescWrapper* connect_desc = subprocess_->socket_addr()->Connect();
827 if (NULL == connect_desc) {
828 NaClLog(LOG_ERROR, "ServiceRuntime::SetupAppChannel (connect failed)\n");
831 NaClLog(4, "ServiceRuntime::SetupAppChannel (conect_desc=%p)\n",
832 static_cast<void*>(connect_desc));
833 SrpcClient* srpc_client = SrpcClient::New(connect_desc);
834 NaClLog(4, "ServiceRuntime::SetupAppChannel (srpc_client=%p)\n",
835 static_cast<void*>(srpc_client));
841 bool ServiceRuntime::Log(int severity, const nacl::string& msg) {
842 NaClSrpcResultCodes rpc_result =
843 NaClSrpcInvokeBySignature(&command_channel_,
846 strdup(msg.c_str()));
847 return (NACL_SRPC_RESULT_OK == rpc_result);
850 void ServiceRuntime::Shutdown() {
851 rev_interface_->ShutDown();
853 // Abandon callbacks, tell service threads to quit if they were
854 // blocked waiting for main thread operations to finish. Note that
855 // some callbacks must still await their completion event, e.g.,
856 // CallOnMainThread must still wait for the time out, or I/O events
857 // must finish, so resources associated with pending events cannot
860 // Note that this does waitpid() to get rid of any zombie subprocess.
861 subprocess_.reset(NULL);
863 NaClSrpcDtor(&command_channel_);
865 // subprocess_ has been shut down, but threads waiting on messages
866 // from the service runtime may not have noticed yet. The low-level
867 // NaClSimpleRevService code takes care to refcount the data objects
868 // that it needs, and reverse_service_ is also refcounted. We wait
869 // for the service threads to get their EOF indications.
870 if (reverse_service_ != NULL) {
871 reverse_service_->WaitForServiceThreadsToExit();
872 reverse_service_->Unref();
873 reverse_service_ = NULL;
877 ServiceRuntime::~ServiceRuntime() {
878 NaClLog(4, "ServiceRuntime::~ServiceRuntime (this=%p)\n",
879 static_cast<void*>(this));
880 // We do this just in case Shutdown() was not called.
881 subprocess_.reset(NULL);
882 if (reverse_service_ != NULL) {
883 reverse_service_->Unref();
886 rev_interface_->Unref();
889 NaClCondVarDtor(&cond_);
893 void ServiceRuntime::set_exit_status(int exit_status) {
894 nacl::MutexLocker take(&mu_);
895 if (main_service_runtime_)
896 plugin_->set_exit_status(exit_status & 0xff);
899 nacl::string ServiceRuntime::GetCrashLogOutput() {
900 if (NULL != subprocess_.get()) {
901 return subprocess_->GetCrashLogOutput();
903 return std::string();
907 } // namespace plugin