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 #include "native_client/src/public/imc_types.h"
37 #include "native_client/src/public/nacl_file_info.h"
38 #include "native_client/src/trusted/service_runtime/nacl_error_code.h"
40 #include "ppapi/c/pp_errors.h"
41 #include "ppapi/cpp/core.h"
42 #include "ppapi/cpp/completion_callback.h"
44 #include "ppapi/native_client/src/trusted/plugin/plugin.h"
45 #include "ppapi/native_client/src/trusted/plugin/plugin_error.h"
46 #include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
47 #include "ppapi/native_client/src/trusted/plugin/sel_ldr_launcher_chrome.h"
48 #include "ppapi/native_client/src/trusted/plugin/srpc_client.h"
49 #include "ppapi/native_client/src/trusted/plugin/utility.h"
50 #include "ppapi/native_client/src/trusted/weak_ref/call_on_main_thread.h"
54 class OpenManifestEntryAsyncCallback {
56 OpenManifestEntryAsyncCallback(PP_OpenResourceCompletionCallback callback,
57 void* callback_user_data)
58 : callback_(callback), callback_user_data_(callback_user_data) {
61 ~OpenManifestEntryAsyncCallback() {
63 callback_(callback_user_data_, PP_kInvalidFileHandle);
66 void Run(int32_t pp_error) {
68 // Currently, this is used only for non-SFI mode, and now the mode is not
69 // supported on windows.
70 // TODO(hidehiko): Support it on Windows when we switch to use
71 // ManifestService also in SFI-mode.
73 #elif defined(OS_POSIX)
74 // On posix, PlatformFile is the file descriptor.
75 callback_(callback_user_data_, (pp_error == PP_OK) ? info_.desc : -1);
80 NaClFileInfo* mutable_info() { return &info_; }
84 PP_OpenResourceCompletionCallback callback_;
85 void* callback_user_data_;
86 DISALLOW_COPY_AND_ASSIGN(OpenManifestEntryAsyncCallback);
91 class ManifestService {
93 ManifestService(nacl::WeakRefAnchor* anchor,
94 PluginReverseInterface* plugin_reverse)
96 plugin_reverse_(plugin_reverse) {
108 bool StartupInitializationComplete() {
109 // Release this instance if the ServiceRuntime is already destructed.
110 if (anchor_->is_abandoned()) {
115 plugin_reverse_->StartupInitializationComplete();
119 bool OpenResource(const char* entry_key,
120 PP_OpenResourceCompletionCallback callback,
121 void* callback_user_data) {
122 // Release this instance if the ServiceRuntime is already destructed.
123 if (anchor_->is_abandoned()) {
124 callback(callback_user_data, PP_kInvalidFileHandle);
129 OpenManifestEntryAsyncCallback* open_manifest_callback =
130 new OpenManifestEntryAsyncCallback(callback, callback_user_data);
131 plugin_reverse_->OpenManifestEntryAsync(
133 open_manifest_callback->mutable_info(),
134 open_manifest_callback);
138 static PP_Bool QuitTrampoline(void* user_data) {
139 return PP_FromBool(static_cast<ManifestService*>(user_data)->Quit());
142 static PP_Bool StartupInitializationCompleteTrampoline(void* user_data) {
143 return PP_FromBool(static_cast<ManifestService*>(user_data)->
144 StartupInitializationComplete());
147 static PP_Bool OpenResourceTrampoline(
149 const char* entry_key,
150 PP_OpenResourceCompletionCallback callback,
151 void* callback_user_data) {
152 return PP_FromBool(static_cast<ManifestService*>(user_data)->OpenResource(
153 entry_key, callback, callback_user_data));
157 // Weak reference to check if plugin_reverse is legally accessible or not.
158 nacl::WeakRefAnchor* anchor_;
159 PluginReverseInterface* plugin_reverse_;
161 DISALLOW_COPY_AND_ASSIGN(ManifestService);
164 // Vtable to pass functions to LaunchSelLdr.
165 const PPP_ManifestService kManifestServiceVTable = {
166 &ManifestService::QuitTrampoline,
167 &ManifestService::StartupInitializationCompleteTrampoline,
168 &ManifestService::OpenResourceTrampoline,
173 OpenManifestEntryResource::~OpenManifestEntryResource() {
174 MaybeRunCallback(PP_ERROR_ABORTED);
177 void OpenManifestEntryResource::MaybeRunCallback(int32_t pp_error) {
181 callback->Run(pp_error);
186 PluginReverseInterface::PluginReverseInterface(
187 nacl::WeakRefAnchor* anchor,
189 ServiceRuntime* service_runtime,
190 pp::CompletionCallback init_done_cb,
191 pp::CompletionCallback crash_cb)
194 service_runtime_(service_runtime),
195 shutting_down_(false),
196 init_done_cb_(init_done_cb),
197 crash_cb_(crash_cb) {
198 NaClXMutexCtor(&mu_);
199 NaClXCondVarCtor(&cv_);
202 PluginReverseInterface::~PluginReverseInterface() {
203 NaClCondVarDtor(&cv_);
207 void PluginReverseInterface::ShutDown() {
208 NaClLog(4, "PluginReverseInterface::Shutdown: entered\n");
209 nacl::MutexLocker take(&mu_);
210 shutting_down_ = true;
211 NaClXCondVarBroadcast(&cv_);
212 NaClLog(4, "PluginReverseInterface::Shutdown: broadcasted, exiting\n");
215 void PluginReverseInterface::DoPostMessage(nacl::string message) {
216 std::string full_message = std::string("DEBUG_POSTMESSAGE:") + message;
217 GetNaClInterface()->PostMessageToJavaScript(plugin_->pp_instance(),
218 full_message.c_str());
221 void PluginReverseInterface::StartupInitializationComplete() {
222 NaClLog(4, "PluginReverseInterface::StartupInitializationComplete\n");
223 if (init_done_cb_.pp_completion_callback().func != NULL) {
225 "PluginReverseInterface::StartupInitializationComplete:"
227 pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb_, PP_OK);
230 "PluginReverseInterface::StartupInitializationComplete:"
231 " init_done_cb_ not valid, skipping.\n");
235 // TODO(bsy): OpenManifestEntry should use the manifest to ResolveKey
236 // and invoke StreamAsFile with a completion callback that invokes
238 bool PluginReverseInterface::OpenManifestEntry(nacl::string url_key,
239 struct NaClFileInfo* info) {
240 bool op_complete = false; // NB: mu_ and cv_ also controls access to this!
241 // The to_open object is owned by the weak ref callback. Because this function
242 // waits for the callback to finish, the to_open object will be deallocated on
243 // the main thread before this function can return. The pointers it contains
244 // to stack variables will not leak.
245 OpenManifestEntryResource* to_open =
246 new OpenManifestEntryResource(url_key, info, &op_complete, NULL);
247 CHECK(to_open != NULL);
248 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: %s\n",
250 // This assumes we are not on the main thread. If false, we deadlock.
251 plugin::WeakRefCallOnMainThread(
255 &plugin::PluginReverseInterface::OpenManifestEntry_MainThreadContinuation,
258 "PluginReverseInterface::OpenManifestEntry:"
259 " waiting on main thread\n");
262 nacl::MutexLocker take(&mu_);
263 while (!shutting_down_ && !op_complete)
264 NaClXCondVarWait(&cv_, &mu_);
265 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: done!\n");
266 if (shutting_down_) {
268 "PluginReverseInterface::OpenManifestEntry:"
269 " plugin is shutting down\n");
274 // info->desc has the returned descriptor if successful, else -1.
276 // The caller is responsible for not closing info->desc. If it is
277 // closed prematurely, then another open could re-use the OS
278 // descriptor, confusing the opened_ map. If the caller is going to
279 // want to make a NaClDesc object and transfer it etc., then the
280 // caller should DUP the descriptor (but remember the original
281 // value) for use by the NaClDesc object, which closes when the
282 // object is destroyed.
284 "PluginReverseInterface::OpenManifestEntry: info->desc = %d\n",
286 if (info->desc == -1) {
287 // TODO(bsy,ncbray): what else should we do with the error? This
288 // is a runtime error that may simply be a programming error in
289 // the untrusted code, or it may be something else wrong w/ the
291 NaClLog(4, "OpenManifestEntry: failed for key %s", url_key.c_str());
296 void PluginReverseInterface::OpenManifestEntryAsync(
297 const nacl::string& entry_key,
298 struct NaClFileInfo* info,
299 OpenManifestEntryAsyncCallback* callback) {
300 bool op_complete = false;
301 OpenManifestEntryResource to_open(
302 entry_key, info, &op_complete, callback);
303 OpenManifestEntry_MainThreadContinuation(&to_open, PP_OK);
306 // Transfer point from OpenManifestEntry() which runs on the main thread
307 // (Some PPAPI actions -- like StreamAsFile -- can only run on the main thread).
308 // OpenManifestEntry() is waiting on a condvar for this continuation to
309 // complete. We Broadcast and awaken OpenManifestEntry() whenever we are done
310 // either here, or in a later MainThreadContinuation step, if there are
312 void PluginReverseInterface::OpenManifestEntry_MainThreadContinuation(
313 OpenManifestEntryResource* p,
315 UNREFERENCED_PARAMETER(err);
316 // CallOnMainThread continuations always called with err == PP_OK.
318 NaClLog(4, "Entered OpenManifestEntry_MainThreadContinuation\n");
320 PP_Var pp_mapped_url;
321 PP_PNaClOptions pnacl_options = {PP_FALSE, PP_FALSE, 2};
322 if (!GetNaClInterface()->ManifestResolveKey(
323 plugin_->pp_instance(),
324 PP_FromBool(!service_runtime_->main_service_runtime()),
328 NaClLog(4, "OpenManifestEntry_MainThreadContinuation: ResolveKey failed\n");
329 // Failed, and error_info has the details on what happened. Wake
330 // up requesting thread -- we are done.
332 nacl::MutexLocker take(&mu_);
333 *p->op_complete_ptr = true; // done...
334 p->file_info->desc = -1; // but failed.
335 NaClXCondVarBroadcast(&cv_);
337 p->MaybeRunCallback(PP_OK);
340 nacl::string mapped_url = pp::Var(pp_mapped_url).AsString();
342 "OpenManifestEntry_MainThreadContinuation: "
343 "ResolveKey: %s -> %s (pnacl_translate(%d))\n",
344 p->url.c_str(), mapped_url.c_str(), pnacl_options.translate);
346 if (pnacl_options.translate) {
347 // Requires PNaCl translation, but that's not supported.
349 "OpenManifestEntry_MainThreadContinuation: "
350 "Requires PNaCl translation -- not supported\n");
352 nacl::MutexLocker take(&mu_);
353 *p->op_complete_ptr = true; // done...
354 p->file_info->desc = -1; // but failed.
355 NaClXCondVarBroadcast(&cv_);
357 p->MaybeRunCallback(PP_OK);
361 // Because p is owned by the callback of this invocation, so it is necessary
362 // to create another instance.
363 OpenManifestEntryResource* open_cont = new OpenManifestEntryResource(*p);
364 open_cont->url = mapped_url;
365 // Callback is now delegated from p to open_cont. So, here we manually clear
366 // complete callback.
369 pp::CompletionCallback stream_cc = WeakRefNewCallback(
372 &PluginReverseInterface::StreamAsFile_MainThreadContinuation,
375 GetNaClInterface()->DownloadFile(plugin_->pp_instance(),
377 &open_cont->pp_file_info,
378 stream_cc.pp_completion_callback());
379 // p is deleted automatically.
382 void PluginReverseInterface::StreamAsFile_MainThreadContinuation(
383 OpenManifestEntryResource* p,
385 NaClLog(4, "Entered StreamAsFile_MainThreadContinuation\n");
387 nacl::MutexLocker take(&mu_);
388 if (result == PP_OK) {
389 // We downloaded this file to temporary storage for this plugin; it's
390 // reasonable to provide a file descriptor with write access.
391 p->file_info->desc = ConvertFileDescriptor(p->pp_file_info.handle, false);
392 p->file_info->file_token.lo = p->pp_file_info.token_lo;
393 p->file_info->file_token.hi = p->pp_file_info.token_hi;
395 "StreamAsFile_MainThreadContinuation: PP_OK, desc %d\n",
400 "StreamAsFile_MainThreadContinuation: !PP_OK, setting desc -1\n");
401 p->file_info->desc = -1;
403 *p->op_complete_ptr = true;
404 NaClXCondVarBroadcast(&cv_);
406 p->MaybeRunCallback(PP_OK);
409 bool PluginReverseInterface::CloseManifestEntry(int32_t desc) {
410 // We don't take any action on a call to CloseManifestEntry today, so always
415 void PluginReverseInterface::ReportCrash() {
416 NaClLog(4, "PluginReverseInterface::ReportCrash\n");
418 if (crash_cb_.pp_completion_callback().func != NULL) {
419 NaClLog(4, "PluginReverseInterface::ReportCrash: invoking CB\n");
420 pp::Module::Get()->core()->CallOnMainThread(0, crash_cb_, PP_OK);
421 // Clear the callback to avoid it gets invoked twice.
422 crash_cb_ = pp::CompletionCallback();
425 "PluginReverseInterface::ReportCrash:"
426 " crash_cb_ not valid, skipping\n");
430 void PluginReverseInterface::ReportExitStatus(int exit_status) {
431 service_runtime_->set_exit_status(exit_status);
434 int64_t PluginReverseInterface::RequestQuotaForWrite(
435 nacl::string file_id, int64_t offset, int64_t bytes_to_write) {
436 return bytes_to_write;
439 // Thin wrapper for the arguments of LoadNexeAndStart(), as WeakRefNewCallback
440 // can take only one argument. Also, this dtor has the responsibility to invoke
441 // callbacks on destruction.
442 struct ServiceRuntime::LoadNexeAndStartData {
443 explicit LoadNexeAndStartData(const pp::CompletionCallback& callback)
444 : callback(callback) {
447 ~LoadNexeAndStartData() {
448 // We must call the callbacks here if they are not yet called, otherwise
449 // the resource would be leaked.
450 if (callback.pp_completion_callback().func)
451 callback.RunAndClear(PP_ERROR_ABORTED);
454 // On success path, this must be invoked manually. Otherwise the dtor would
455 // invoke callbacks with error code unexpectedly.
457 callback = pp::CompletionCallback();
460 pp::CompletionCallback callback;
463 ServiceRuntime::ServiceRuntime(Plugin* plugin,
464 bool main_service_runtime,
465 bool uses_nonsfi_mode,
466 pp::CompletionCallback init_done_cb,
467 pp::CompletionCallback crash_cb)
469 main_service_runtime_(main_service_runtime),
470 uses_nonsfi_mode_(uses_nonsfi_mode),
471 reverse_service_(NULL),
472 anchor_(new nacl::WeakRefAnchor()),
473 rev_interface_(new PluginReverseInterface(anchor_, plugin, this,
474 init_done_cb, crash_cb)),
475 start_sel_ldr_done_(false),
476 nexe_started_(false) {
477 NaClSrpcChannelInitialize(&command_channel_);
478 NaClXMutexCtor(&mu_);
479 NaClXCondVarCtor(&cond_);
482 void ServiceRuntime::LoadNexeAndStartAfterLoadModule(
483 LoadNexeAndStartData* data, int32_t pp_error) {
484 if (pp_error != PP_OK) {
485 DidLoadNexeAndStart(data, pp_error);
489 // Here, LoadModule is successfully done. So the remaining task is just
490 // calling StartModule(), here.
491 DidLoadNexeAndStart(data, StartModule() ? PP_OK : PP_ERROR_FAILED);
494 void ServiceRuntime::DidLoadNexeAndStart(
495 LoadNexeAndStartData* data, int32_t pp_error) {
496 if (pp_error == PP_OK) {
497 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (success)\n");
499 // On a load failure the service runtime does not crash itself to
500 // avoid a race where the no-more-senders error on the reverse
501 // channel esrvice thread might cause the crash-detection logic to
502 // kick in before the start_module RPC reply has been received. So
503 // we induce a service runtime crash here. We do not release
504 // subprocess_ since it's needed to collect crash log output after
505 // the error is reported.
506 Log(LOG_FATAL, "reap logs");
507 if (NULL == reverse_service_) {
508 // No crash detector thread.
509 NaClLog(LOG_ERROR, "scheduling to get crash log\n");
510 // Invoking rev_interface's method is workaround to avoid crash_cb
511 // gets called twice or more. We should clean this up later.
512 rev_interface_->ReportCrash();
513 NaClLog(LOG_ERROR, "should fire soon\n");
515 NaClLog(LOG_ERROR, "Reverse service thread will pick up crash log\n");
519 pp::Module::Get()->core()->CallOnMainThread(0, data->callback, pp_error);
521 // Because the ownership of data is taken by caller, we must clear it
522 // manually here. Otherwise, its dtor invokes callbacks again.
526 bool ServiceRuntime::SetupCommandChannel() {
527 NaClLog(4, "ServiceRuntime::SetupCommand (this=%p, subprocess=%p)\n",
528 static_cast<void*>(this),
529 static_cast<void*>(subprocess_.get()));
530 if (!subprocess_->SetupCommand(&command_channel_)) {
531 if (main_service_runtime_) {
532 ErrorInfo error_info;
533 error_info.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
534 "ServiceRuntime: command channel creation failed");
535 plugin_->ReportLoadError(error_info);
542 void ServiceRuntime::LoadModule(PP_NaClFileInfo file_info,
543 pp::CompletionCallback callback) {
544 NaClFileInfo nacl_file_info;
545 nacl_file_info.desc = ConvertFileDescriptor(file_info.handle, true);
546 nacl_file_info.file_token.lo = file_info.token_lo;
547 nacl_file_info.file_token.hi = file_info.token_hi;
548 NaClDesc* desc = NaClDescIoFromFileInfo(nacl_file_info, O_RDONLY);
550 DidLoadModule(callback, PP_ERROR_FAILED);
554 // We don't use a scoped_ptr here since we would immediately release the
555 // DescWrapper to LoadModule().
556 nacl::DescWrapper* wrapper =
557 plugin_->wrapper_factory()->MakeGenericCleanup(desc);
559 // TODO(teravest, hidehiko): Replace this by Chrome IPC.
560 bool result = subprocess_->LoadModule(&command_channel_, wrapper);
561 DidLoadModule(callback, result ? PP_OK : PP_ERROR_FAILED);
564 void ServiceRuntime::DidLoadModule(pp::CompletionCallback callback,
566 if (pp_error != PP_OK) {
567 ErrorInfo error_info;
568 error_info.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
569 "ServiceRuntime: load module failed");
570 plugin_->ReportLoadError(error_info);
572 callback.Run(pp_error);
575 bool ServiceRuntime::InitReverseService() {
576 if (uses_nonsfi_mode_) {
577 // In non-SFI mode, no reverse service is set up. Just returns success.
581 // Hook up the reverse service channel. We are the IMC client, but
582 // provide SRPC service.
583 NaClDesc* out_conn_cap;
584 NaClSrpcResultCodes rpc_result =
585 NaClSrpcInvokeBySignature(&command_channel_,
589 if (NACL_SRPC_RESULT_OK != rpc_result) {
590 if (main_service_runtime_) {
591 ErrorInfo error_info;
592 error_info.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SETUP,
593 "ServiceRuntime: reverse setup rpc failed");
594 plugin_->ReportLoadError(error_info);
598 // Get connection capability to service runtime where the IMC
599 // server/SRPC client is waiting for a rendezvous.
600 NaClLog(4, "ServiceRuntime: got 0x%" NACL_PRIxPTR "\n",
601 (uintptr_t) out_conn_cap);
602 nacl::DescWrapper* conn_cap = plugin_->wrapper_factory()->MakeGenericCleanup(
604 if (conn_cap == NULL) {
605 if (main_service_runtime_) {
606 ErrorInfo error_info;
607 error_info.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_WRAPPER,
608 "ServiceRuntime: wrapper allocation failure");
609 plugin_->ReportLoadError(error_info);
613 out_conn_cap = NULL; // ownership passed
614 NaClLog(4, "ServiceRuntime::InitReverseService: starting reverse service\n");
615 reverse_service_ = new nacl::ReverseService(conn_cap, rev_interface_->Ref());
616 if (!reverse_service_->Start()) {
617 if (main_service_runtime_) {
618 ErrorInfo error_info;
619 error_info.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SERVICE,
620 "ServiceRuntime: starting reverse services failed");
621 plugin_->ReportLoadError(error_info);
628 bool ServiceRuntime::StartModule() {
629 // start the module. otherwise we cannot connect for multimedia
630 // subsystem since that is handled by user-level code (not secure!)
632 int load_status = -1;
633 if (uses_nonsfi_mode_) {
634 // In non-SFI mode, we don't need to call start_module SRPC to launch
636 load_status = LOAD_OK;
638 NaClSrpcResultCodes rpc_result =
639 NaClSrpcInvokeBySignature(&command_channel_,
643 if (NACL_SRPC_RESULT_OK != rpc_result) {
644 if (main_service_runtime_) {
645 ErrorInfo error_info;
646 error_info.SetReport(PP_NACL_ERROR_SEL_LDR_START_MODULE,
647 "ServiceRuntime: could not start nacl module");
648 plugin_->ReportLoadError(error_info);
654 NaClLog(4, "ServiceRuntime::StartModule (load_status=%d)\n", load_status);
655 if (main_service_runtime_) {
656 if (load_status < 0 || load_status > NACL_ERROR_CODE_MAX)
657 load_status = LOAD_STATUS_UNKNOWN;
658 GetNaClInterface()->ReportSelLdrStatus(plugin_->pp_instance(),
660 NACL_ERROR_CODE_MAX);
663 if (LOAD_OK != load_status) {
664 if (main_service_runtime_) {
665 ErrorInfo error_info;
666 error_info.SetReport(
667 PP_NACL_ERROR_SEL_LDR_START_STATUS,
668 NaClErrorString(static_cast<NaClErrorCode>(load_status)));
669 plugin_->ReportLoadError(error_info);
676 void ServiceRuntime::StartSelLdr(const SelLdrStartParams& params,
677 pp::CompletionCallback callback) {
678 NaClLog(4, "ServiceRuntime::Start\n");
680 nacl::scoped_ptr<SelLdrLauncherChrome>
681 tmp_subprocess(new SelLdrLauncherChrome());
682 if (NULL == tmp_subprocess.get()) {
683 NaClLog(LOG_ERROR, "ServiceRuntime::Start (subprocess create failed)\n");
684 if (main_service_runtime_) {
685 ErrorInfo error_info;
686 error_info.SetReport(
687 PP_NACL_ERROR_SEL_LDR_CREATE_LAUNCHER,
688 "ServiceRuntime: failed to create sel_ldr launcher");
689 plugin_->ReportLoadError(error_info);
691 pp::Module::Get()->core()->CallOnMainThread(0, callback, PP_ERROR_FAILED);
695 ManifestService* manifest_service =
696 new ManifestService(anchor_->Ref(), rev_interface_);
697 bool enable_dev_interfaces =
698 GetNaClInterface()->DevInterfacesEnabled(plugin_->pp_instance());
700 tmp_subprocess->Start(plugin_->pp_instance(),
701 main_service_runtime_,
706 enable_dev_interfaces,
707 params.enable_dyncode_syscalls,
708 params.enable_exception_handling,
709 params.enable_crash_throttling,
710 &kManifestServiceVTable,
713 subprocess_.reset(tmp_subprocess.release());
716 bool ServiceRuntime::WaitForSelLdrStart() {
717 // Time to wait on condvar (for browser to create a new sel_ldr process on
718 // our behalf). Use 6 seconds to be *fairly* conservative.
720 // On surfaway, the CallOnMainThread above may never get scheduled
721 // to unblock this condvar, or the IPC reply from the browser to renderer
722 // might get canceled/dropped. However, it is currently important to
723 // avoid waiting indefinitely because ~PnaclCoordinator will attempt to
724 // join() the PnaclTranslateThread, and the PnaclTranslateThread is waiting
725 // for the signal before exiting.
726 static int64_t const kWaitTimeMicrosecs = 6 * NACL_MICROS_PER_UNIT;
727 int64_t left_to_wait = kWaitTimeMicrosecs;
728 int64_t deadline = NaClGetTimeOfDayMicroseconds() + left_to_wait;
729 nacl::MutexLocker take(&mu_);
730 while(!start_sel_ldr_done_ && left_to_wait > 0) {
731 struct nacl_abi_timespec left_timespec;
732 left_timespec.tv_sec = left_to_wait / NACL_MICROS_PER_UNIT;
733 left_timespec.tv_nsec =
734 (left_to_wait % NACL_MICROS_PER_UNIT) * NACL_NANOS_PER_MICRO;
735 NaClXCondVarTimedWaitRelative(&cond_, &mu_, &left_timespec);
736 int64_t now = NaClGetTimeOfDayMicroseconds();
737 left_to_wait = deadline - now;
739 return start_sel_ldr_done_;
742 void ServiceRuntime::SignalStartSelLdrDone() {
743 nacl::MutexLocker take(&mu_);
744 start_sel_ldr_done_ = true;
745 NaClXCondVarSignal(&cond_);
748 void ServiceRuntime::WaitForNexeStart() {
749 nacl::MutexLocker take(&mu_);
750 while (!nexe_started_)
751 NaClXCondVarWait(&cond_, &mu_);
752 // Reset nexe_started_ here in case we run again.
753 nexe_started_ = false;
756 void ServiceRuntime::SignalNexeStarted() {
757 nacl::MutexLocker take(&mu_);
758 nexe_started_ = true;
759 NaClXCondVarSignal(&cond_);
762 void ServiceRuntime::LoadNexeAndStart(PP_NaClFileInfo file_info,
763 const pp::CompletionCallback& callback) {
764 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (handle_valid=%d "
765 "token_lo=%" NACL_PRIu64 " token_hi=%" NACL_PRIu64 ")\n",
766 file_info.handle != PP_kInvalidFileHandle,
770 nacl::scoped_ptr<LoadNexeAndStartData> data(
771 new LoadNexeAndStartData(callback));
772 if (!SetupCommandChannel() || !InitReverseService()) {
773 DidLoadNexeAndStart(data.get(), PP_ERROR_FAILED);
779 WeakRefNewCallback(anchor_,
781 &ServiceRuntime::LoadNexeAndStartAfterLoadModule,
782 data.release())); // Delegate the ownership.
785 SrpcClient* ServiceRuntime::SetupAppChannel() {
786 NaClLog(4, "ServiceRuntime::SetupAppChannel (subprocess_=%p)\n",
787 reinterpret_cast<void*>(subprocess_.get()));
788 nacl::DescWrapper* connect_desc = subprocess_->socket_addr()->Connect();
789 if (NULL == connect_desc) {
790 NaClLog(LOG_ERROR, "ServiceRuntime::SetupAppChannel (connect failed)\n");
793 NaClLog(4, "ServiceRuntime::SetupAppChannel (conect_desc=%p)\n",
794 static_cast<void*>(connect_desc));
795 SrpcClient* srpc_client = SrpcClient::New(connect_desc);
796 NaClLog(4, "ServiceRuntime::SetupAppChannel (srpc_client=%p)\n",
797 static_cast<void*>(srpc_client));
803 bool ServiceRuntime::Log(int severity, const nacl::string& msg) {
804 NaClSrpcResultCodes rpc_result =
805 NaClSrpcInvokeBySignature(&command_channel_,
808 strdup(msg.c_str()));
809 return (NACL_SRPC_RESULT_OK == rpc_result);
812 void ServiceRuntime::Shutdown() {
813 rev_interface_->ShutDown();
815 // Abandon callbacks, tell service threads to quit if they were
816 // blocked waiting for main thread operations to finish. Note that
817 // some callbacks must still await their completion event, e.g.,
818 // CallOnMainThread must still wait for the time out, or I/O events
819 // must finish, so resources associated with pending events cannot
822 // Note that this does waitpid() to get rid of any zombie subprocess.
823 subprocess_.reset(NULL);
825 NaClSrpcDtor(&command_channel_);
827 // subprocess_ has been shut down, but threads waiting on messages
828 // from the service runtime may not have noticed yet. The low-level
829 // NaClSimpleRevService code takes care to refcount the data objects
830 // that it needs, and reverse_service_ is also refcounted. We wait
831 // for the service threads to get their EOF indications.
832 if (reverse_service_ != NULL) {
833 reverse_service_->WaitForServiceThreadsToExit();
834 reverse_service_->Unref();
835 reverse_service_ = NULL;
839 ServiceRuntime::~ServiceRuntime() {
840 NaClLog(4, "ServiceRuntime::~ServiceRuntime (this=%p)\n",
841 static_cast<void*>(this));
842 // We do this just in case Shutdown() was not called.
843 subprocess_.reset(NULL);
844 if (reverse_service_ != NULL)
845 reverse_service_->Unref();
847 rev_interface_->Unref();
850 NaClCondVarDtor(&cond_);
854 void ServiceRuntime::set_exit_status(int exit_status) {
855 nacl::MutexLocker take(&mu_);
856 if (main_service_runtime_)
857 plugin_->set_exit_status(exit_status & 0xff);
860 nacl::string ServiceRuntime::GetCrashLogOutput() {
861 if (NULL != subprocess_.get()) {
862 return subprocess_->GetCrashLogOutput();
864 return std::string();
868 } // namespace plugin