1 /*
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.
5 */
6
7 #define NACL_LOG_MODULE_NAME "Plugin_ServiceRuntime"
8
9 #include "ppapi/native_client/src/trusted/plugin/service_runtime.h"
10
11 #include <string.h>
12 #include <set>
13 #include <string>
14 #include <utility>
15
16 #include "base/compiler_specific.h"
17
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"
35
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"
39
40 #include "ppapi/c/pp_errors.h"
41 #include "ppapi/cpp/core.h"
42 #include "ppapi/cpp/completion_callback.h"
43
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"
51
52 namespace plugin {
53
54 class OpenManifestEntryAsyncCallback {
55 public:
OpenManifestEntryAsyncCallback(PP_OpenResourceCompletionCallback callback,void * callback_user_data)56 OpenManifestEntryAsyncCallback(PP_OpenResourceCompletionCallback callback,
57 void* callback_user_data)
58 : callback_(callback), callback_user_data_(callback_user_data) {
59 }
60
~OpenManifestEntryAsyncCallback()61 ~OpenManifestEntryAsyncCallback() {
62 if (callback_)
63 callback_(callback_user_data_, PP_kInvalidFileHandle);
64 }
65
Run(int32_t pp_error)66 void Run(int32_t pp_error) {
67 #if defined(OS_WIN)
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.
72 NACL_NOTREACHED();
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);
76 callback_ = NULL;
77 #endif
78 }
79
mutable_info()80 NaClFileInfo* mutable_info() { return &info_; }
81
82 private:
83 NaClFileInfo info_;
84 PP_OpenResourceCompletionCallback callback_;
85 void* callback_user_data_;
86 DISALLOW_COPY_AND_ASSIGN(OpenManifestEntryAsyncCallback);
87 };
88
89 namespace {
90
91 class ManifestService {
92 public:
ManifestService(nacl::WeakRefAnchor * anchor,PluginReverseInterface * plugin_reverse)93 ManifestService(nacl::WeakRefAnchor* anchor,
94 PluginReverseInterface* plugin_reverse)
95 : anchor_(anchor),
96 plugin_reverse_(plugin_reverse) {
97 }
98
~ManifestService()99 ~ManifestService() {
100 anchor_->Unref();
101 }
102
Quit()103 bool Quit() {
104 delete this;
105 return false;
106 }
107
StartupInitializationComplete()108 bool StartupInitializationComplete() {
109 // Release this instance if the ServiceRuntime is already destructed.
110 if (anchor_->is_abandoned()) {
111 delete this;
112 return false;
113 }
114
115 plugin_reverse_->StartupInitializationComplete();
116 return true;
117 }
118
OpenResource(const char * entry_key,PP_OpenResourceCompletionCallback callback,void * callback_user_data)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);
125 delete this;
126 return false;
127 }
128
129 OpenManifestEntryAsyncCallback* open_manifest_callback =
130 new OpenManifestEntryAsyncCallback(callback, callback_user_data);
131 plugin_reverse_->OpenManifestEntryAsync(
132 entry_key,
133 open_manifest_callback->mutable_info(),
134 open_manifest_callback);
135 return true;
136 }
137
QuitTrampoline(void * user_data)138 static PP_Bool QuitTrampoline(void* user_data) {
139 return PP_FromBool(static_cast<ManifestService*>(user_data)->Quit());
140 }
141
StartupInitializationCompleteTrampoline(void * user_data)142 static PP_Bool StartupInitializationCompleteTrampoline(void* user_data) {
143 return PP_FromBool(static_cast<ManifestService*>(user_data)->
144 StartupInitializationComplete());
145 }
146
OpenResourceTrampoline(void * user_data,const char * entry_key,PP_OpenResourceCompletionCallback callback,void * callback_user_data)147 static PP_Bool OpenResourceTrampoline(
148 void* user_data,
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));
154 }
155
156 private:
157 // Weak reference to check if plugin_reverse is legally accessible or not.
158 nacl::WeakRefAnchor* anchor_;
159 PluginReverseInterface* plugin_reverse_;
160
161 DISALLOW_COPY_AND_ASSIGN(ManifestService);
162 };
163
164 // Vtable to pass functions to LaunchSelLdr.
165 const PPP_ManifestService kManifestServiceVTable = {
166 &ManifestService::QuitTrampoline,
167 &ManifestService::StartupInitializationCompleteTrampoline,
168 &ManifestService::OpenResourceTrampoline,
169 };
170
171 } // namespace
172
~OpenManifestEntryResource()173 OpenManifestEntryResource::~OpenManifestEntryResource() {
174 MaybeRunCallback(PP_ERROR_ABORTED);
175 }
176
MaybeRunCallback(int32_t pp_error)177 void OpenManifestEntryResource::MaybeRunCallback(int32_t pp_error) {
178 if (!callback)
179 return;
180
181 callback->Run(pp_error);
182 delete callback;
183 callback = NULL;
184 }
185
PluginReverseInterface(nacl::WeakRefAnchor * anchor,Plugin * plugin,ServiceRuntime * service_runtime,pp::CompletionCallback init_done_cb,pp::CompletionCallback crash_cb)186 PluginReverseInterface::PluginReverseInterface(
187 nacl::WeakRefAnchor* anchor,
188 Plugin* plugin,
189 ServiceRuntime* service_runtime,
190 pp::CompletionCallback init_done_cb,
191 pp::CompletionCallback crash_cb)
192 : anchor_(anchor),
193 plugin_(plugin),
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_);
200 }
201
~PluginReverseInterface()202 PluginReverseInterface::~PluginReverseInterface() {
203 NaClCondVarDtor(&cv_);
204 NaClMutexDtor(&mu_);
205 }
206
ShutDown()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");
213 }
214
DoPostMessage(nacl::string message)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());
219 }
220
StartupInitializationComplete()221 void PluginReverseInterface::StartupInitializationComplete() {
222 NaClLog(4, "PluginReverseInterface::StartupInitializationComplete\n");
223 if (init_done_cb_.pp_completion_callback().func != NULL) {
224 NaClLog(4,
225 "PluginReverseInterface::StartupInitializationComplete:"
226 " invoking CB\n");
227 pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb_, PP_OK);
228 } else {
229 NaClLog(1,
230 "PluginReverseInterface::StartupInitializationComplete:"
231 " init_done_cb_ not valid, skipping.\n");
232 }
233 }
234
235 // TODO(bsy): OpenManifestEntry should use the manifest to ResolveKey
236 // and invoke StreamAsFile with a completion callback that invokes
237 // GetPOSIXFileDesc.
OpenManifestEntry(nacl::string url_key,struct NaClFileInfo * info)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",
249 url_key.c_str());
250 // This assumes we are not on the main thread. If false, we deadlock.
251 plugin::WeakRefCallOnMainThread(
252 anchor_,
253 0,
254 this,
255 &plugin::PluginReverseInterface::OpenManifestEntry_MainThreadContinuation,
256 to_open);
257 NaClLog(4,
258 "PluginReverseInterface::OpenManifestEntry:"
259 " waiting on main thread\n");
260
261 {
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_) {
267 NaClLog(4,
268 "PluginReverseInterface::OpenManifestEntry:"
269 " plugin is shutting down\n");
270 return false;
271 }
272 }
273
274 // info->desc has the returned descriptor if successful, else -1.
275
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.
283 NaClLog(4,
284 "PluginReverseInterface::OpenManifestEntry: info->desc = %d\n",
285 info->desc);
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
290 // manifest.
291 NaClLog(4, "OpenManifestEntry: failed for key %s", url_key.c_str());
292 }
293 return true;
294 }
295
OpenManifestEntryAsync(const nacl::string & entry_key,struct NaClFileInfo * info,OpenManifestEntryAsyncCallback * callback)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);
304 }
305
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
311 // multiple steps.
OpenManifestEntry_MainThreadContinuation(OpenManifestEntryResource * p,int32_t err)312 void PluginReverseInterface::OpenManifestEntry_MainThreadContinuation(
313 OpenManifestEntryResource* p,
314 int32_t err) {
315 UNREFERENCED_PARAMETER(err);
316 // CallOnMainThread continuations always called with err == PP_OK.
317
318 NaClLog(4, "Entered OpenManifestEntry_MainThreadContinuation\n");
319
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()),
325 p->url.c_str(),
326 &pp_mapped_url,
327 &pnacl_options)) {
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.
331 {
332 nacl::MutexLocker take(&mu_);
333 *p->op_complete_ptr = true; // done...
334 p->file_info->desc = -1; // but failed.
335 NaClXCondVarBroadcast(&cv_);
336 }
337 p->MaybeRunCallback(PP_OK);
338 return;
339 }
340 nacl::string mapped_url = pp::Var(pp_mapped_url).AsString();
341 NaClLog(4,
342 "OpenManifestEntry_MainThreadContinuation: "
343 "ResolveKey: %s -> %s (pnacl_translate(%d))\n",
344 p->url.c_str(), mapped_url.c_str(), pnacl_options.translate);
345
346 if (pnacl_options.translate) {
347 // Requires PNaCl translation, but that's not supported.
348 NaClLog(4,
349 "OpenManifestEntry_MainThreadContinuation: "
350 "Requires PNaCl translation -- not supported\n");
351 {
352 nacl::MutexLocker take(&mu_);
353 *p->op_complete_ptr = true; // done...
354 p->file_info->desc = -1; // but failed.
355 NaClXCondVarBroadcast(&cv_);
356 }
357 p->MaybeRunCallback(PP_OK);
358 return;
359 }
360
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.
367 p->callback = NULL;
368
369 pp::CompletionCallback stream_cc = WeakRefNewCallback(
370 anchor_,
371 this,
372 &PluginReverseInterface::StreamAsFile_MainThreadContinuation,
373 open_cont);
374
375 GetNaClInterface()->DownloadFile(plugin_->pp_instance(),
376 mapped_url.c_str(),
377 &open_cont->pp_file_info,
378 stream_cc.pp_completion_callback());
379 // p is deleted automatically.
380 }
381
StreamAsFile_MainThreadContinuation(OpenManifestEntryResource * p,int32_t result)382 void PluginReverseInterface::StreamAsFile_MainThreadContinuation(
383 OpenManifestEntryResource* p,
384 int32_t result) {
385 NaClLog(4, "Entered StreamAsFile_MainThreadContinuation\n");
386 {
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;
394 NaClLog(4,
395 "StreamAsFile_MainThreadContinuation: PP_OK, desc %d\n",
396 p->file_info->desc);
397 } else {
398 NaClLog(
399 4,
400 "StreamAsFile_MainThreadContinuation: !PP_OK, setting desc -1\n");
401 p->file_info->desc = -1;
402 }
403 *p->op_complete_ptr = true;
404 NaClXCondVarBroadcast(&cv_);
405 }
406 p->MaybeRunCallback(PP_OK);
407 }
408
CloseManifestEntry(int32_t desc)409 bool PluginReverseInterface::CloseManifestEntry(int32_t desc) {
410 // We don't take any action on a call to CloseManifestEntry today, so always
411 // return success.
412 return true;
413 }
414
ReportCrash()415 void PluginReverseInterface::ReportCrash() {
416 NaClLog(4, "PluginReverseInterface::ReportCrash\n");
417
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();
423 } else {
424 NaClLog(1,
425 "PluginReverseInterface::ReportCrash:"
426 " crash_cb_ not valid, skipping\n");
427 }
428 }
429
ReportExitStatus(int exit_status)430 void PluginReverseInterface::ReportExitStatus(int exit_status) {
431 service_runtime_->set_exit_status(exit_status);
432 }
433
RequestQuotaForWrite(nacl::string file_id,int64_t offset,int64_t bytes_to_write)434 int64_t PluginReverseInterface::RequestQuotaForWrite(
435 nacl::string file_id, int64_t offset, int64_t bytes_to_write) {
436 return bytes_to_write;
437 }
438
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 {
LoadNexeAndStartDataplugin::ServiceRuntime::LoadNexeAndStartData443 explicit LoadNexeAndStartData(const pp::CompletionCallback& callback)
444 : callback(callback) {
445 }
446
~LoadNexeAndStartDataplugin::ServiceRuntime::LoadNexeAndStartData447 ~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);
452 }
453
454 // On success path, this must be invoked manually. Otherwise the dtor would
455 // invoke callbacks with error code unexpectedly.
Clearplugin::ServiceRuntime::LoadNexeAndStartData456 void Clear() {
457 callback = pp::CompletionCallback();
458 }
459
460 pp::CompletionCallback callback;
461 };
462
ServiceRuntime(Plugin * plugin,bool main_service_runtime,bool uses_nonsfi_mode,pp::CompletionCallback init_done_cb,pp::CompletionCallback crash_cb)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)
468 : plugin_(plugin),
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_);
480 }
481
LoadNexeAndStartAfterLoadModule(LoadNexeAndStartData * data,int32_t pp_error)482 void ServiceRuntime::LoadNexeAndStartAfterLoadModule(
483 LoadNexeAndStartData* data, int32_t pp_error) {
484 if (pp_error != PP_OK) {
485 DidLoadNexeAndStart(data, pp_error);
486 return;
487 }
488
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);
492 }
493
DidLoadNexeAndStart(LoadNexeAndStartData * data,int32_t pp_error)494 void ServiceRuntime::DidLoadNexeAndStart(
495 LoadNexeAndStartData* data, int32_t pp_error) {
496 if (pp_error == PP_OK) {
497 NaClLog(4, "ServiceRuntime::LoadNexeAndStart (success)\n");
498 } else {
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");
514 } else {
515 NaClLog(LOG_ERROR, "Reverse service thread will pick up crash log\n");
516 }
517 }
518
519 pp::Module::Get()->core()->CallOnMainThread(0, data->callback, pp_error);
520
521 // Because the ownership of data is taken by caller, we must clear it
522 // manually here. Otherwise, its dtor invokes callbacks again.
523 data->Clear();
524 }
525
SetupCommandChannel()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);
536 }
537 return false;
538 }
539 return true;
540 }
541
LoadModule(PP_NaClFileInfo file_info,pp::CompletionCallback callback)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);
549 if (desc == NULL) {
550 DidLoadModule(callback, PP_ERROR_FAILED);
551 return;
552 }
553
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);
558
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);
562 }
563
DidLoadModule(pp::CompletionCallback callback,int32_t pp_error)564 void ServiceRuntime::DidLoadModule(pp::CompletionCallback callback,
565 int32_t pp_error) {
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);
571 }
572 callback.Run(pp_error);
573 }
574
InitReverseService()575 bool ServiceRuntime::InitReverseService() {
576 if (uses_nonsfi_mode_) {
577 // In non-SFI mode, no reverse service is set up. Just returns success.
578 return true;
579 }
580
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_,
586 "reverse_setup::h",
587 &out_conn_cap);
588
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);
595 }
596 return false;
597 }
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(
603 out_conn_cap);
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);
610 }
611 return false;
612 }
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);
622 }
623 return false;
624 }
625 return true;
626 }
627
StartModule()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!)
631 // in libsrpc.
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
635 // the plugin.
636 load_status = LOAD_OK;
637 } else {
638 NaClSrpcResultCodes rpc_result =
639 NaClSrpcInvokeBySignature(&command_channel_,
640 "start_module::i",
641 &load_status);
642
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);
649 }
650 return false;
651 }
652 }
653
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(),
659 load_status,
660 NACL_ERROR_CODE_MAX);
661 }
662
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);
670 }
671 return false;
672 }
673 return true;
674 }
675
StartSelLdr(const SelLdrStartParams & params,pp::CompletionCallback callback)676 void ServiceRuntime::StartSelLdr(const SelLdrStartParams& params,
677 pp::CompletionCallback callback) {
678 NaClLog(4, "ServiceRuntime::Start\n");
679
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);
690 }
691 pp::Module::Get()->core()->CallOnMainThread(0, callback, PP_ERROR_FAILED);
692 return;
693 }
694
695 ManifestService* manifest_service =
696 new ManifestService(anchor_->Ref(), rev_interface_);
697 bool enable_dev_interfaces =
698 GetNaClInterface()->DevInterfacesEnabled(plugin_->pp_instance());
699
700 tmp_subprocess->Start(plugin_->pp_instance(),
701 main_service_runtime_,
702 params.url.c_str(),
703 params.uses_irt,
704 params.uses_ppapi,
705 uses_nonsfi_mode_,
706 enable_dev_interfaces,
707 params.enable_dyncode_syscalls,
708 params.enable_exception_handling,
709 params.enable_crash_throttling,
710 &kManifestServiceVTable,
711 manifest_service,
712 callback);
713 subprocess_.reset(tmp_subprocess.release());
714 }
715
WaitForSelLdrStart()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.
719 //
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;
738 }
739 return start_sel_ldr_done_;
740 }
741
SignalStartSelLdrDone()742 void ServiceRuntime::SignalStartSelLdrDone() {
743 nacl::MutexLocker take(&mu_);
744 start_sel_ldr_done_ = true;
745 NaClXCondVarSignal(&cond_);
746 }
747
WaitForNexeStart()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;
754 }
755
SignalNexeStarted()756 void ServiceRuntime::SignalNexeStarted() {
757 nacl::MutexLocker take(&mu_);
758 nexe_started_ = true;
759 NaClXCondVarSignal(&cond_);
760 }
761
LoadNexeAndStart(PP_NaClFileInfo file_info,const pp::CompletionCallback & callback)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,
767 file_info.token_lo,
768 file_info.token_hi);
769
770 nacl::scoped_ptr<LoadNexeAndStartData> data(
771 new LoadNexeAndStartData(callback));
772 if (!SetupCommandChannel() || !InitReverseService()) {
773 DidLoadNexeAndStart(data.get(), PP_ERROR_FAILED);
774 return;
775 }
776
777 LoadModule(
778 file_info,
779 WeakRefNewCallback(anchor_,
780 this,
781 &ServiceRuntime::LoadNexeAndStartAfterLoadModule,
782 data.release())); // Delegate the ownership.
783 }
784
SetupAppChannel()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");
791 return NULL;
792 } else {
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));
798 delete connect_desc;
799 return srpc_client;
800 }
801 }
802
Log(int severity,const nacl::string & msg)803 bool ServiceRuntime::Log(int severity, const nacl::string& msg) {
804 NaClSrpcResultCodes rpc_result =
805 NaClSrpcInvokeBySignature(&command_channel_,
806 "log:is:",
807 severity,
808 strdup(msg.c_str()));
809 return (NACL_SRPC_RESULT_OK == rpc_result);
810 }
811
Shutdown()812 void ServiceRuntime::Shutdown() {
813 rev_interface_->ShutDown();
814 anchor_->Abandon();
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
820 // be deallocated.
821
822 // Note that this does waitpid() to get rid of any zombie subprocess.
823 subprocess_.reset(NULL);
824
825 NaClSrpcDtor(&command_channel_);
826
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;
836 }
837 }
838
~ServiceRuntime()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();
846
847 rev_interface_->Unref();
848
849 anchor_->Unref();
850 NaClCondVarDtor(&cond_);
851 NaClMutexDtor(&mu_);
852 }
853
set_exit_status(int exit_status)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);
858 }
859
GetCrashLogOutput()860 nacl::string ServiceRuntime::GetCrashLogOutput() {
861 if (NULL != subprocess_.get()) {
862 return subprocess_->GetCrashLogOutput();
863 } else {
864 return std::string();
865 }
866 }
867
868 } // namespace plugin
869