Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / ppapi / native_client / src / trusted / plugin / service_runtime.cc
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 // 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.
39 #ifdef PostMessage
40 #undef PostMessage
41 #endif
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"
45
46 #include "ppapi/c/pp_errors.h"
47 #include "ppapi/cpp/core.h"
48 #include "ppapi/cpp/completion_callback.h"
49
50 #include "ppapi/native_client/src/trusted/plugin/manifest.h"
51 #include "ppapi/native_client/src/trusted/plugin/plugin.h"
52 #include "ppapi/native_client/src/trusted/plugin/plugin_error.h"
53 #include "ppapi/native_client/src/trusted/plugin/pnacl_options.h"
54 #include "ppapi/native_client/src/trusted/plugin/pnacl_resources.h"
55 #include "ppapi/native_client/src/trusted/plugin/sel_ldr_launcher_chrome.h"
56 #include "ppapi/native_client/src/trusted/plugin/srpc_client.h"
57 #include "ppapi/native_client/src/trusted/weak_ref/call_on_main_thread.h"
58
59 namespace {
60
61 // For doing crude quota enforcement on writes to temp files.
62 // We do not allow a temp file bigger than 128 MB for now.
63 // There is currently a limit of 32M for nexe text size, so 128M
64 // should be plenty for static data
65 const int64_t kMaxTempQuota = 0x8000000;
66
67 }  // namespace
68
69 namespace plugin {
70
71 PluginReverseInterface::PluginReverseInterface(
72     nacl::WeakRefAnchor* anchor,
73     Plugin* plugin,
74     const Manifest* manifest,
75     ServiceRuntime* service_runtime,
76     pp::CompletionCallback init_done_cb,
77     pp::CompletionCallback crash_cb)
78       : anchor_(anchor),
79         plugin_(plugin),
80         manifest_(manifest),
81         service_runtime_(service_runtime),
82         shutting_down_(false),
83         init_done_cb_(init_done_cb),
84         crash_cb_(crash_cb) {
85   NaClXMutexCtor(&mu_);
86   NaClXCondVarCtor(&cv_);
87 }
88
89 PluginReverseInterface::~PluginReverseInterface() {
90   NaClCondVarDtor(&cv_);
91   NaClMutexDtor(&mu_);
92 }
93
94 void PluginReverseInterface::ShutDown() {
95   NaClLog(4, "PluginReverseInterface::Shutdown: entered\n");
96   nacl::MutexLocker take(&mu_);
97   shutting_down_ = true;
98   NaClXCondVarBroadcast(&cv_);
99   NaClLog(4, "PluginReverseInterface::Shutdown: broadcasted, exiting\n");
100 }
101
102 void PluginReverseInterface::DoPostMessage(nacl::string message) {
103   PostMessageResource* continuation = new PostMessageResource(message);
104   CHECK(continuation != NULL);
105   NaClLog(4, "PluginReverseInterface::DoPostMessage(%s)\n", message.c_str());
106   plugin::WeakRefCallOnMainThread(
107       anchor_,
108       0,  /* delay in ms */
109       this,
110       &plugin::PluginReverseInterface::PostMessage_MainThreadContinuation,
111       continuation);
112 }
113
114 void PluginReverseInterface::StartupInitializationComplete() {
115   NaClLog(4, "PluginReverseInterface::StartupInitializationComplete\n");
116   if (init_done_cb_.pp_completion_callback().func != NULL) {
117     NaClLog(4,
118             "PluginReverseInterface::StartupInitializationComplete:"
119             " invoking CB\n");
120     pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb_, PP_OK);
121   } else {
122     NaClLog(1,
123             "PluginReverseInterface::StartupInitializationComplete:"
124             " init_done_cb_ not valid, skipping.\n");
125   }
126 }
127
128 void PluginReverseInterface::PostMessage_MainThreadContinuation(
129     PostMessageResource* p,
130     int32_t err) {
131   UNREFERENCED_PARAMETER(err);
132   NaClLog(4,
133           "PluginReverseInterface::PostMessage_MainThreadContinuation(%s)\n",
134           p->message.c_str());
135   plugin_->PostMessage(std::string("DEBUG_POSTMESSAGE:") + p->message);
136 }
137
138 bool PluginReverseInterface::EnumerateManifestKeys(
139     std::set<nacl::string>* out_keys) {
140   return manifest_->GetFileKeys(out_keys);
141 }
142
143 // TODO(bsy): OpenManifestEntry should use the manifest to ResolveKey
144 // and invoke StreamAsFile with a completion callback that invokes
145 // GetPOSIXFileDesc.
146 bool PluginReverseInterface::OpenManifestEntry(nacl::string url_key,
147                                                struct NaClFileInfo* info) {
148   bool op_complete = false;  // NB: mu_ and cv_ also controls access to this!
149   // The to_open object is owned by the weak ref callback. Because this function
150   // waits for the callback to finish, the to_open object will be deallocated on
151   // the main thread before this function can return. The pointers it contains
152   // to stack variables will not leak.
153   OpenManifestEntryResource* to_open =
154       new OpenManifestEntryResource(url_key, info, &op_complete);
155   CHECK(to_open != NULL);
156   NaClLog(4, "PluginReverseInterface::OpenManifestEntry: %s\n",
157           url_key.c_str());
158   // This assumes we are not on the main thread.  If false, we deadlock.
159   plugin::WeakRefCallOnMainThread(
160       anchor_,
161       0,
162       this,
163       &plugin::PluginReverseInterface::OpenManifestEntry_MainThreadContinuation,
164       to_open);
165   NaClLog(4,
166           "PluginReverseInterface::OpenManifestEntry:"
167           " waiting on main thread\n");
168
169   {
170     nacl::MutexLocker take(&mu_);
171     while (!shutting_down_ && !op_complete)
172       NaClXCondVarWait(&cv_, &mu_);
173     NaClLog(4, "PluginReverseInterface::OpenManifestEntry: done!\n");
174     if (shutting_down_) {
175       NaClLog(4,
176               "PluginReverseInterface::OpenManifestEntry:"
177               " plugin is shutting down\n");
178       return false;
179     }
180   }
181
182   // info->desc has the returned descriptor if successful, else -1.
183
184   // The caller is responsible for not closing info->desc.  If it is
185   // closed prematurely, then another open could re-use the OS
186   // descriptor, confusing the opened_ map.  If the caller is going to
187   // want to make a NaClDesc object and transfer it etc., then the
188   // caller should DUP the descriptor (but remember the original
189   // value) for use by the NaClDesc object, which closes when the
190   // object is destroyed.
191   NaClLog(4,
192           "PluginReverseInterface::OpenManifestEntry: info->desc = %d\n",
193           info->desc);
194   if (info->desc == -1) {
195     // TODO(bsy,ncbray): what else should we do with the error?  This
196     // is a runtime error that may simply be a programming error in
197     // the untrusted code, or it may be something else wrong w/ the
198     // manifest.
199     NaClLog(4, "OpenManifestEntry: failed for key %s", url_key.c_str());
200   }
201   return true;
202 }
203
204 // Transfer point from OpenManifestEntry() which runs on the main thread
205 // (Some PPAPI actions -- like StreamAsFile -- can only run on the main thread).
206 // OpenManifestEntry() is waiting on a condvar for this continuation to
207 // complete.  We Broadcast and awaken OpenManifestEntry() whenever we are done
208 // either here, or in a later MainThreadContinuation step, if there are
209 // multiple steps.
210 void PluginReverseInterface::OpenManifestEntry_MainThreadContinuation(
211     OpenManifestEntryResource* p,
212     int32_t err) {
213   UNREFERENCED_PARAMETER(err);
214   // CallOnMainThread continuations always called with err == PP_OK.
215
216   NaClLog(4, "Entered OpenManifestEntry_MainThreadContinuation\n");
217
218   std::string mapped_url;
219   PnaclOptions pnacl_options;
220   ErrorInfo error_info;
221   if (!manifest_->ResolveKey(p->url, &mapped_url,
222                              &pnacl_options, &error_info)) {
223     NaClLog(4, "OpenManifestEntry_MainThreadContinuation: ResolveKey failed\n");
224     NaClLog(4,
225             "Error code %d, string %s\n",
226             error_info.error_code(),
227             error_info.message().c_str());
228     // Failed, and error_info has the details on what happened.  Wake
229     // up requesting thread -- we are done.
230     nacl::MutexLocker take(&mu_);
231     *p->op_complete_ptr = true;  // done...
232     p->file_info->desc = -1;  // but failed.
233     NaClXCondVarBroadcast(&cv_);
234     return;
235   }
236   NaClLog(4,
237           "OpenManifestEntry_MainThreadContinuation: "
238           "ResolveKey: %s -> %s (pnacl_translate(%d))\n",
239           p->url.c_str(), mapped_url.c_str(), pnacl_options.translate());
240
241   if (pnacl_options.translate()) {
242     // Requires PNaCl translation, but that's not supported.
243     NaClLog(4,
244             "OpenManifestEntry_MainThreadContinuation: "
245             "Requires PNaCl translation -- not supported\n");
246     nacl::MutexLocker take(&mu_);
247     *p->op_complete_ptr = true;  // done...
248     p->file_info->desc = -1;  // but failed.
249     NaClXCondVarBroadcast(&cv_);
250     return;
251   }
252
253   if (PnaclUrls::IsPnaclComponent(mapped_url)) {
254     // Special PNaCl support files, that are installed on the
255     // user machine.
256     int32_t fd = PnaclResources::GetPnaclFD(
257         plugin_,
258         PnaclUrls::PnaclComponentURLToFilename(mapped_url).c_str());
259     if (fd < 0) {
260       // We checked earlier if the pnacl component wasn't installed
261       // yet, so this shouldn't happen. At this point, we can't do much
262       // anymore, so just continue with an invalid fd.
263       NaClLog(4,
264               "OpenManifestEntry_MainThreadContinuation: "
265               "GetReadonlyPnaclFd failed\n");
266     }
267     nacl::MutexLocker take(&mu_);
268     *p->op_complete_ptr = true;  // done!
269     // TODO(ncbray): enable the fast loading and validation paths for this
270     // type of file.
271     p->file_info->desc = fd;
272     NaClXCondVarBroadcast(&cv_);
273     NaClLog(4,
274             "OpenManifestEntry_MainThreadContinuation: GetPnaclFd okay\n");
275     return;
276   }
277
278   // Hereafter, normal files.
279
280   // Because p is owned by the callback of this invocation, so it is necessary
281   // to create another instance.
282   OpenManifestEntryResource* open_cont = new OpenManifestEntryResource(*p);
283   open_cont->url = mapped_url;
284   pp::CompletionCallback stream_cc = WeakRefNewCallback(
285       anchor_,
286       this,
287       &PluginReverseInterface::StreamAsFile_MainThreadContinuation,
288       open_cont);
289
290   if (!plugin_->StreamAsFile(mapped_url, stream_cc)) {
291     NaClLog(4,
292             "OpenManifestEntry_MainThreadContinuation: "
293             "StreamAsFile failed\n");
294     // Here, StreamAsFile is failed and stream_cc is not called.
295     // However, open_cont will be released only by the invocation.
296     // So, we manually call it here with error.
297     stream_cc.Run(PP_ERROR_FAILED);
298     return;
299   }
300
301   NaClLog(4, "OpenManifestEntry_MainThreadContinuation: StreamAsFile okay\n");
302   // p is deleted automatically
303 }
304
305 void PluginReverseInterface::StreamAsFile_MainThreadContinuation(
306     OpenManifestEntryResource* p,
307     int32_t result) {
308   NaClLog(4,
309           "Entered StreamAsFile_MainThreadContinuation\n");
310
311   nacl::MutexLocker take(&mu_);
312   if (result == PP_OK) {
313     NaClLog(4, "StreamAsFile_MainThreadContinuation: GetFileInfo(%s)\n",
314             p->url.c_str());
315     *p->file_info = plugin_->GetFileInfo(p->url);
316
317     NaClLog(4,
318             "StreamAsFile_MainThreadContinuation: PP_OK, desc %d\n",
319             p->file_info->desc);
320   } else {
321     NaClLog(4,
322             "StreamAsFile_MainThreadContinuation: !PP_OK, setting desc -1\n");
323     p->file_info->desc = -1;
324   }
325   *p->op_complete_ptr = true;
326   NaClXCondVarBroadcast(&cv_);
327 }
328
329 bool PluginReverseInterface::CloseManifestEntry(int32_t desc) {
330   bool op_complete = false;
331   bool op_result;
332   CloseManifestEntryResource* to_close =
333       new CloseManifestEntryResource(desc, &op_complete, &op_result);
334
335   plugin::WeakRefCallOnMainThread(
336       anchor_,
337       0,
338       this,
339       &plugin::PluginReverseInterface::
340         CloseManifestEntry_MainThreadContinuation,
341       to_close);
342
343   // wait for completion or surf-away.
344   {
345     nacl::MutexLocker take(&mu_);
346     while (!shutting_down_ && !op_complete)
347       NaClXCondVarWait(&cv_, &mu_);
348     if (shutting_down_)
349       return false;
350   }
351
352   // op_result true if close was successful; false otherwise (e.g., bad desc).
353   return op_result;
354 }
355
356 void PluginReverseInterface::CloseManifestEntry_MainThreadContinuation(
357     CloseManifestEntryResource* cls,
358     int32_t err) {
359   UNREFERENCED_PARAMETER(err);
360
361   nacl::MutexLocker take(&mu_);
362   // TODO(bsy): once the plugin has a reliable way to report that the
363   // file usage is done -- and sel_ldr uses this RPC call -- we should
364   // tell the plugin that the associated resources can be freed.
365   *cls->op_result_ptr = true;
366   *cls->op_complete_ptr = true;
367   NaClXCondVarBroadcast(&cv_);
368   // cls automatically deleted
369 }
370
371 void PluginReverseInterface::ReportCrash() {
372   NaClLog(4, "PluginReverseInterface::ReportCrash\n");
373
374   if (crash_cb_.pp_completion_callback().func != NULL) {
375     NaClLog(4, "PluginReverseInterface::ReportCrash: invoking CB\n");
376     pp::Module::Get()->core()->CallOnMainThread(0, crash_cb_, PP_OK);
377   } else {
378     NaClLog(1,
379             "PluginReverseInterface::ReportCrash:"
380             " crash_cb_ not valid, skipping\n");
381   }
382 }
383
384 void PluginReverseInterface::ReportExitStatus(int exit_status) {
385   service_runtime_->set_exit_status(exit_status);
386 }
387
388 int64_t PluginReverseInterface::RequestQuotaForWrite(
389     nacl::string file_id, int64_t offset, int64_t bytes_to_write) {
390   NaClLog(4,
391           "PluginReverseInterface::RequestQuotaForWrite:"
392           " (file_id='%s', offset=%" NACL_PRId64 ", bytes_to_write=%"
393           NACL_PRId64 ")\n", file_id.c_str(), offset, bytes_to_write);
394   uint64_t file_key = STRTOULL(file_id.c_str(), NULL, 10);
395   nacl::MutexLocker take(&mu_);
396   if (quota_files_.count(file_key) == 0) {
397     // Look up failed to find the requested quota managed resource.
398     NaClLog(4, "PluginReverseInterface::RequestQuotaForWrite: failed...\n");
399     return 0;
400   }
401
402   // Because we now only support this interface for tempfiles which are not
403   // pepper objects, we can just do some crude quota enforcement here rather
404   // than calling out to pepper from the main thread.
405   if (offset + bytes_to_write >= kMaxTempQuota)
406     return 0;
407
408   return bytes_to_write;
409 }
410
411 void PluginReverseInterface::AddTempQuotaManagedFile(
412     const nacl::string& file_id) {
413   NaClLog(4, "PluginReverseInterface::AddTempQuotaManagedFile: "
414           "(file_id='%s')\n", file_id.c_str());
415   uint64_t file_key = STRTOULL(file_id.c_str(), NULL, 10);
416   nacl::MutexLocker take(&mu_);
417   quota_files_.insert(file_key);
418 }
419
420 ServiceRuntime::ServiceRuntime(Plugin* plugin,
421                                const Manifest* manifest,
422                                bool main_service_runtime,
423                                bool uses_nonsfi_mode,
424                                pp::CompletionCallback init_done_cb,
425                                pp::CompletionCallback crash_cb)
426     : plugin_(plugin),
427       main_service_runtime_(main_service_runtime),
428       uses_nonsfi_mode_(uses_nonsfi_mode),
429       reverse_service_(NULL),
430       anchor_(new nacl::WeakRefAnchor()),
431       rev_interface_(new PluginReverseInterface(anchor_, plugin,
432                                                 manifest,
433                                                 this,
434                                                 init_done_cb, crash_cb)),
435       exit_status_(-1),
436       start_sel_ldr_done_(false),
437       callback_factory_(this) {
438   NaClSrpcChannelInitialize(&command_channel_);
439   NaClXMutexCtor(&mu_);
440   NaClXCondVarCtor(&cond_);
441 }
442
443 bool ServiceRuntime::SetupCommandChannel(ErrorInfo* error_info) {
444   NaClLog(4, "ServiceRuntime::SetupCommand (this=%p, subprocess=%p)\n",
445           static_cast<void*>(this),
446           static_cast<void*>(subprocess_.get()));
447   if (!subprocess_->SetupCommand(&command_channel_)) {
448     error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
449                           "ServiceRuntime: command channel creation failed");
450     return false;
451   }
452   return true;
453 }
454
455 bool ServiceRuntime::LoadModule(nacl::DescWrapper* nacl_desc,
456                                 ErrorInfo* error_info) {
457   NaClLog(4, "ServiceRuntime::LoadModule"
458           " (this=%p, subprocess=%p)\n",
459           static_cast<void*>(this),
460           static_cast<void*>(subprocess_.get()));
461   CHECK(nacl_desc);
462   if (!subprocess_->LoadModule(&command_channel_, nacl_desc)) {
463     error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_CMD_CHANNEL,
464                           "ServiceRuntime: load module failed");
465     return false;
466   }
467   return true;
468 }
469
470 bool ServiceRuntime::InitReverseService(ErrorInfo* error_info) {
471   if (uses_nonsfi_mode_) {
472     // In non-SFI mode, open_resource() is not yet supported, so we do not
473     // need the reverse service. So, skip the initialization (with calling
474     // the completion callback).
475     // Note that there is on going work to replace SRPC by Chrome IPC (not only
476     // for non-SFI mode, but also for SFI mode) (crbug.com/333950),
477     // and non-SFI mode will use Chrome IPC for open_resource() after the
478     // refactoring is done.
479     rev_interface_->StartupInitializationComplete();
480     return true;
481   }
482
483   // Hook up the reverse service channel.  We are the IMC client, but
484   // provide SRPC service.
485   NaClDesc* out_conn_cap;
486   NaClSrpcResultCodes rpc_result =
487       NaClSrpcInvokeBySignature(&command_channel_,
488                                 "reverse_setup::h",
489                                 &out_conn_cap);
490
491   if (NACL_SRPC_RESULT_OK != rpc_result) {
492     error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SETUP,
493                           "ServiceRuntime: reverse setup rpc failed");
494     return false;
495   }
496   //  Get connection capability to service runtime where the IMC
497   //  server/SRPC client is waiting for a rendezvous.
498   NaClLog(4, "ServiceRuntime: got 0x%" NACL_PRIxPTR "\n",
499           (uintptr_t) out_conn_cap);
500   nacl::DescWrapper* conn_cap = plugin_->wrapper_factory()->MakeGenericCleanup(
501       out_conn_cap);
502   if (conn_cap == NULL) {
503     error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_WRAPPER,
504                           "ServiceRuntime: wrapper allocation failure");
505     return false;
506   }
507   out_conn_cap = NULL;  // ownership passed
508   NaClLog(4, "ServiceRuntime::InitReverseService: starting reverse service\n");
509   reverse_service_ = new nacl::ReverseService(conn_cap, rev_interface_->Ref());
510   if (!reverse_service_->Start()) {
511     error_info->SetReport(PP_NACL_ERROR_SEL_LDR_COMMUNICATION_REV_SERVICE,
512                           "ServiceRuntime: starting reverse services failed");
513     return false;
514   }
515   return true;
516 }
517
518 bool ServiceRuntime::StartModule(ErrorInfo* error_info) {
519   // start the module.  otherwise we cannot connect for multimedia
520   // subsystem since that is handled by user-level code (not secure!)
521   // in libsrpc.
522   int load_status = -1;
523   if (uses_nonsfi_mode_) {
524     // In non-SFI mode, we don't need to call start_module SRPC to launch
525     // the plugin.
526     load_status = LOAD_OK;
527   } else {
528     NaClSrpcResultCodes rpc_result =
529         NaClSrpcInvokeBySignature(&command_channel_,
530                                   "start_module::i",
531                                   &load_status);
532
533     if (NACL_SRPC_RESULT_OK != rpc_result) {
534       error_info->SetReport(PP_NACL_ERROR_SEL_LDR_START_MODULE,
535                             "ServiceRuntime: could not start nacl module");
536       return false;
537     }
538   }
539
540   NaClLog(4, "ServiceRuntime::StartModule (load_status=%d)\n", load_status);
541   if (main_service_runtime_) {
542     plugin_->ReportSelLdrLoadStatus(load_status);
543   }
544   if (LOAD_OK != load_status) {
545     error_info->SetReport(
546         PP_NACL_ERROR_SEL_LDR_START_STATUS,
547         NaClErrorString(static_cast<NaClErrorCode>(load_status)));
548     return false;
549   }
550   return true;
551 }
552
553 void ServiceRuntime::StartSelLdr(const SelLdrStartParams& params,
554                                  pp::CompletionCallback callback) {
555   NaClLog(4, "ServiceRuntime::Start\n");
556
557   nacl::scoped_ptr<SelLdrLauncherChrome>
558       tmp_subprocess(new SelLdrLauncherChrome());
559   if (NULL == tmp_subprocess.get()) {
560     NaClLog(LOG_ERROR, "ServiceRuntime::Start (subprocess create failed)\n");
561     if (main_service_runtime_) {
562       ErrorInfo error_info;
563       error_info.SetReport(
564           PP_NACL_ERROR_SEL_LDR_CREATE_LAUNCHER,
565           "ServiceRuntime: failed to create sel_ldr launcher");
566       plugin_->ReportLoadError(error_info);
567     }
568     pp::Module::Get()->core()->CallOnMainThread(0, callback, PP_ERROR_FAILED);
569     return;
570   }
571   pp::CompletionCallback internal_callback =
572       callback_factory_.NewCallback(&ServiceRuntime::StartSelLdrContinuation,
573                                     callback);
574
575   tmp_subprocess->Start(plugin_->pp_instance(),
576                         params.url.c_str(),
577                         params.uses_irt,
578                         params.uses_ppapi,
579                         params.uses_nonsfi_mode,
580                         params.enable_dev_interfaces,
581                         params.enable_dyncode_syscalls,
582                         params.enable_exception_handling,
583                         params.enable_crash_throttling,
584                         &start_sel_ldr_error_message_,
585                         internal_callback);
586   subprocess_.reset(tmp_subprocess.release());
587 }
588
589 void ServiceRuntime::StartSelLdrContinuation(int32_t pp_error,
590                                              pp::CompletionCallback callback) {
591   if (pp_error != PP_OK) {
592     NaClLog(LOG_ERROR, "ServiceRuntime::StartSelLdrContinuation "
593                        " (start failed)\n");
594     if (main_service_runtime_) {
595       std::string error_message;
596       pp::Var var_error_message_cpp(pp::PASS_REF, start_sel_ldr_error_message_);
597       if (var_error_message_cpp.is_string()) {
598         error_message = var_error_message_cpp.AsString();
599       }
600       ErrorInfo error_info;
601       error_info.SetReportWithConsoleOnlyError(
602           PP_NACL_ERROR_SEL_LDR_LAUNCH,
603           "ServiceRuntime: failed to start",
604           error_message);
605       plugin_->ReportLoadError(error_info);
606     }
607   }
608   pp::Module::Get()->core()->CallOnMainThread(0, callback, pp_error);
609 }
610
611 bool ServiceRuntime::WaitForSelLdrStart() {
612   // Time to wait on condvar (for browser to create a new sel_ldr process on
613   // our behalf). Use 6 seconds to be *fairly* conservative.
614   //
615   // On surfaway, the CallOnMainThread above may never get scheduled
616   // to unblock this condvar, or the IPC reply from the browser to renderer
617   // might get canceled/dropped. However, it is currently important to
618   // avoid waiting indefinitely because ~PnaclCoordinator will attempt to
619   // join() the PnaclTranslateThread, and the PnaclTranslateThread is waiting
620   // for the signal before exiting.
621   static int64_t const kWaitTimeMicrosecs = 6 * NACL_MICROS_PER_UNIT;
622   int64_t left_to_wait = kWaitTimeMicrosecs;
623   int64_t deadline = NaClGetTimeOfDayMicroseconds() + left_to_wait;
624   nacl::MutexLocker take(&mu_);
625   while(!start_sel_ldr_done_ && left_to_wait > 0) {
626     struct nacl_abi_timespec left_timespec;
627     left_timespec.tv_sec = left_to_wait / NACL_MICROS_PER_UNIT;
628     left_timespec.tv_nsec =
629         (left_to_wait % NACL_MICROS_PER_UNIT) * NACL_NANOS_PER_MICRO;
630     NaClXCondVarTimedWaitRelative(&cond_, &mu_, &left_timespec);
631     int64_t now = NaClGetTimeOfDayMicroseconds();
632     left_to_wait = deadline - now;
633   }
634   return start_sel_ldr_done_;
635 }
636
637 void ServiceRuntime::SignalStartSelLdrDone() {
638   nacl::MutexLocker take(&mu_);
639   start_sel_ldr_done_ = true;
640   NaClXCondVarSignal(&cond_);
641 }
642
643 bool ServiceRuntime::LoadNexeAndStart(nacl::DescWrapper* nacl_desc,
644                                       const pp::CompletionCallback& crash_cb) {
645   NaClLog(4, "ServiceRuntime::LoadNexeAndStart (nacl_desc=%p)\n",
646           reinterpret_cast<void*>(nacl_desc));
647   ErrorInfo error_info;
648
649   bool ok = SetupCommandChannel(&error_info) &&
650             InitReverseService(&error_info) &&
651             LoadModule(nacl_desc, &error_info) &&
652             StartModule(&error_info);
653   if (!ok) {
654     if (main_service_runtime_) {
655       plugin_->ReportLoadError(error_info);
656     }
657     // On a load failure the service runtime does not crash itself to
658     // avoid a race where the no-more-senders error on the reverse
659     // channel esrvice thread might cause the crash-detection logic to
660     // kick in before the start_module RPC reply has been received. So
661     // we induce a service runtime crash here. We do not release
662     // subprocess_ since it's needed to collect crash log output after
663     // the error is reported.
664     Log(LOG_FATAL, "reap logs");
665     if (NULL == reverse_service_) {
666       // No crash detector thread.
667       NaClLog(LOG_ERROR, "scheduling to get crash log\n");
668       pp::Module::Get()->core()->CallOnMainThread(0, crash_cb, PP_OK);
669       NaClLog(LOG_ERROR, "should fire soon\n");
670     } else {
671       NaClLog(LOG_ERROR, "Reverse service thread will pick up crash log\n");
672     }
673     return false;
674   }
675
676   NaClLog(4, "ServiceRuntime::LoadNexeAndStart (return 1)\n");
677   return true;
678 }
679
680 SrpcClient* ServiceRuntime::SetupAppChannel() {
681   NaClLog(4, "ServiceRuntime::SetupAppChannel (subprocess_=%p)\n",
682           reinterpret_cast<void*>(subprocess_.get()));
683   nacl::DescWrapper* connect_desc = subprocess_->socket_addr()->Connect();
684   if (NULL == connect_desc) {
685     NaClLog(LOG_ERROR, "ServiceRuntime::SetupAppChannel (connect failed)\n");
686     return NULL;
687   } else {
688     NaClLog(4, "ServiceRuntime::SetupAppChannel (conect_desc=%p)\n",
689             static_cast<void*>(connect_desc));
690     SrpcClient* srpc_client = SrpcClient::New(connect_desc);
691     NaClLog(4, "ServiceRuntime::SetupAppChannel (srpc_client=%p)\n",
692             static_cast<void*>(srpc_client));
693     delete connect_desc;
694     return srpc_client;
695   }
696 }
697
698 bool ServiceRuntime::Log(int severity, const nacl::string& msg) {
699   NaClSrpcResultCodes rpc_result =
700       NaClSrpcInvokeBySignature(&command_channel_,
701                                 "log:is:",
702                                 severity,
703                                 strdup(msg.c_str()));
704   return (NACL_SRPC_RESULT_OK == rpc_result);
705 }
706
707 void ServiceRuntime::Shutdown() {
708   rev_interface_->ShutDown();
709   anchor_->Abandon();
710   // Abandon callbacks, tell service threads to quit if they were
711   // blocked waiting for main thread operations to finish.  Note that
712   // some callbacks must still await their completion event, e.g.,
713   // CallOnMainThread must still wait for the time out, or I/O events
714   // must finish, so resources associated with pending events cannot
715   // be deallocated.
716
717   // Note that this does waitpid() to get rid of any zombie subprocess.
718   subprocess_.reset(NULL);
719
720   NaClSrpcDtor(&command_channel_);
721
722   // subprocess_ has been shut down, but threads waiting on messages
723   // from the service runtime may not have noticed yet.  The low-level
724   // NaClSimpleRevService code takes care to refcount the data objects
725   // that it needs, and reverse_service_ is also refcounted.  We wait
726   // for the service threads to get their EOF indications.
727   if (reverse_service_ != NULL) {
728     reverse_service_->WaitForServiceThreadsToExit();
729     reverse_service_->Unref();
730     reverse_service_ = NULL;
731   }
732 }
733
734 ServiceRuntime::~ServiceRuntime() {
735   NaClLog(4, "ServiceRuntime::~ServiceRuntime (this=%p)\n",
736           static_cast<void*>(this));
737   // We do this just in case Shutdown() was not called.
738   subprocess_.reset(NULL);
739   if (reverse_service_ != NULL) {
740     reverse_service_->Unref();
741   }
742
743   rev_interface_->Unref();
744
745   anchor_->Unref();
746   NaClCondVarDtor(&cond_);
747   NaClMutexDtor(&mu_);
748 }
749
750 void ServiceRuntime::set_exit_status(int exit_status) {
751   nacl::MutexLocker take(&mu_);
752   if (main_service_runtime_)
753     plugin_->set_exit_status(exit_status & 0xff);
754 }
755
756 nacl::string ServiceRuntime::GetCrashLogOutput() {
757   if (NULL != subprocess_.get()) {
758     return subprocess_->GetCrashLogOutput();
759   } else {
760     return std::string();
761   }
762 }
763
764 }  // namespace plugin