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