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 OpenManifestEntryResource::~OpenManifestEntryResource() {
57 PluginReverseInterface::PluginReverseInterface(
58 nacl::WeakRefAnchor
* anchor
,
59 PP_Instance pp_instance
,
60 ServiceRuntime
* service_runtime
,
61 pp::CompletionCallback init_done_cb
,
62 pp::CompletionCallback crash_cb
)
64 pp_instance_(pp_instance
),
65 service_runtime_(service_runtime
),
66 shutting_down_(false),
67 init_done_cb_(init_done_cb
),
70 NaClXCondVarCtor(&cv_
);
73 PluginReverseInterface::~PluginReverseInterface() {
74 NaClCondVarDtor(&cv_
);
78 void PluginReverseInterface::ShutDown() {
79 NaClLog(4, "PluginReverseInterface::Shutdown: entered\n");
80 nacl::MutexLocker
take(&mu_
);
81 shutting_down_
= true;
82 NaClXCondVarBroadcast(&cv_
);
83 NaClLog(4, "PluginReverseInterface::Shutdown: broadcasted, exiting\n");
86 void PluginReverseInterface::DoPostMessage(nacl::string message
) {
87 std::string full_message
= std::string("DEBUG_POSTMESSAGE:") + message
;
88 GetNaClInterface()->PostMessageToJavaScript(pp_instance_
,
89 full_message
.c_str());
92 void PluginReverseInterface::StartupInitializationComplete() {
93 NaClLog(4, "PluginReverseInterface::StartupInitializationComplete\n");
94 if (init_done_cb_
.pp_completion_callback().func
!= NULL
) {
96 "PluginReverseInterface::StartupInitializationComplete:"
98 pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb_
, PP_OK
);
101 "PluginReverseInterface::StartupInitializationComplete:"
102 " init_done_cb_ not valid, skipping.\n");
106 // TODO(bsy): OpenManifestEntry should use the manifest to ResolveKey
107 // and invoke StreamAsFile with a completion callback that invokes
109 bool PluginReverseInterface::OpenManifestEntry(nacl::string url_key
,
110 struct NaClFileInfo
* info
) {
111 bool op_complete
= false; // NB: mu_ and cv_ also controls access to this!
112 // The to_open object is owned by the weak ref callback. Because this function
113 // waits for the callback to finish, the to_open object will be deallocated on
114 // the main thread before this function can return. The pointers it contains
115 // to stack variables will not leak.
116 OpenManifestEntryResource
* to_open
=
117 new OpenManifestEntryResource(url_key
, info
, &op_complete
);
118 CHECK(to_open
!= NULL
);
119 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: %s\n",
121 // This assumes we are not on the main thread. If false, we deadlock.
122 plugin::WeakRefCallOnMainThread(
126 &plugin::PluginReverseInterface::OpenManifestEntry_MainThreadContinuation
,
129 "PluginReverseInterface::OpenManifestEntry:"
130 " waiting on main thread\n");
133 nacl::MutexLocker
take(&mu_
);
134 while (!shutting_down_
&& !op_complete
)
135 NaClXCondVarWait(&cv_
, &mu_
);
136 NaClLog(4, "PluginReverseInterface::OpenManifestEntry: done!\n");
137 if (shutting_down_
) {
139 "PluginReverseInterface::OpenManifestEntry:"
140 " plugin is shutting down\n");
145 // info->desc has the returned descriptor if successful, else -1.
147 // The caller is responsible for not closing info->desc. If it is
148 // closed prematurely, then another open could re-use the OS
149 // descriptor, confusing the opened_ map. If the caller is going to
150 // want to make a NaClDesc object and transfer it etc., then the
151 // caller should DUP the descriptor (but remember the original
152 // value) for use by the NaClDesc object, which closes when the
153 // object is destroyed.
155 "PluginReverseInterface::OpenManifestEntry: info->desc = %d\n",
157 if (info
->desc
== -1) {
158 // TODO(bsy,ncbray): what else should we do with the error? This
159 // is a runtime error that may simply be a programming error in
160 // the untrusted code, or it may be something else wrong w/ the
162 NaClLog(4, "OpenManifestEntry: failed for key %s", url_key
.c_str());
167 // Transfer point from OpenManifestEntry() which runs on the main thread
168 // (Some PPAPI actions -- like StreamAsFile -- can only run on the main thread).
169 // OpenManifestEntry() is waiting on a condvar for this continuation to
170 // complete. We Broadcast and awaken OpenManifestEntry() whenever we are done
171 // either here, or in a later MainThreadContinuation step, if there are
173 void PluginReverseInterface::OpenManifestEntry_MainThreadContinuation(
174 OpenManifestEntryResource
* p
,
176 UNREFERENCED_PARAMETER(err
);
177 // CallOnMainThread continuations always called with err == PP_OK.
179 NaClLog(4, "Entered OpenManifestEntry_MainThreadContinuation\n");
181 // Because p is owned by the callback of this invocation, so it is necessary
182 // to create another instance.
183 OpenManifestEntryResource
* open_cont
= new OpenManifestEntryResource(*p
);
184 pp::CompletionCallback stream_cc
= WeakRefNewCallback(
187 &PluginReverseInterface::StreamAsFile_MainThreadContinuation
,
190 GetNaClInterface()->OpenManifestEntry(
192 PP_FromBool(!service_runtime_
->main_service_runtime()),
194 &open_cont
->pp_file_info
,
195 stream_cc
.pp_completion_callback());
196 // p is deleted automatically.
199 void PluginReverseInterface::StreamAsFile_MainThreadContinuation(
200 OpenManifestEntryResource
* p
,
202 NaClLog(4, "Entered StreamAsFile_MainThreadContinuation\n");
204 nacl::MutexLocker
take(&mu_
);
205 if (result
== PP_OK
) {
206 // We downloaded this file to temporary storage for this plugin; it's
207 // reasonable to provide a file descriptor with write access.
208 p
->file_info
->desc
= ConvertFileDescriptor(p
->pp_file_info
.handle
, false);
209 p
->file_info
->file_token
.lo
= p
->pp_file_info
.token_lo
;
210 p
->file_info
->file_token
.hi
= p
->pp_file_info
.token_hi
;
212 "StreamAsFile_MainThreadContinuation: PP_OK, desc %d\n",
217 "StreamAsFile_MainThreadContinuation: !PP_OK, setting desc -1\n");
218 p
->file_info
->desc
= -1;
220 *p
->op_complete_ptr
= true;
221 NaClXCondVarBroadcast(&cv_
);
225 void PluginReverseInterface::ReportCrash() {
226 NaClLog(4, "PluginReverseInterface::ReportCrash\n");
228 if (crash_cb_
.pp_completion_callback().func
!= NULL
) {
229 NaClLog(4, "PluginReverseInterface::ReportCrash: invoking CB\n");
230 pp::Module::Get()->core()->CallOnMainThread(0, crash_cb_
, PP_OK
);
231 // Clear the callback to avoid it gets invoked twice.
232 crash_cb_
= pp::CompletionCallback();
235 "PluginReverseInterface::ReportCrash:"
236 " crash_cb_ not valid, skipping\n");
240 void PluginReverseInterface::ReportExitStatus(int exit_status
) {
241 // We do nothing here; reporting exit status is handled through a separate
242 // embedder interface.
245 int64_t PluginReverseInterface::RequestQuotaForWrite(
246 nacl::string file_id
, int64_t offset
, int64_t bytes_to_write
) {
247 return bytes_to_write
;
250 ServiceRuntime::ServiceRuntime(Plugin
* plugin
,
251 PP_Instance pp_instance
,
252 bool main_service_runtime
,
253 bool uses_nonsfi_mode
,
254 pp::CompletionCallback init_done_cb
,
255 pp::CompletionCallback crash_cb
)
257 pp_instance_(pp_instance
),
258 main_service_runtime_(main_service_runtime
),
259 uses_nonsfi_mode_(uses_nonsfi_mode
),
260 reverse_service_(NULL
),
261 anchor_(new nacl::WeakRefAnchor()),
262 rev_interface_(new PluginReverseInterface(anchor_
, pp_instance
, this,
263 init_done_cb
, crash_cb
)),
264 start_sel_ldr_done_(false),
265 start_nexe_done_(false),
266 nexe_started_ok_(false),
267 bootstrap_channel_(NACL_INVALID_HANDLE
) {
268 NaClSrpcChannelInitialize(&command_channel_
);
269 NaClXMutexCtor(&mu_
);
270 NaClXCondVarCtor(&cond_
);
273 bool ServiceRuntime::SetupCommandChannel() {
274 NaClLog(4, "ServiceRuntime::SetupCommand (this=%p, subprocess=%p)\n",
275 static_cast<void*>(this),
276 static_cast<void*>(subprocess_
.get()));
277 // Set up the bootstrap channel in our subprocess so that we can establish
279 subprocess_
->set_channel(bootstrap_channel_
);
281 if (uses_nonsfi_mode_
) {
282 // In non-SFI mode, no SRPC is used. Just skips and returns success.
286 if (!subprocess_
->SetupCommand(&command_channel_
)) {
287 ErrorInfo error_info
;
288 error_info
.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL
,
289 "ServiceRuntime: command channel creation failed");
290 ReportLoadError(error_info
);
296 bool ServiceRuntime::InitReverseService() {
297 if (uses_nonsfi_mode_
) {
298 // In non-SFI mode, no reverse service is set up. Just returns success.
302 // Hook up the reverse service channel. We are the IMC client, but
303 // provide SRPC service.
304 NaClDesc
* out_conn_cap
;
305 NaClSrpcResultCodes rpc_result
=
306 NaClSrpcInvokeBySignature(&command_channel_
,
310 if (NACL_SRPC_RESULT_OK
!= rpc_result
) {
311 ErrorInfo error_info
;
312 error_info
.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SETUP
,
313 "ServiceRuntime: reverse setup rpc failed");
314 ReportLoadError(error_info
);
317 // Get connection capability to service runtime where the IMC
318 // server/SRPC client is waiting for a rendezvous.
319 NaClLog(4, "ServiceRuntime: got 0x%" NACL_PRIxPTR
"\n",
320 (uintptr_t) out_conn_cap
);
321 nacl::DescWrapper
* conn_cap
= plugin_
->wrapper_factory()->MakeGenericCleanup(
323 if (conn_cap
== NULL
) {
324 ErrorInfo error_info
;
325 error_info
.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_WRAPPER
,
326 "ServiceRuntime: wrapper allocation failure");
327 ReportLoadError(error_info
);
330 out_conn_cap
= NULL
; // ownership passed
331 NaClLog(4, "ServiceRuntime::InitReverseService: starting reverse service\n");
332 reverse_service_
= new nacl::ReverseService(conn_cap
, rev_interface_
->Ref());
333 if (!reverse_service_
->Start()) {
334 ErrorInfo error_info
;
335 error_info
.SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SERVICE
,
336 "ServiceRuntime: starting reverse services failed");
337 ReportLoadError(error_info
);
343 bool ServiceRuntime::StartModule() {
344 // start the module. otherwise we cannot connect for multimedia
345 // subsystem since that is handled by user-level code (not secure!)
347 int load_status
= -1;
348 if (uses_nonsfi_mode_
) {
349 // In non-SFI mode, we don't need to call start_module SRPC to launch
351 load_status
= LOAD_OK
;
353 NaClSrpcResultCodes rpc_result
=
354 NaClSrpcInvokeBySignature(&command_channel_
,
358 if (NACL_SRPC_RESULT_OK
!= rpc_result
) {
359 ErrorInfo error_info
;
360 error_info
.SetReport(PP_NACL_ERROR_SEL_LDR_START_MODULE
,
361 "ServiceRuntime: could not start nacl module");
362 ReportLoadError(error_info
);
367 NaClLog(4, "ServiceRuntime::StartModule (load_status=%d)\n", load_status
);
368 if (main_service_runtime_
) {
369 if (load_status
< 0 || load_status
> NACL_ERROR_CODE_MAX
)
370 load_status
= LOAD_STATUS_UNKNOWN
;
371 GetNaClInterface()->ReportSelLdrStatus(pp_instance_
,
373 NACL_ERROR_CODE_MAX
);
376 if (LOAD_OK
!= load_status
) {
377 ErrorInfo error_info
;
378 error_info
.SetReport(
379 PP_NACL_ERROR_SEL_LDR_START_STATUS
,
380 NaClErrorString(static_cast<NaClErrorCode
>(load_status
)));
381 ReportLoadError(error_info
);
387 void ServiceRuntime::StartSelLdr(const SelLdrStartParams
& params
,
388 pp::CompletionCallback callback
) {
389 NaClLog(4, "ServiceRuntime::Start\n");
391 nacl::scoped_ptr
<SelLdrLauncherChrome
>
392 tmp_subprocess(new SelLdrLauncherChrome());
393 if (NULL
== tmp_subprocess
.get()) {
394 NaClLog(LOG_ERROR
, "ServiceRuntime::Start (subprocess create failed)\n");
395 ErrorInfo error_info
;
396 error_info
.SetReport(
397 PP_NACL_ERROR_SEL_LDR_CREATE_LAUNCHER
,
398 "ServiceRuntime: failed to create sel_ldr launcher");
399 ReportLoadError(error_info
);
400 pp::Module::Get()->core()->CallOnMainThread(0, callback
, PP_ERROR_FAILED
);
404 bool enable_dev_interfaces
=
405 GetNaClInterface()->DevInterfacesEnabled(pp_instance_
);
407 GetNaClInterface()->LaunchSelLdr(
409 PP_FromBool(main_service_runtime_
),
412 PP_FromBool(params
.uses_irt
),
413 PP_FromBool(params
.uses_ppapi
),
414 PP_FromBool(uses_nonsfi_mode_
),
415 PP_FromBool(enable_dev_interfaces
),
416 PP_FromBool(params
.enable_dyncode_syscalls
),
417 PP_FromBool(params
.enable_exception_handling
),
418 PP_FromBool(params
.enable_crash_throttling
),
420 callback
.pp_completion_callback());
421 subprocess_
.reset(tmp_subprocess
.release());
424 bool ServiceRuntime::WaitForSelLdrStart() {
425 // Time to wait on condvar (for browser to create a new sel_ldr process on
426 // our behalf). Use 6 seconds to be *fairly* conservative.
428 // On surfaway, the CallOnMainThread above may never get scheduled
429 // to unblock this condvar, or the IPC reply from the browser to renderer
430 // might get canceled/dropped. However, it is currently important to
431 // avoid waiting indefinitely because ~PnaclCoordinator will attempt to
432 // join() the PnaclTranslateThread, and the PnaclTranslateThread is waiting
433 // for the signal before exiting.
434 static int64_t const kWaitTimeMicrosecs
= 6 * NACL_MICROS_PER_UNIT
;
435 int64_t left_to_wait
= kWaitTimeMicrosecs
;
436 int64_t deadline
= NaClGetTimeOfDayMicroseconds() + left_to_wait
;
437 nacl::MutexLocker
take(&mu_
);
438 while(!start_sel_ldr_done_
&& left_to_wait
> 0) {
439 struct nacl_abi_timespec left_timespec
;
440 left_timespec
.tv_sec
= left_to_wait
/ NACL_MICROS_PER_UNIT
;
441 left_timespec
.tv_nsec
=
442 (left_to_wait
% NACL_MICROS_PER_UNIT
) * NACL_NANOS_PER_MICRO
;
443 NaClXCondVarTimedWaitRelative(&cond_
, &mu_
, &left_timespec
);
444 int64_t now
= NaClGetTimeOfDayMicroseconds();
445 left_to_wait
= deadline
- now
;
447 return start_sel_ldr_done_
;
450 void ServiceRuntime::SignalStartSelLdrDone() {
451 nacl::MutexLocker
take(&mu_
);
452 start_sel_ldr_done_
= true;
453 NaClXCondVarSignal(&cond_
);
456 bool ServiceRuntime::WaitForNexeStart() {
457 nacl::MutexLocker
take(&mu_
);
458 while (!start_nexe_done_
)
459 NaClXCondVarWait(&cond_
, &mu_
);
460 return nexe_started_ok_
;
463 void ServiceRuntime::SignalNexeStarted(bool ok
) {
464 nacl::MutexLocker
take(&mu_
);
465 start_nexe_done_
= true;
466 nexe_started_ok_
= ok
;
467 NaClXCondVarSignal(&cond_
);
470 void ServiceRuntime::StartNexe() {
471 bool ok
= StartNexeInternal();
473 NaClLog(4, "ServiceRuntime::StartNexe (success)\n");
477 // This only matters if a background thread is waiting, but we signal in all
478 // cases to simplify the code.
479 SignalNexeStarted(ok
);
482 bool ServiceRuntime::StartNexeInternal() {
483 if (!SetupCommandChannel())
485 if (!InitReverseService())
487 return StartModule();
490 void ServiceRuntime::ReapLogs() {
491 // On a load failure the service runtime does not crash itself to
492 // avoid a race where the no-more-senders error on the reverse
493 // channel service thread might cause the crash-detection logic to
494 // kick in before the start_module RPC reply has been received. So
495 // we induce a service runtime crash here. We do not release
496 // subprocess_ since it's needed to collect crash log output after
497 // the error is reported.
498 RemoteLog(LOG_FATAL
, "reap logs\n");
499 if (NULL
== reverse_service_
) {
500 // No crash detector thread.
501 NaClLog(LOG_ERROR
, "scheduling to get crash log\n");
502 // Invoking rev_interface's method is workaround to avoid crash_cb
503 // gets called twice or more. We should clean this up later.
504 rev_interface_
->ReportCrash();
505 NaClLog(LOG_ERROR
, "should fire soon\n");
507 NaClLog(LOG_ERROR
, "Reverse service thread will pick up crash log\n");
511 void ServiceRuntime::ReportLoadError(const ErrorInfo
& error_info
) {
512 if (main_service_runtime_
) {
513 plugin_
->ReportLoadError(error_info
);
517 SrpcClient
* ServiceRuntime::SetupAppChannel() {
518 NaClLog(4, "ServiceRuntime::SetupAppChannel (subprocess_=%p)\n",
519 reinterpret_cast<void*>(subprocess_
.get()));
520 nacl::DescWrapper
* connect_desc
= subprocess_
->socket_addr()->Connect();
521 if (NULL
== connect_desc
) {
522 NaClLog(LOG_ERROR
, "ServiceRuntime::SetupAppChannel (connect failed)\n");
525 NaClLog(4, "ServiceRuntime::SetupAppChannel (conect_desc=%p)\n",
526 static_cast<void*>(connect_desc
));
527 SrpcClient
* srpc_client
= SrpcClient::New(connect_desc
);
528 NaClLog(4, "ServiceRuntime::SetupAppChannel (srpc_client=%p)\n",
529 static_cast<void*>(srpc_client
));
535 bool ServiceRuntime::RemoteLog(int severity
, const nacl::string
& msg
) {
536 NaClSrpcResultCodes rpc_result
=
537 NaClSrpcInvokeBySignature(&command_channel_
,
540 strdup(msg
.c_str()));
541 return (NACL_SRPC_RESULT_OK
== rpc_result
);
544 void ServiceRuntime::Shutdown() {
545 rev_interface_
->ShutDown();
547 // Abandon callbacks, tell service threads to quit if they were
548 // blocked waiting for main thread operations to finish. Note that
549 // some callbacks must still await their completion event, e.g.,
550 // CallOnMainThread must still wait for the time out, or I/O events
551 // must finish, so resources associated with pending events cannot
554 // Note that this does waitpid() to get rid of any zombie subprocess.
555 subprocess_
.reset(NULL
);
557 NaClSrpcDtor(&command_channel_
);
559 // subprocess_ has been shut down, but threads waiting on messages
560 // from the service runtime may not have noticed yet. The low-level
561 // NaClSimpleRevService code takes care to refcount the data objects
562 // that it needs, and reverse_service_ is also refcounted. We wait
563 // for the service threads to get their EOF indications.
564 if (reverse_service_
!= NULL
) {
565 reverse_service_
->WaitForServiceThreadsToExit();
566 reverse_service_
->Unref();
567 reverse_service_
= NULL
;
571 ServiceRuntime::~ServiceRuntime() {
572 NaClLog(4, "ServiceRuntime::~ServiceRuntime (this=%p)\n",
573 static_cast<void*>(this));
574 // We do this just in case Shutdown() was not called.
575 subprocess_
.reset(NULL
);
576 if (reverse_service_
!= NULL
)
577 reverse_service_
->Unref();
579 rev_interface_
->Unref();
582 NaClCondVarDtor(&cond_
);
586 } // namespace plugin