Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / ppapi / native_client / src / trusted / plugin / plugin.h
1 // -*- c++ -*-
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 // The portable representation of an instance and root scriptable object.
7 // The PPAPI version of the plugin instantiates a subclass of this class.
8
9 #ifndef NATIVE_CLIENT_SRC_TRUSTED_PLUGIN_PLUGIN_H_
10 #define NATIVE_CLIENT_SRC_TRUSTED_PLUGIN_PLUGIN_H_
11
12 #include <stdio.h>
13
14 #include <map>
15 #include <queue>
16 #include <set>
17 #include <string>
18
19 #include "native_client/src/include/nacl_macros.h"
20 #include "native_client/src/include/nacl_scoped_ptr.h"
21 #include "native_client/src/include/nacl_string.h"
22 #include "native_client/src/trusted/validator/nacl_file_info.h"
23
24 #include "ppapi/c/private/ppb_nacl_private.h"
25 #include "ppapi/cpp/private/instance_private.h"
26 #include "ppapi/cpp/private/uma_private.h"
27 #include "ppapi/cpp/url_loader.h"
28 #include "ppapi/cpp/var.h"
29 #include "ppapi/cpp/view.h"
30
31 #include "ppapi/native_client/src/trusted/plugin/file_downloader.h"
32 #include "ppapi/native_client/src/trusted/plugin/nacl_subprocess.h"
33 #include "ppapi/native_client/src/trusted/plugin/pnacl_coordinator.h"
34 #include "ppapi/native_client/src/trusted/plugin/service_runtime.h"
35 #include "ppapi/native_client/src/trusted/plugin/utility.h"
36
37 namespace nacl {
38 class DescWrapper;
39 class DescWrapperFactory;
40 }  // namespace nacl
41
42 namespace pp {
43 class URLLoader;
44 class URLUtil_Dev;
45 }
46
47 namespace ppapi_proxy {
48 class BrowserPpp;
49 }
50
51 namespace plugin {
52
53 class ErrorInfo;
54 class Manifest;
55 class ProgressEvent;
56 class ScriptablePlugin;
57
58 class Plugin : public pp::InstancePrivate {
59  public:
60   // Factory method for creation.
61   static Plugin* New(PP_Instance instance);
62
63   // ----- Methods inherited from pp::Instance:
64
65   // Initializes this plugin with <embed/object ...> tag attribute count |argc|,
66   // names |argn| and values |argn|. Returns false on failure.
67   // Gets called by the browser right after New().
68   virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]);
69
70   // Handles document load, when the plugin is a MIME type handler.
71   virtual bool HandleDocumentLoad(const pp::URLLoader& url_loader);
72
73   // Returns a scriptable reference to this plugin element.
74   // Called by JavaScript document.getElementById(plugin_id).
75   virtual pp::Var GetInstanceObject();
76
77   // ----- Plugin interface support.
78
79   // Load support.
80   // NaCl module can be loaded given a DescWrapper.
81   //
82   // Starts NaCl module but does not wait until low-level
83   // initialization (e.g., ld.so dynamic loading of manifest files) is
84   // done.  The module will become ready later, asynchronously.  Other
85   // event handlers should block until the module is ready before
86   // trying to communicate with it, i.e., until nacl_ready_state is
87   // DONE.
88   //
89   // NB: currently we do not time out, so if the untrusted code
90   // does not signal that it is ready, then we will deadlock the main
91   // thread of the renderer on this subsequent event delivery.  We
92   // should include a time-out at which point we declare the
93   // nacl_ready_state to be done, and let the normal crash detection
94   // mechanism(s) take over.
95   //
96   // Updates nacl_module_origin() and nacl_module_url().
97   bool LoadNaClModule(nacl::DescWrapper* wrapper, ErrorInfo* error_info,
98                       bool enable_dyncode_syscalls,
99                       bool enable_exception_handling,
100                       bool enable_crash_throttling,
101                       const pp::CompletionCallback& init_done_cb,
102                       const pp::CompletionCallback& crash_cb);
103
104   // Finish hooking interfaces up, after low-level initialization is
105   // complete.
106   bool LoadNaClModuleContinuationIntern(ErrorInfo* error_info);
107
108   // Continuation for starting SRPC/JSProxy services as appropriate.
109   // This is invoked as a callback when the NaCl module makes the
110   // init_done reverse RPC to tell us that low-level initialization
111   // such as ld.so processing is done.  That initialization requires
112   // that the main thread be free in order to do Pepper
113   // main-thread-only operations such as file processing.
114   bool LoadNaClModuleContinuation(int32_t pp_error);
115
116   // Load support.
117   // A helper SRPC NaCl module can be loaded given a DescWrapper.
118   // Blocks until the helper module signals initialization is done.
119   // Does not update nacl_module_origin().
120   // Returns NULL or the NaClSubprocess of the new helper NaCl module.
121   NaClSubprocess* LoadHelperNaClModule(nacl::DescWrapper* wrapper,
122                                        const Manifest* manifest,
123                                        ErrorInfo* error_info);
124
125   // Returns the argument value for the specified key, or NULL if not found.
126   // The callee retains ownership of the result.
127   char* LookupArgument(const char* key);
128
129   enum LengthComputable {
130     LENGTH_IS_NOT_COMPUTABLE = 0,
131     LENGTH_IS_COMPUTABLE = 1
132   };
133   // Report successful loading of a module.
134   void ReportLoadSuccess(LengthComputable length_computable,
135                          uint64_t loaded_bytes,
136                          uint64_t total_bytes);
137   // Report an error that was encountered while loading a module.
138   void ReportLoadError(const ErrorInfo& error_info);
139   // Report loading a module was aborted, typically due to user action.
140   void ReportLoadAbort();
141
142   // Write a text string on the JavaScript console.
143   void AddToConsole(const nacl::string& text);
144
145   // Dispatch a JavaScript event to indicate a key step in loading.
146   // |event_type| is a character string indicating which type of progress
147   // event (loadstart, progress, error, abort, load, loadend).  Events are
148   // enqueued on the JavaScript event loop, which then calls back through
149   // DispatchProgressEvent.
150   void EnqueueProgressEvent(PP_NaClEventType event_type);
151   void EnqueueProgressEvent(PP_NaClEventType event_type,
152                             const nacl::string& url,
153                             LengthComputable length_computable,
154                             uint64_t loaded_bytes,
155                             uint64_t total_bytes);
156
157   // Report the error code that sel_ldr produces when starting a nexe.
158   void ReportSelLdrLoadStatus(int status);
159
160   // Report nexe death after load to JS and shut down the proxy.
161   void ReportDeadNexe();
162
163   // URL resolution support.
164   // plugin_base_url is the URL used for resolving relative URLs used in
165   // src="...".
166   nacl::string plugin_base_url() const { return plugin_base_url_; }
167   void set_plugin_base_url(const nacl::string& url) { plugin_base_url_ = url; }
168   // manifest_base_url is the URL used for resolving relative URLs mentioned
169   // in manifest files.  If the manifest is a data URI, this is an empty string.
170   nacl::string manifest_base_url() const { return manifest_base_url_; }
171   void set_manifest_base_url(const nacl::string& url) {
172     manifest_base_url_ = url;
173   }
174
175   // The URL of the manifest file as set by the "src" attribute.
176   // It is not the fully resolved URL if it was set as relative.
177   const nacl::string& manifest_url() const { return manifest_url_; }
178   void set_manifest_url(const nacl::string& manifest_url) {
179     manifest_url_ = manifest_url;
180   }
181
182   // The state of readiness of the plugin.
183   enum ReadyState {
184     // The trusted plugin begins in this ready state.
185     UNSENT = 0,
186     // The manifest file has been requested, but not yet received.
187     OPENED = 1,
188     // This state is unused.
189     HEADERS_RECEIVED = 2,
190     // The manifest file has been received and the nexe successfully requested.
191     LOADING = 3,
192     // The nexe has been loaded and the proxy started, so it is ready for
193     // interaction with the page.
194     DONE = 4
195   };
196   bool nexe_error_reported() const { return nexe_error_reported_; }
197   void set_nexe_error_reported(bool val) {
198     nexe_error_reported_ = val;
199   }
200
201   nacl::DescWrapperFactory* wrapper_factory() const { return wrapper_factory_; }
202
203   // Requests a NaCl manifest download from a |url| relative to the page origin.
204   void RequestNaClManifest(const nacl::string& url);
205
206   // The size returned when a file download operation is unable to determine
207   // the size of the file to load.  W3C ProgressEvents specify that unknown
208   // sizes return 0.
209   static const uint64_t kUnknownBytes = 0;
210
211   // Called back by CallOnMainThread.  Dispatches the first enqueued progress
212   // event.
213   void DispatchProgressEvent(int32_t result);
214
215   // Requests a URL asynchronously resulting in a call to pp_callback with
216   // a PP_Error indicating status. On success an open file descriptor
217   // corresponding to the url body is recorded for further lookup.
218   bool StreamAsFile(const nacl::string& url,
219                     PP_CompletionCallback pp_callback);
220
221   // Returns rich information for a file retrieved by StreamAsFile(). This info
222   // contains a file descriptor. The caller must take ownership of this
223   // descriptor.
224   struct NaClFileInfo GetFileInfo(const nacl::string& url);
225
226   // A helper function that gets the scheme type for |url|. Uses URLUtil_Dev
227   // interface which this class has as a member.
228   UrlSchemeType GetUrlScheme(const std::string& url);
229
230   // A helper function that indicates if |url| can be requested by the document
231   // under the same-origin policy. Strictly speaking, it may be possible for the
232   // document to request the URL using CORS even if this function returns false.
233   bool DocumentCanRequest(const std::string& url);
234
235   void set_last_error_string(const nacl::string& error);
236
237   // The MIME type used to instantiate this instance of the NaCl plugin.
238   // Typically, the MIME type will be application/x-nacl.  However, if the NEXE
239   // is being used as a content type handler for another content type (such as
240   // PDF), then this function will return that type.
241   const nacl::string& mime_type() const { return mime_type_; }
242   // The default MIME type for the NaCl plugin.
243   static const char* const kNaClMIMEType;
244   // The MIME type for the plugin when using PNaCl.
245   static const char* const kPnaclMIMEType;
246   // Returns true if PPAPI Dev interfaces should be allowed.
247   bool enable_dev_interfaces() { return enable_dev_interfaces_; }
248
249   Manifest const* manifest() const { return manifest_.get(); }
250   const pp::URLUtil_Dev* url_util() const { return url_util_; }
251
252   int exit_status() const { return exit_status_; }
253   // set_exit_status may be called off the main thread.
254   void set_exit_status(int exit_status);
255
256   const PPB_NaCl_Private* nacl_interface() const { return nacl_interface_; }
257   pp::UMAPrivate& uma_interface() { return uma_interface_; }
258
259  private:
260   NACL_DISALLOW_COPY_AND_ASSIGN(Plugin);
261   // Prevent construction and destruction from outside the class:
262   // must use factory New() method instead.
263   explicit Plugin(PP_Instance instance);
264   // The browser will invoke the destructor via the pp::Instance
265   // pointer to this object, not from base's Delete().
266   ~Plugin();
267
268   bool EarlyInit(int argc, const char* argn[], const char* argv[]);
269   // Shuts down socket connection, service runtime, and receive thread,
270   // in this order, for the main nacl subprocess.
271   void ShutDownSubprocesses();
272
273   ScriptablePlugin* scriptable_plugin() const { return scriptable_plugin_; }
274   void set_scriptable_plugin(ScriptablePlugin* scriptable_plugin) {
275     scriptable_plugin_ = scriptable_plugin;
276   }
277
278   // Access the service runtime for the main NaCl subprocess.
279   ServiceRuntime* main_service_runtime() const {
280     return main_subprocess_.service_runtime();
281   }
282
283   // Histogram helper functions, internal to Plugin so they can use
284   // uma_interface_ normally.
285   void HistogramTimeSmall(const std::string& name, int64_t ms);
286   void HistogramTimeMedium(const std::string& name, int64_t ms);
287   void HistogramTimeLarge(const std::string& name, int64_t ms);
288   void HistogramSizeKB(const std::string& name, int32_t sample);
289   void HistogramEnumerate(const std::string& name,
290                           int sample,
291                           int maximum,
292                           int out_of_range_replacement);
293   void HistogramEnumerateOsArch(const std::string& sandbox_isa);
294   void HistogramEnumerateLoadStatus(PluginErrorCode error_code,
295                                     bool is_installed);
296   void HistogramEnumerateSelLdrLoadStatus(NaClErrorCode error_code,
297                                           bool is_installed);
298   void HistogramEnumerateManifestIsDataURI(bool is_data_uri);
299   void HistogramHTTPStatusCode(const std::string& name, int status);
300
301   // Help load a nacl module, from the file specified in wrapper.
302   // This will fully initialize the |subprocess| if the load was successful.
303   bool LoadNaClModuleCommon(nacl::DescWrapper* wrapper,
304                             NaClSubprocess* subprocess,
305                             const Manifest* manifest,
306                             bool should_report_uma,
307                             const SelLdrStartParams& params,
308                             const pp::CompletionCallback& init_done_cb,
309                             const pp::CompletionCallback& crash_cb);
310
311   // Start sel_ldr from the main thread, given the start params.
312   // Sets |success| to true on success.
313   // |pp_error| is set by CallOnMainThread (should be PP_OK).
314   void StartSelLdrOnMainThread(int32_t pp_error,
315                                ServiceRuntime* service_runtime,
316                                const SelLdrStartParams& params,
317                                bool* success);
318
319   // Callback used when getting the URL for the .nexe file.  If the URL loading
320   // is successful, the file descriptor is opened and can be passed to sel_ldr
321   // with the sandbox on.
322   void NexeFileDidOpen(int32_t pp_error);
323   void NexeFileDidOpenContinuation(int32_t pp_error);
324
325   // Callback used when the reverse channel closes.  This is an
326   // asynchronous event that might turn into a JavaScript error or
327   // crash event -- this is controlled by the two state variables
328   // nacl_ready_state_ and nexe_error_reported_: If an error or crash
329   // had already been reported, no additional crash event is
330   // generated.  If no error has been reported but nacl_ready_state_
331   // is not DONE, then the loadend event has not been reported, and we
332   // enqueue an error event followed by loadend.  If nacl_ready_state_
333   // is DONE, then we are in the post-loadend (we need temporal
334   // predicate symbols), and we enqueue a crash event.
335   void NexeDidCrash(int32_t pp_error);
336
337   // Callback used when a .nexe is translated from bitcode.  If the translation
338   // is successful, the file descriptor is opened and can be passed to sel_ldr
339   // with the sandbox on.
340   void BitcodeDidTranslate(int32_t pp_error);
341   void BitcodeDidTranslateContinuation(int32_t pp_error);
342
343   // NaCl ISA selection manifest file support.  The manifest file is specified
344   // using the "nacl" attribute in the <embed> tag.  First, the manifest URL (or
345   // data: URI) is fetched, then the JSON is parsed.  Once a valid .nexe is
346   // chosen for the sandbox ISA, any current service runtime is shut down, the
347   // .nexe is loaded and run.
348
349   // Callback used when getting the manifest file as a buffer (e.g., data URIs)
350   void NaClManifestBufferReady(int32_t pp_error);
351
352   // Callback used when getting the manifest file as a local file descriptor.
353   void NaClManifestFileDidOpen(int32_t pp_error);
354
355   // Processes the JSON manifest string and starts loading the nexe.
356   void ProcessNaClManifest(const nacl::string& manifest_json);
357
358   // Parses the JSON in |manifest_json| and retains a Manifest in
359   // |manifest_| for use by subsequent resource lookups.
360   // On success, |true| is returned and |manifest_| is updated to
361   // contain a Manifest that is used by SelectNexeURLFromManifest.
362   // On failure, |false| is returned, and |manifest_| is unchanged.
363   bool SetManifestObject(const nacl::string& manifest_json,
364                          ErrorInfo* error_info);
365
366   // Logs timing information to a UMA histogram, and also logs the same timing
367   // information divided by the size of the nexe to another histogram.
368   void HistogramStartupTimeSmall(const std::string& name, float dt);
369   void HistogramStartupTimeMedium(const std::string& name, float dt);
370
371   // This NEXE is being used as a content type handler rather than directly by
372   // an HTML document.
373   bool NexeIsContentHandler() const;
374
375   // Callback used when loading a URL for SRPC-based StreamAsFile().
376   void UrlDidOpenForStreamAsFile(int32_t pp_error,
377                                  FileDownloader*& url_downloader,
378                                  PP_CompletionCallback pp_callback);
379
380   // Copy the main service runtime's most recent NaClLog output to the
381   // JavaScript console.  Valid to use only after a crash, e.g., via a
382   // detail level LOG_FATAL NaClLog entry.  If the crash was not due
383   // to a LOG_FATAL this method will do nothing.
384   void CopyCrashLogToJsConsole();
385
386   // Open an app file by requesting a file descriptor from the browser. This
387   // method first checks that the url is for an installed file before making the
388   // request so it won't slow down non-installed file downloads.
389   bool OpenURLFast(const nacl::string& url, FileDownloader* downloader);
390
391   void set_nacl_ready_state(ReadyState state);
392
393   void SetExitStatusOnMainThread(int32_t pp_error, int exit_status);
394
395   ScriptablePlugin* scriptable_plugin_;
396
397   int argc_;
398   char** argn_;
399   char** argv_;
400
401   // Keep track of the NaCl module subprocess that was spun up in the plugin.
402   NaClSubprocess main_subprocess_;
403
404   nacl::string plugin_base_url_;
405   nacl::string manifest_base_url_;
406   nacl::string manifest_url_;
407   ReadyState nacl_ready_state_;
408   bool nexe_error_reported_;  // error or crash reported
409
410   nacl::DescWrapperFactory* wrapper_factory_;
411
412   // File download support.  |nexe_downloader_| can be opened with a specific
413   // callback to run when the file has been downloaded and is opened for
414   // reading.  We use one downloader for all URL downloads to prevent issuing
415   // multiple GETs that might arrive out of order.  For example, this will
416   // prevent a GET of a NaCl manifest while a .nexe GET is pending.  Note that
417   // this will also prevent simultaneous handling of multiple .nexes on a page.
418   FileDownloader nexe_downloader_;
419   pp::CompletionCallbackFactory<Plugin> callback_factory_;
420
421   nacl::scoped_ptr<PnaclCoordinator> pnacl_coordinator_;
422
423   // The manifest dictionary.  Used for looking up resources to be loaded.
424   nacl::scoped_ptr<Manifest> manifest_;
425   // URL processing interface for use in looking up resources in manifests.
426   const pp::URLUtil_Dev* url_util_;
427
428   // PPAPI Dev interfaces are disabled by default.
429   bool enable_dev_interfaces_;
430
431   // A flag indicating if the NaCl executable is being loaded from an installed
432   // application.  This flag is used to bucket UMA statistics more precisely to
433   // help determine whether nexe loading problems are caused by networking
434   // issues.  (Installed applications will be loaded from disk.)
435   // Unfortunately, the definition of what it means to be part of an installed
436   // application is a little murky - for example an installed application can
437   // register a mime handler that loads NaCl executables into an arbitrary web
438   // page.  As such, the flag actually means "our best guess, based on the URLs
439   // for NaCl resources that we have seen so far".
440   bool is_installed_;
441
442   // If we get a DidChangeView event before the nexe is loaded, we store it and
443   // replay it to nexe after it's loaded. We need to replay when this View
444   // resource is non-is_null().
445   pp::View view_to_replay_;
446
447   // If we get a HandleDocumentLoad event before the nexe is loaded, we store
448   // it and replay it to nexe after it's loaded. We need to replay when this
449   // URLLoader resource is non-is_null().
450   pp::URLLoader document_load_to_replay_;
451
452   nacl::string mime_type_;
453
454   // Keep track of the FileDownloaders created to fetch urls.
455   std::set<FileDownloader*> url_downloaders_;
456   // Keep track of file descriptors opened by StreamAsFile().
457   // These are owned by the browser.
458   std::map<nacl::string, struct NaClFileInfo> url_file_info_map_;
459
460   // Pending progress events.
461   std::queue<ProgressEvent*> progress_events_;
462
463   // Used for NexeFileDidOpenContinuation
464   int64_t load_start_;
465
466   int64_t init_time_;
467   int64_t ready_time_;
468   size_t nexe_size_;
469
470   // Callback to receive .nexe and .dso download progress notifications.
471   static void UpdateDownloadProgress(
472       PP_Instance pp_instance,
473       PP_Resource pp_resource,
474       int64_t bytes_sent,
475       int64_t total_bytes_to_be_sent,
476       int64_t bytes_received,
477       int64_t total_bytes_to_be_received);
478
479   // Finds the file downloader which owns the given URL loader. This is used
480   // in UpdateDownloadProgress to map a url loader back to the URL being
481   // downloaded.
482   const FileDownloader* FindFileDownloader(PP_Resource url_loader) const;
483
484   int64_t time_of_last_progress_event_;
485   int exit_status_;
486
487   const PPB_NaCl_Private* nacl_interface_;
488   pp::UMAPrivate uma_interface_;
489 };
490
491 }  // namespace plugin
492
493 #endif  // NATIVE_CLIENT_SRC_TRUSTED_PLUGIN_PLUGIN_H_