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.
6 // The portable representation of an instance and root scriptable object.
7 // The PPAPI version of the plugin instantiates a subclass of this class.
9 #ifndef NATIVE_CLIENT_SRC_TRUSTED_PLUGIN_PLUGIN_H_
10 #define NATIVE_CLIENT_SRC_TRUSTED_PLUGIN_PLUGIN_H_
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"
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"
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"
39 class DescWrapperFactory;
47 namespace ppapi_proxy {
56 class ScriptablePlugin;
58 class Plugin : public pp::InstancePrivate {
60 // Factory method for creation.
61 static Plugin* New(PP_Instance instance);
63 // ----- Methods inherited from pp::Instance:
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[]);
70 // Handles document load, when the plugin is a MIME type handler.
71 virtual bool HandleDocumentLoad(const pp::URLLoader& url_loader);
73 // Returns a scriptable reference to this plugin element.
74 // Called by JavaScript document.getElementById(plugin_id).
75 virtual pp::Var GetInstanceObject();
77 // ----- Plugin interface support.
80 // NaCl module can be loaded given a DescWrapper.
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
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.
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);
104 // Finish hooking interfaces up, after low-level initialization is
106 bool LoadNaClModuleContinuationIntern(ErrorInfo* error_info);
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);
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);
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);
129 enum LengthComputable {
130 LENGTH_IS_NOT_COMPUTABLE = 0,
131 LENGTH_IS_COMPUTABLE = 1
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();
142 // Write a text string on the JavaScript console.
143 void AddToConsole(const nacl::string& text);
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);
157 // Report the error code that sel_ldr produces when starting a nexe.
158 void ReportSelLdrLoadStatus(int status);
160 // Report nexe death after load to JS and shut down the proxy.
161 void ReportDeadNexe();
163 // URL resolution support.
164 // plugin_base_url is the URL used for resolving relative URLs used in
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;
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;
182 // The state of readiness of the plugin.
184 // The trusted plugin begins in this ready state.
186 // The manifest file has been requested, but not yet received.
188 // This state is unused.
189 HEADERS_RECEIVED = 2,
190 // The manifest file has been received and the nexe successfully requested.
192 // The nexe has been loaded and the proxy started, so it is ready for
193 // interaction with the page.
196 bool nexe_error_reported() const { return nexe_error_reported_; }
197 void set_nexe_error_reported(bool val) {
198 nexe_error_reported_ = val;
201 nacl::DescWrapperFactory* wrapper_factory() const { return wrapper_factory_; }
203 // Requests a NaCl manifest download from a |url| relative to the page origin.
204 void RequestNaClManifest(const nacl::string& url);
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
209 static const uint64_t kUnknownBytes = 0;
211 // Called back by CallOnMainThread. Dispatches the first enqueued progress
213 void DispatchProgressEvent(int32_t result);
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);
221 // Returns rich information for a file retrieved by StreamAsFile(). This info
222 // contains a file descriptor. The caller must take ownership of this
224 struct NaClFileInfo GetFileInfo(const nacl::string& url);
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);
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);
235 void set_last_error_string(const nacl::string& error);
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_; }
249 Manifest const* manifest() const { return manifest_.get(); }
250 const pp::URLUtil_Dev* url_util() const { return url_util_; }
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);
256 const PPB_NaCl_Private* nacl_interface() const { return nacl_interface_; }
257 pp::UMAPrivate& uma_interface() { return uma_interface_; }
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().
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();
273 ScriptablePlugin* scriptable_plugin() const { return scriptable_plugin_; }
274 void set_scriptable_plugin(ScriptablePlugin* scriptable_plugin) {
275 scriptable_plugin_ = scriptable_plugin;
278 // Access the service runtime for the main NaCl subprocess.
279 ServiceRuntime* main_service_runtime() const {
280 return main_subprocess_.service_runtime();
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,
292 int out_of_range_replacement);
293 void HistogramEnumerateOsArch(const std::string& sandbox_isa);
294 void HistogramEnumerateLoadStatus(PluginErrorCode error_code,
296 void HistogramEnumerateSelLdrLoadStatus(NaClErrorCode error_code,
298 void HistogramEnumerateManifestIsDataURI(bool is_data_uri);
299 void HistogramHTTPStatusCode(const std::string& name, int status);
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);
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,
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);
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);
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);
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.
349 // Callback used when getting the manifest file as a buffer (e.g., data URIs)
350 void NaClManifestBufferReady(int32_t pp_error);
352 // Callback used when getting the manifest file as a local file descriptor.
353 void NaClManifestFileDidOpen(int32_t pp_error);
355 // Processes the JSON manifest string and starts loading the nexe.
356 void ProcessNaClManifest(const nacl::string& manifest_json);
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);
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);
371 // This NEXE is being used as a content type handler rather than directly by
373 bool NexeIsContentHandler() const;
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);
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();
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);
391 void set_nacl_ready_state(ReadyState state);
393 void SetExitStatusOnMainThread(int32_t pp_error, int exit_status);
395 ScriptablePlugin* scriptable_plugin_;
401 // Keep track of the NaCl module subprocess that was spun up in the plugin.
402 NaClSubprocess main_subprocess_;
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
410 nacl::DescWrapperFactory* wrapper_factory_;
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_;
421 nacl::scoped_ptr<PnaclCoordinator> pnacl_coordinator_;
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_;
428 // PPAPI Dev interfaces are disabled by default.
429 bool enable_dev_interfaces_;
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".
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_;
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_;
452 nacl::string mime_type_;
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_;
460 // Pending progress events.
461 std::queue<ProgressEvent*> progress_events_;
463 // Used for NexeFileDidOpenContinuation
470 // Callback to receive .nexe and .dso download progress notifications.
471 static void UpdateDownloadProgress(
472 PP_Instance pp_instance,
473 PP_Resource pp_resource,
475 int64_t total_bytes_to_be_sent,
476 int64_t bytes_received,
477 int64_t total_bytes_to_be_received);
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
482 const FileDownloader* FindFileDownloader(PP_Resource url_loader) const;
484 int64_t time_of_last_progress_event_;
487 const PPB_NaCl_Private* nacl_interface_;
488 pp::UMAPrivate uma_interface_;
491 } // namespace plugin
493 #endif // NATIVE_CLIENT_SRC_TRUSTED_PLUGIN_PLUGIN_H_