Don't preload rarely seen large images
[chromium-blink-merge.git] / components / nacl / renderer / nexe_load_manager.cc
blobb7c99689f1a21643db563d48b5b03d3403552cd5
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/nacl/renderer/nexe_load_manager.h"
7 #include "base/command_line.h"
8 #include "base/logging.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string_tokenizer.h"
11 #include "base/strings/string_util.h"
12 #include "components/nacl/common/nacl_host_messages.h"
13 #include "components/nacl/common/nacl_types.h"
14 #include "components/nacl/renderer/histogram.h"
15 #include "components/nacl/renderer/manifest_service_channel.h"
16 #include "components/nacl/renderer/platform_info.h"
17 #include "components/nacl/renderer/pnacl_translation_resource_host.h"
18 #include "components/nacl/renderer/progress_event.h"
19 #include "components/nacl/renderer/trusted_plugin_channel.h"
20 #include "content/public/common/content_client.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/sandbox_init.h"
23 #include "content/public/renderer/pepper_plugin_instance.h"
24 #include "content/public/renderer/render_thread.h"
25 #include "content/public/renderer/render_view.h"
26 #include "content/public/renderer/renderer_ppapi_host.h"
27 #include "ppapi/c/pp_bool.h"
28 #include "ppapi/c/private/pp_file_handle.h"
29 #include "ppapi/shared_impl/ppapi_globals.h"
30 #include "ppapi/shared_impl/ppapi_permissions.h"
31 #include "ppapi/shared_impl/ppapi_preferences.h"
32 #include "ppapi/shared_impl/scoped_pp_var.h"
33 #include "ppapi/shared_impl/var.h"
34 #include "ppapi/shared_impl/var_tracker.h"
35 #include "ppapi/thunk/enter.h"
36 #include "third_party/WebKit/public/web/WebDocument.h"
37 #include "third_party/WebKit/public/web/WebElement.h"
38 #include "third_party/WebKit/public/web/WebPluginContainer.h"
39 #include "third_party/WebKit/public/web/WebView.h"
40 #include "v8/include/v8.h"
42 namespace nacl {
44 namespace {
46 const char* const kTypeAttribute = "type";
47 // The "src" attribute of the <embed> tag. The value is expected to be either
48 // a URL or URI pointing to the manifest file (which is expected to contain
49 // JSON matching ISAs with .nexe URLs).
50 const char* const kSrcManifestAttribute = "src";
51 // The "nacl" attribute of the <embed> tag. We use the value of this attribute
52 // to find the manifest file when NaCl is registered as a plugin for another
53 // MIME type because the "src" attribute is used to supply us with the resource
54 // of that MIME type that we're supposed to display.
55 const char* const kNaClManifestAttribute = "nacl";
56 // Define an argument name to enable 'dev' interfaces. To make sure it doesn't
57 // collide with any user-defined HTML attribute, make the first character '@'.
58 const char* const kDevAttribute = "@dev";
60 const char* const kNaClMIMEType = "application/x-nacl";
61 const char* const kPNaClMIMEType = "application/x-pnacl";
63 static int GetRoutingID(PP_Instance instance) {
64 // Check that we are on the main renderer thread.
65 DCHECK(content::RenderThread::Get());
66 content::RendererPpapiHost *host =
67 content::RendererPpapiHost::GetForPPInstance(instance);
68 if (!host)
69 return 0;
70 return host->GetRoutingIDForWidget(instance);
73 std::string LookupAttribute(const std::map<std::string, std::string>& args,
74 const std::string& key) {
75 std::map<std::string, std::string>::const_iterator it = args.find(key);
76 if (it != args.end())
77 return it->second;
78 return std::string();
81 } // namespace
83 NexeLoadManager::NexeLoadManager(
84 PP_Instance pp_instance)
85 : pp_instance_(pp_instance),
86 nacl_ready_state_(PP_NACL_READY_STATE_UNSENT),
87 nexe_error_reported_(false),
88 is_installed_(false),
89 exit_status_(-1),
90 nexe_size_(0),
91 plugin_instance_(content::PepperPluginInstance::Get(pp_instance)),
92 nonsfi_(false),
93 crash_info_shmem_handle_(base::SharedMemory::NULLHandle()),
94 weak_factory_(this) {
95 set_exit_status(-1);
96 SetLastError("");
97 HistogramEnumerateOsArch(GetSandboxArch());
98 if (plugin_instance_) {
99 plugin_base_url_ =
100 plugin_instance_->GetContainer()->element().document().url();
104 NexeLoadManager::~NexeLoadManager() {
105 if (!nexe_error_reported_) {
106 base::TimeDelta uptime = base::Time::Now() - ready_time_;
107 HistogramTimeLarge("NaCl.ModuleUptime.Normal", uptime.InMilliseconds());
109 if (base::SharedMemory::IsHandleValid(crash_info_shmem_handle_))
110 base::SharedMemory::CloseHandle(crash_info_shmem_handle_);
113 void NexeLoadManager::NexeFileDidOpen(int32_t pp_error,
114 const base::File& file,
115 int32_t http_status,
116 int64_t nexe_bytes_read,
117 const std::string& url,
118 base::TimeDelta time_since_open) {
119 // Check that we are on the main renderer thread.
120 DCHECK(content::RenderThread::Get());
121 VLOG(1) << "Plugin::NexeFileDidOpen (pp_error=" << pp_error << ")";
122 HistogramHTTPStatusCode(
123 is_installed_ ? "NaCl.HttpStatusCodeClass.Nexe.InstalledApp" :
124 "NaCl.HttpStatusCodeClass.Nexe.NotInstalledApp",
125 http_status);
127 if (pp_error != PP_OK || !file.IsValid()) {
128 if (pp_error == PP_ERROR_ABORTED) {
129 ReportLoadAbort();
130 } else if (pp_error == PP_ERROR_NOACCESS) {
131 ReportLoadError(PP_NACL_ERROR_NEXE_NOACCESS_URL,
132 "access to nexe url was denied.");
133 } else {
134 ReportLoadError(PP_NACL_ERROR_NEXE_LOAD_URL,
135 "could not load nexe url.");
137 } else if (nexe_bytes_read == -1) {
138 ReportLoadError(PP_NACL_ERROR_NEXE_STAT, "could not stat nexe file.");
139 } else {
140 // TODO(dmichael): Can we avoid stashing away so much state?
141 nexe_size_ = nexe_bytes_read;
142 HistogramSizeKB("NaCl.Perf.Size.Nexe",
143 static_cast<int32_t>(nexe_size_ / 1024));
144 HistogramStartupTimeMedium(
145 "NaCl.Perf.StartupTime.NexeDownload", time_since_open, nexe_size_);
147 // Inform JavaScript that we successfully downloaded the nacl module.
148 ProgressEvent progress_event(PP_NACL_EVENT_PROGRESS, url, true, nexe_size_,
149 nexe_size_);
150 DispatchProgressEvent(pp_instance_, progress_event);
151 load_start_ = base::Time::Now();
155 void NexeLoadManager::ReportLoadSuccess(const std::string& url,
156 uint64_t loaded_bytes,
157 uint64_t total_bytes) {
158 ready_time_ = base::Time::Now();
159 if (!IsPNaCl()) {
160 base::TimeDelta load_module_time = ready_time_ - load_start_;
161 HistogramStartupTimeSmall(
162 "NaCl.Perf.StartupTime.LoadModule", load_module_time, nexe_size_);
163 HistogramStartupTimeMedium(
164 "NaCl.Perf.StartupTime.Total", ready_time_ - init_time_, nexe_size_);
167 // Check that we are on the main renderer thread.
168 DCHECK(content::RenderThread::Get());
169 set_nacl_ready_state(PP_NACL_READY_STATE_DONE);
171 // Inform JavaScript that loading was successful and is complete.
172 ProgressEvent load_event(PP_NACL_EVENT_LOAD, url, true, loaded_bytes,
173 total_bytes);
174 DispatchProgressEvent(pp_instance_, load_event);
176 ProgressEvent loadend_event(PP_NACL_EVENT_LOADEND, url, true, loaded_bytes,
177 total_bytes);
178 DispatchProgressEvent(pp_instance_, loadend_event);
180 // UMA
181 HistogramEnumerateLoadStatus(PP_NACL_ERROR_LOAD_SUCCESS, is_installed_);
184 void NexeLoadManager::ReportLoadError(PP_NaClError error,
185 const std::string& error_message) {
186 ReportLoadError(error, error_message, error_message);
189 void NexeLoadManager::ReportLoadError(PP_NaClError error,
190 const std::string& error_message,
191 const std::string& console_message) {
192 // Check that we are on the main renderer thread.
193 DCHECK(content::RenderThread::Get());
195 if (error == PP_NACL_ERROR_MANIFEST_PROGRAM_MISSING_ARCH) {
196 // A special case: the manifest may otherwise be valid but is missing
197 // a program/file compatible with the user's sandbox.
198 IPC::Sender* sender = content::RenderThread::Get();
199 sender->Send(
200 new NaClHostMsg_MissingArchError(GetRoutingID(pp_instance_)));
202 set_nacl_ready_state(PP_NACL_READY_STATE_DONE);
203 nexe_error_reported_ = true;
205 // We must set all properties before calling DispatchEvent so that when an
206 // event handler runs, the properties reflect the current load state.
207 std::string error_string = std::string("NaCl module load failed: ") +
208 std::string(error_message);
209 SetLastError(error_string);
211 // Inform JavaScript that loading encountered an error and is complete.
212 DispatchProgressEvent(pp_instance_, ProgressEvent(PP_NACL_EVENT_ERROR));
213 DispatchProgressEvent(pp_instance_, ProgressEvent(PP_NACL_EVENT_LOADEND));
215 HistogramEnumerateLoadStatus(error, is_installed_);
216 LogToConsole(console_message);
219 void NexeLoadManager::ReportLoadAbort() {
220 // Check that we are on the main renderer thread.
221 DCHECK(content::RenderThread::Get());
223 // Set the readyState attribute to indicate we need to start over.
224 set_nacl_ready_state(PP_NACL_READY_STATE_DONE);
225 nexe_error_reported_ = true;
227 // Report an error in lastError and on the JavaScript console.
228 std::string error_string("NaCl module load failed: user aborted");
229 SetLastError(error_string);
231 // Inform JavaScript that loading was aborted and is complete.
232 DispatchProgressEvent(pp_instance_, ProgressEvent(PP_NACL_EVENT_ABORT));
233 DispatchProgressEvent(pp_instance_, ProgressEvent(PP_NACL_EVENT_LOADEND));
235 HistogramEnumerateLoadStatus(PP_NACL_ERROR_LOAD_ABORTED, is_installed_);
236 LogToConsole(error_string);
239 void NexeLoadManager::NexeDidCrash() {
240 VLOG(1) << "Plugin::NexeDidCrash: crash event!";
241 // The NaCl module voluntarily exited. However, this is still a
242 // crash from the point of view of Pepper, since PPAPI plugins are
243 // event handlers and should never exit.
244 VLOG_IF(1, exit_status_ != -1)
245 << "Plugin::NexeDidCrash: nexe exited with status " << exit_status_
246 << " so this is a \"controlled crash\".";
247 // If the crash occurs during load, we just want to report an error
248 // that fits into our load progress event grammar. If the crash
249 // occurs after loaded/loadend, then we use ReportDeadNexe to send a
250 // "crash" event.
251 if (nexe_error_reported_) {
252 VLOG(1) << "Plugin::NexeDidCrash: error already reported; suppressing";
253 } else {
254 if (nacl_ready_state_ == PP_NACL_READY_STATE_DONE) {
255 ReportDeadNexe();
256 } else {
257 ReportLoadError(PP_NACL_ERROR_START_PROXY_CRASH,
258 "Nexe crashed during startup");
261 // In all cases, try to grab the crash log. The first error
262 // reported may have come from the start_module RPC reply indicating
263 // a validation error or something similar, which wouldn't grab the
264 // crash log. In the event that this is called twice, the second
265 // invocation will just be a no-op, since the entire crash log will
266 // have been received and we'll just get an EOF indication.
268 base::SharedMemory shmem(crash_info_shmem_handle_, true);
269 if (shmem.Map(kNaClCrashInfoShmemSize)) {
270 uint32_t crash_log_length;
271 // We cast the length value to volatile here to prevent the compiler from
272 // reordering instructions in a way that could introduce a TOCTTOU race.
273 crash_log_length = *(static_cast<volatile uint32_t*>(shmem.memory()));
274 crash_log_length = std::min<uint32_t>(crash_log_length,
275 kNaClCrashInfoMaxLogSize);
277 scoped_ptr<char[]> crash_log_data(new char[kNaClCrashInfoShmemSize]);
278 memcpy(crash_log_data.get(),
279 static_cast<char*>(shmem.memory()) + sizeof(uint32_t),
280 crash_log_length);
281 std::string crash_log(crash_log_data.get(), crash_log_length);
282 CopyCrashLogToJsConsole(crash_log);
286 void NexeLoadManager::set_trusted_plugin_channel(
287 scoped_ptr<TrustedPluginChannel> channel) {
288 trusted_plugin_channel_ = channel.Pass();
291 void NexeLoadManager::set_manifest_service_channel(
292 scoped_ptr<ManifestServiceChannel> channel) {
293 manifest_service_channel_ = channel.Pass();
296 PP_NaClReadyState NexeLoadManager::nacl_ready_state() {
297 return nacl_ready_state_;
300 void NexeLoadManager::set_nacl_ready_state(PP_NaClReadyState ready_state) {
301 nacl_ready_state_ = ready_state;
302 ppapi::ScopedPPVar ready_state_name(
303 ppapi::ScopedPPVar::PassRef(),
304 ppapi::StringVar::StringToPPVar("readyState"));
305 SetReadOnlyProperty(ready_state_name.get(), PP_MakeInt32(ready_state));
308 void NexeLoadManager::SetLastError(const std::string& error) {
309 ppapi::ScopedPPVar error_name_var(
310 ppapi::ScopedPPVar::PassRef(),
311 ppapi::StringVar::StringToPPVar("lastError"));
312 ppapi::ScopedPPVar error_var(
313 ppapi::ScopedPPVar::PassRef(),
314 ppapi::StringVar::StringToPPVar(error));
315 SetReadOnlyProperty(error_name_var.get(), error_var.get());
318 void NexeLoadManager::SetReadOnlyProperty(PP_Var key, PP_Var value) {
319 plugin_instance_->SetEmbedProperty(key, value);
322 void NexeLoadManager::LogToConsole(const std::string& message) {
323 ppapi::PpapiGlobals::Get()->LogWithSource(
324 pp_instance_, PP_LOGLEVEL_LOG, std::string("NativeClient"), message);
327 void NexeLoadManager::set_exit_status(int exit_status) {
328 exit_status_ = exit_status;
329 ppapi::ScopedPPVar exit_status_name_var(
330 ppapi::ScopedPPVar::PassRef(),
331 ppapi::StringVar::StringToPPVar("exitStatus"));
332 SetReadOnlyProperty(exit_status_name_var.get(), PP_MakeInt32(exit_status));
335 void NexeLoadManager::InitializePlugin(
336 uint32_t argc, const char* argn[], const char* argv[]) {
337 init_time_ = base::Time::Now();
339 for (size_t i = 0; i < argc; ++i) {
340 std::string name(argn[i]);
341 std::string value(argv[i]);
342 args_[name] = value;
345 // Store mime_type_ at initialization time since we make it lowercase.
346 mime_type_ = base::StringToLowerASCII(LookupAttribute(args_, kTypeAttribute));
349 void NexeLoadManager::ReportStartupOverhead() const {
350 base::TimeDelta overhead = base::Time::Now() - init_time_;
351 HistogramStartupTimeMedium(
352 "NaCl.Perf.StartupTime.NaClOverhead", overhead, nexe_size_);
355 bool NexeLoadManager::RequestNaClManifest(const std::string& url) {
356 if (plugin_base_url_.is_valid()) {
357 const GURL& resolved_url = plugin_base_url_.Resolve(url);
358 if (resolved_url.is_valid()) {
359 manifest_base_url_ = resolved_url;
360 is_installed_ = manifest_base_url_.SchemeIs("chrome-extension");
361 HistogramEnumerateManifestIsDataURI(
362 manifest_base_url_.SchemeIs("data"));
363 set_nacl_ready_state(PP_NACL_READY_STATE_OPENED);
364 DispatchProgressEvent(pp_instance_,
365 ProgressEvent(PP_NACL_EVENT_LOADSTART));
366 return true;
369 ReportLoadError(PP_NACL_ERROR_MANIFEST_RESOLVE_URL,
370 std::string("could not resolve URL \"") + url +
371 "\" relative to \"" +
372 plugin_base_url_.possibly_invalid_spec() + "\".");
373 return false;
376 void NexeLoadManager::ProcessNaClManifest(const std::string& program_url) {
377 program_url_ = program_url;
378 GURL gurl(program_url);
379 DCHECK(gurl.is_valid());
380 if (gurl.is_valid())
381 is_installed_ = gurl.SchemeIs("chrome-extension");
382 set_nacl_ready_state(PP_NACL_READY_STATE_LOADING);
383 DispatchProgressEvent(pp_instance_, ProgressEvent(PP_NACL_EVENT_PROGRESS));
386 std::string NexeLoadManager::GetManifestURLArgument() const {
387 std::string manifest_url;
389 // If the MIME type is foreign, then this NEXE is being used as a content
390 // type handler rather than directly by an HTML document.
391 bool nexe_is_content_handler =
392 !mime_type_.empty() &&
393 mime_type_ != kNaClMIMEType &&
394 mime_type_ != kPNaClMIMEType;
396 if (nexe_is_content_handler) {
397 // For content handlers 'src' will be the URL for the content
398 // and 'nacl' will be the URL for the manifest.
399 manifest_url = LookupAttribute(args_, kNaClManifestAttribute);
400 } else {
401 manifest_url = LookupAttribute(args_, kSrcManifestAttribute);
404 if (manifest_url.empty()) {
405 VLOG(1) << "WARNING: no 'src' property, so no manifest loaded.";
406 if (args_.find(kNaClManifestAttribute) != args_.end())
407 VLOG(1) << "WARNING: 'nacl' property is incorrect. Use 'src'.";
409 return manifest_url;
412 bool NexeLoadManager::IsPNaCl() const {
413 return mime_type_ == kPNaClMIMEType;
416 bool NexeLoadManager::DevInterfacesEnabled() const {
417 // Look for the developer attribute; if it's present, enable 'dev'
418 // interfaces.
419 return args_.find(kDevAttribute) != args_.end();
422 void NexeLoadManager::ReportDeadNexe() {
423 if (nacl_ready_state_ == PP_NACL_READY_STATE_DONE && // After loadEnd
424 !nexe_error_reported_) {
425 // Crashes will be more likely near startup, so use a medium histogram
426 // instead of a large one.
427 base::TimeDelta uptime = base::Time::Now() - ready_time_;
428 HistogramTimeMedium("NaCl.ModuleUptime.Crash", uptime.InMilliseconds());
430 std::string message("NaCl module crashed");
431 SetLastError(message);
432 LogToConsole(message);
434 DispatchProgressEvent(pp_instance_, ProgressEvent(PP_NACL_EVENT_CRASH));
435 nexe_error_reported_ = true;
437 // else ReportLoadError() and ReportLoadAbort() will be used by loading code
438 // to provide error handling.
441 void NexeLoadManager::CopyCrashLogToJsConsole(const std::string& crash_log) {
442 base::StringTokenizer t(crash_log, "\n");
443 while (t.GetNext())
444 LogToConsole(t.token());
447 } // namespace nacl