QUIC - cleanup changes to sync chromium tree with internal source.
[chromium-blink-merge.git] / components / nacl / renderer / ppb_nacl_private_impl.cc
blobdde4ef85bff3ab4a546d63aa2d221f83cace3252
1 // Copyright 2013 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/ppb_nacl_private_impl.h"
7 #include <numeric>
8 #include <string>
9 #include <vector>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/containers/scoped_ptr_hash_map.h"
15 #include "base/cpu.h"
16 #include "base/files/file.h"
17 #include "base/json/json_reader.h"
18 #include "base/lazy_instance.h"
19 #include "base/location.h"
20 #include "base/logging.h"
21 #include "base/rand_util.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/strings/string_split.h"
24 #include "base/strings/string_util.h"
25 #include "base/thread_task_runner_handle.h"
26 #include "components/nacl/common/nacl_host_messages.h"
27 #include "components/nacl/common/nacl_messages.h"
28 #include "components/nacl/common/nacl_nonsfi_util.h"
29 #include "components/nacl/common/nacl_switches.h"
30 #include "components/nacl/common/nacl_types.h"
31 #include "components/nacl/renderer/file_downloader.h"
32 #include "components/nacl/renderer/histogram.h"
33 #include "components/nacl/renderer/json_manifest.h"
34 #include "components/nacl/renderer/manifest_downloader.h"
35 #include "components/nacl/renderer/manifest_service_channel.h"
36 #include "components/nacl/renderer/nexe_load_manager.h"
37 #include "components/nacl/renderer/platform_info.h"
38 #include "components/nacl/renderer/pnacl_translation_resource_host.h"
39 #include "components/nacl/renderer/progress_event.h"
40 #include "components/nacl/renderer/trusted_plugin_channel.h"
41 #include "content/public/common/content_client.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/sandbox_init.h"
44 #include "content/public/renderer/pepper_plugin_instance.h"
45 #include "content/public/renderer/render_thread.h"
46 #include "content/public/renderer/render_view.h"
47 #include "content/public/renderer/renderer_ppapi_host.h"
48 #include "native_client/src/public/imc_types.h"
49 #include "net/base/data_url.h"
50 #include "net/base/net_errors.h"
51 #include "net/http/http_util.h"
52 #include "ppapi/c/pp_bool.h"
53 #include "ppapi/c/private/pp_file_handle.h"
54 #include "ppapi/shared_impl/ppapi_globals.h"
55 #include "ppapi/shared_impl/ppapi_permissions.h"
56 #include "ppapi/shared_impl/ppapi_preferences.h"
57 #include "ppapi/shared_impl/var.h"
58 #include "ppapi/shared_impl/var_tracker.h"
59 #include "ppapi/thunk/enter.h"
60 #include "third_party/WebKit/public/platform/WebURLLoader.h"
61 #include "third_party/WebKit/public/platform/WebURLResponse.h"
62 #include "third_party/WebKit/public/web/WebDocument.h"
63 #include "third_party/WebKit/public/web/WebElement.h"
64 #include "third_party/WebKit/public/web/WebLocalFrame.h"
65 #include "third_party/WebKit/public/web/WebPluginContainer.h"
66 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
67 #include "third_party/WebKit/public/web/WebURLLoaderOptions.h"
69 namespace nacl {
70 namespace {
72 // The pseudo-architecture used to indicate portable native client.
73 const char* const kPortableArch = "portable";
75 // The base URL for resources used by the PNaCl translator processes.
76 const char* kPNaClTranslatorBaseUrl = "chrome://pnacl-translator/";
78 base::LazyInstance<scoped_refptr<PnaclTranslationResourceHost> >
79 g_pnacl_resource_host = LAZY_INSTANCE_INITIALIZER;
81 bool InitializePnaclResourceHost() {
82 // Must run on the main thread.
83 content::RenderThread* render_thread = content::RenderThread::Get();
84 if (!render_thread)
85 return false;
86 if (!g_pnacl_resource_host.Get().get()) {
87 g_pnacl_resource_host.Get() = new PnaclTranslationResourceHost(
88 render_thread->GetIOMessageLoopProxy());
89 render_thread->AddFilter(g_pnacl_resource_host.Get().get());
91 return true;
94 bool CanOpenViaFastPath(content::PepperPluginInstance* plugin_instance,
95 const GURL& gurl) {
96 // Fast path only works for installed file URLs.
97 if (!gurl.SchemeIs("chrome-extension"))
98 return PP_kInvalidFileHandle;
100 // IMPORTANT: Make sure the document can request the given URL. If we don't
101 // check, a malicious app could probe the extension system. This enforces a
102 // same-origin policy which prevents the app from requesting resources from
103 // another app.
104 blink::WebSecurityOrigin security_origin =
105 plugin_instance->GetContainer()->element().document().securityOrigin();
106 return security_origin.canRequest(gurl);
109 // This contains state that is produced by LaunchSelLdr() and consumed
110 // by StartPpapiProxy().
111 struct InstanceInfo {
112 InstanceInfo() : plugin_pid(base::kNullProcessId), plugin_child_id(0) {}
113 GURL url;
114 ppapi::PpapiPermissions permissions;
115 base::ProcessId plugin_pid;
116 int plugin_child_id;
117 IPC::ChannelHandle channel_handle;
120 class NaClPluginInstance {
121 public:
122 NaClPluginInstance(PP_Instance instance):
123 nexe_load_manager(instance), pexe_size(0) {}
125 NexeLoadManager nexe_load_manager;
126 scoped_ptr<JsonManifest> json_manifest;
127 scoped_ptr<InstanceInfo> instance_info;
129 // When translation is complete, this records the size of the pexe in
130 // bytes so that it can be reported in a later load event.
131 uint64_t pexe_size;
134 typedef base::ScopedPtrHashMap<PP_Instance, scoped_ptr<NaClPluginInstance>>
135 InstanceMap;
136 base::LazyInstance<InstanceMap> g_instance_map = LAZY_INSTANCE_INITIALIZER;
138 NaClPluginInstance* GetNaClPluginInstance(PP_Instance instance) {
139 InstanceMap& map = g_instance_map.Get();
140 InstanceMap::iterator iter = map.find(instance);
141 if (iter == map.end())
142 return NULL;
143 return iter->second;
146 NexeLoadManager* GetNexeLoadManager(PP_Instance instance) {
147 NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
148 if (!nacl_plugin_instance)
149 return NULL;
150 return &nacl_plugin_instance->nexe_load_manager;
153 JsonManifest* GetJsonManifest(PP_Instance instance) {
154 NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
155 if (!nacl_plugin_instance)
156 return NULL;
157 return nacl_plugin_instance->json_manifest.get();
160 static const PP_NaClFileInfo kInvalidNaClFileInfo = {
161 PP_kInvalidFileHandle,
162 0, // token_lo
163 0, // token_hi
166 int GetRoutingID(PP_Instance instance) {
167 // Check that we are on the main renderer thread.
168 DCHECK(content::RenderThread::Get());
169 content::RendererPpapiHost* host =
170 content::RendererPpapiHost::GetForPPInstance(instance);
171 if (!host)
172 return 0;
173 return host->GetRoutingIDForWidget(instance);
176 // Returns whether the channel_handle is valid or not.
177 bool IsValidChannelHandle(const IPC::ChannelHandle& channel_handle) {
178 if (channel_handle.name.empty()) {
179 return false;
182 #if defined(OS_POSIX)
183 if (channel_handle.socket.fd == -1) {
184 return false;
186 #endif
188 return true;
191 void PostPPCompletionCallback(PP_CompletionCallback callback,
192 int32_t status) {
193 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
194 FROM_HERE,
195 base::Bind(callback.func, callback.user_data, status));
198 bool ManifestResolveKey(PP_Instance instance,
199 bool is_helper_process,
200 const std::string& key,
201 std::string* full_url,
202 PP_PNaClOptions* pnacl_options);
204 typedef base::Callback<void(int32_t, const PP_NaClFileInfo&)>
205 DownloadFileCallback;
207 void DownloadFile(PP_Instance instance,
208 const std::string& url,
209 const DownloadFileCallback& callback);
211 PP_Bool StartPpapiProxy(PP_Instance instance);
213 // Thin adapter from PPP_ManifestService to ManifestServiceChannel::Delegate.
214 // Note that user_data is managed by the caller of LaunchSelLdr. Please see
215 // also PP_ManifestService's comment for more details about resource
216 // management.
217 class ManifestServiceProxy : public ManifestServiceChannel::Delegate {
218 public:
219 ManifestServiceProxy(PP_Instance pp_instance, NaClAppProcessType process_type)
220 : pp_instance_(pp_instance), process_type_(process_type) {}
222 ~ManifestServiceProxy() override {}
224 void StartupInitializationComplete() override {
225 if (StartPpapiProxy(pp_instance_) == PP_TRUE) {
226 NaClPluginInstance* nacl_plugin_instance =
227 GetNaClPluginInstance(pp_instance_);
228 JsonManifest* manifest = GetJsonManifest(pp_instance_);
229 if (nacl_plugin_instance && manifest) {
230 NexeLoadManager* load_manager =
231 &nacl_plugin_instance->nexe_load_manager;
232 std::string full_url;
233 PP_PNaClOptions pnacl_options;
234 bool uses_nonsfi_mode;
235 JsonManifest::ErrorInfo error_info;
236 if (manifest->GetProgramURL(&full_url,
237 &pnacl_options,
238 &uses_nonsfi_mode,
239 &error_info)) {
240 int64_t exe_size = nacl_plugin_instance->pexe_size;
241 if (exe_size == 0)
242 exe_size = load_manager->nexe_size();
243 load_manager->ReportLoadSuccess(full_url, exe_size, exe_size);
249 void OpenResource(
250 const std::string& key,
251 const ManifestServiceChannel::OpenResourceCallback& callback) override {
252 DCHECK(ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->
253 BelongsToCurrentThread());
255 // For security hardening, disable open_resource() when it is isn't
256 // needed. PNaCl pexes can't use open_resource(), but general nexes
257 // and the PNaCl translator nexes may use it.
258 if (process_type_ != kNativeNaClProcessType &&
259 process_type_ != kPNaClTranslatorProcessType) {
260 // Return an error.
261 base::ThreadTaskRunnerHandle::Get()->PostTask(
262 FROM_HERE, base::Bind(callback, base::Passed(base::File()), 0, 0));
263 return;
266 std::string url;
267 // TODO(teravest): Clean up pnacl_options logic in JsonManifest so we don't
268 // have to initialize it like this here.
269 PP_PNaClOptions pnacl_options;
270 pnacl_options.translate = PP_FALSE;
271 pnacl_options.is_debug = PP_FALSE;
272 pnacl_options.use_subzero = PP_FALSE;
273 pnacl_options.opt_level = 2;
274 bool is_helper_process = process_type_ == kPNaClTranslatorProcessType;
275 if (!ManifestResolveKey(pp_instance_, is_helper_process, key, &url,
276 &pnacl_options)) {
277 base::ThreadTaskRunnerHandle::Get()->PostTask(
278 FROM_HERE, base::Bind(callback, base::Passed(base::File()), 0, 0));
279 return;
282 // We have to call DidDownloadFile, even if this object is destroyed, so
283 // that the handle inside PP_NaClFileInfo isn't leaked. This means that the
284 // callback passed to this function shouldn't have a weak pointer to an
285 // object either.
287 // TODO(teravest): Make a type like PP_NaClFileInfo to use for DownloadFile
288 // that would close the file handle on destruction.
289 DownloadFile(pp_instance_, url,
290 base::Bind(&ManifestServiceProxy::DidDownloadFile, callback));
293 private:
294 static void DidDownloadFile(
295 ManifestServiceChannel::OpenResourceCallback callback,
296 int32_t pp_error,
297 const PP_NaClFileInfo& file_info) {
298 if (pp_error != PP_OK) {
299 callback.Run(base::File(), 0, 0);
300 return;
302 callback.Run(base::File(file_info.handle),
303 file_info.token_lo,
304 file_info.token_hi);
307 PP_Instance pp_instance_;
308 NaClAppProcessType process_type_;
309 DISALLOW_COPY_AND_ASSIGN(ManifestServiceProxy);
312 blink::WebURLLoader* CreateWebURLLoader(const blink::WebDocument& document,
313 const GURL& gurl) {
314 blink::WebURLLoaderOptions options;
315 options.untrustedHTTP = true;
317 // Options settings here follow the original behavior in the trusted
318 // plugin and PepperURLLoaderHost.
319 if (document.securityOrigin().canRequest(gurl)) {
320 options.allowCredentials = true;
321 } else {
322 // Allow CORS.
323 options.crossOriginRequestPolicy =
324 blink::WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
326 return document.frame()->createAssociatedURLLoader(options);
329 blink::WebURLRequest CreateWebURLRequest(const blink::WebDocument& document,
330 const GURL& gurl) {
331 blink::WebURLRequest request;
332 request.initialize();
333 request.setURL(gurl);
334 request.setFirstPartyForCookies(document.firstPartyForCookies());
335 return request;
338 int32_t FileDownloaderToPepperError(FileDownloader::Status status) {
339 switch (status) {
340 case FileDownloader::SUCCESS:
341 return PP_OK;
342 case FileDownloader::ACCESS_DENIED:
343 return PP_ERROR_NOACCESS;
344 case FileDownloader::FAILED:
345 return PP_ERROR_FAILED;
346 // No default case, to catch unhandled Status values.
348 return PP_ERROR_FAILED;
351 NaClAppProcessType PP_ToNaClAppProcessType(
352 PP_NaClAppProcessType pp_process_type) {
353 #define STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(pp, nonpp) \
354 static_assert(static_cast<int>(pp) == static_cast<int>(nonpp), \
355 "PP_NaClAppProcessType differs from NaClAppProcessType");
356 STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_UNKNOWN_NACL_PROCESS_TYPE,
357 kUnknownNaClProcessType);
358 STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_NATIVE_NACL_PROCESS_TYPE,
359 kNativeNaClProcessType);
360 STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_PNACL_PROCESS_TYPE,
361 kPNaClProcessType);
362 STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_PNACL_TRANSLATOR_PROCESS_TYPE,
363 kPNaClTranslatorProcessType);
364 STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ(PP_NUM_NACL_PROCESS_TYPES,
365 kNumNaClProcessTypes);
366 #undef STATICALLY_CHECK_NACLAPPPROCESSTYPE_EQ
367 DCHECK(pp_process_type > PP_UNKNOWN_NACL_PROCESS_TYPE &&
368 pp_process_type < PP_NUM_NACL_PROCESS_TYPES);
369 return static_cast<NaClAppProcessType>(pp_process_type);
372 // Launch NaCl's sel_ldr process.
373 void LaunchSelLdr(PP_Instance instance,
374 PP_Bool main_service_runtime,
375 const char* alleged_url,
376 const PP_NaClFileInfo* nexe_file_info,
377 PP_Bool uses_nonsfi_mode,
378 PP_NaClAppProcessType pp_process_type,
379 void* imc_handle,
380 PP_CompletionCallback callback) {
381 CHECK(ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->
382 BelongsToCurrentThread());
383 NaClAppProcessType process_type = PP_ToNaClAppProcessType(pp_process_type);
384 // Create the manifest service proxy here, so on error case, it will be
385 // destructed (without passing it to ManifestServiceChannel).
386 scoped_ptr<ManifestServiceChannel::Delegate> manifest_service_proxy(
387 new ManifestServiceProxy(instance, process_type));
389 IPC::Sender* sender = content::RenderThread::Get();
390 DCHECK(sender);
391 int routing_id = GetRoutingID(instance);
392 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
393 DCHECK(load_manager);
394 content::PepperPluginInstance* plugin_instance =
395 content::PepperPluginInstance::Get(instance);
396 DCHECK(plugin_instance);
397 if (!routing_id || !load_manager || !plugin_instance) {
398 if (nexe_file_info->handle != PP_kInvalidFileHandle) {
399 base::File closer(nexe_file_info->handle);
401 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
402 FROM_HERE, base::Bind(callback.func, callback.user_data,
403 static_cast<int32_t>(PP_ERROR_FAILED)));
404 return;
407 InstanceInfo instance_info;
408 instance_info.url = GURL(alleged_url);
410 uint32_t perm_bits = ppapi::PERMISSION_NONE;
411 // Conditionally block 'Dev' interfaces. We do this for the NaCl process, so
412 // it's clearer to developers when they are using 'Dev' inappropriately. We
413 // must also check on the trusted side of the proxy.
414 if (load_manager->DevInterfacesEnabled())
415 perm_bits |= ppapi::PERMISSION_DEV;
416 instance_info.permissions =
417 ppapi::PpapiPermissions::GetForCommandLine(perm_bits);
419 std::vector<NaClResourcePrefetchRequest> resource_prefetch_request_list;
420 if (process_type == kNativeNaClProcessType) {
421 JsonManifest* manifest = GetJsonManifest(instance);
422 if (manifest) {
423 manifest->GetPrefetchableFiles(&resource_prefetch_request_list);
425 for (size_t i = 0; i < resource_prefetch_request_list.size(); ++i) {
426 const GURL gurl(resource_prefetch_request_list[i].resource_url);
427 // Important security check. Do not remove.
428 if (!CanOpenViaFastPath(plugin_instance, gurl)) {
429 resource_prefetch_request_list.clear();
430 break;
436 IPC::PlatformFileForTransit nexe_for_transit =
437 IPC::InvalidPlatformFileForTransit();
438 #if defined(OS_POSIX)
439 if (nexe_file_info->handle != PP_kInvalidFileHandle)
440 nexe_for_transit = base::FileDescriptor(nexe_file_info->handle, true);
441 #elif defined(OS_WIN)
442 // Duplicate the handle on the browser side instead of the renderer.
443 // This is because BrokerGetFileForProcess isn't part of content/public, and
444 // it's simpler to do the duplication in the browser anyway.
445 nexe_for_transit = nexe_file_info->handle;
446 #else
447 # error Unsupported target platform.
448 #endif
450 std::string error_message_string;
451 NaClLaunchResult launch_result;
452 if (!sender->Send(new NaClHostMsg_LaunchNaCl(
453 NaClLaunchParams(
454 instance_info.url.spec(),
455 nexe_for_transit,
456 nexe_file_info->token_lo,
457 nexe_file_info->token_hi,
458 resource_prefetch_request_list,
459 routing_id,
460 perm_bits,
461 PP_ToBool(uses_nonsfi_mode),
462 process_type),
463 &launch_result,
464 &error_message_string))) {
465 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
466 FROM_HERE,
467 base::Bind(callback.func, callback.user_data,
468 static_cast<int32_t>(PP_ERROR_FAILED)));
469 return;
472 load_manager->set_nonsfi(PP_ToBool(uses_nonsfi_mode));
474 if (!error_message_string.empty()) {
475 // Even on error, some FDs/handles may be passed to here.
476 // We must release those resources.
477 // See also nacl_process_host.cc.
478 IPC::PlatformFileForTransitToFile(launch_result.imc_channel_handle);
479 base::SharedMemory::CloseHandle(launch_result.crash_info_shmem_handle);
481 if (PP_ToBool(main_service_runtime)) {
482 load_manager->ReportLoadError(PP_NACL_ERROR_SEL_LDR_LAUNCH,
483 "ServiceRuntime: failed to start",
484 error_message_string);
486 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
487 FROM_HERE,
488 base::Bind(callback.func, callback.user_data,
489 static_cast<int32_t>(PP_ERROR_FAILED)));
490 return;
493 instance_info.channel_handle = launch_result.ppapi_ipc_channel_handle;
494 instance_info.plugin_pid = launch_result.plugin_pid;
495 instance_info.plugin_child_id = launch_result.plugin_child_id;
497 // Don't save instance_info if channel handle is invalid.
498 if (IsValidChannelHandle(instance_info.channel_handle)) {
499 NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
500 nacl_plugin_instance->instance_info.reset(new InstanceInfo(instance_info));
503 *(static_cast<NaClHandle*>(imc_handle)) =
504 IPC::PlatformFileForTransitToPlatformFile(
505 launch_result.imc_channel_handle);
507 // Store the crash information shared memory handle.
508 load_manager->set_crash_info_shmem_handle(
509 launch_result.crash_info_shmem_handle);
511 // Create the trusted plugin channel.
512 if (IsValidChannelHandle(launch_result.trusted_ipc_channel_handle)) {
513 bool is_helper_nexe = !PP_ToBool(main_service_runtime);
514 scoped_ptr<TrustedPluginChannel> trusted_plugin_channel(
515 new TrustedPluginChannel(
516 load_manager,
517 launch_result.trusted_ipc_channel_handle,
518 content::RenderThread::Get()->GetShutdownEvent(),
519 is_helper_nexe));
520 load_manager->set_trusted_plugin_channel(trusted_plugin_channel.Pass());
521 } else {
522 PostPPCompletionCallback(callback, PP_ERROR_FAILED);
523 return;
526 // Create the manifest service handle as well.
527 if (IsValidChannelHandle(launch_result.manifest_service_ipc_channel_handle)) {
528 scoped_ptr<ManifestServiceChannel> manifest_service_channel(
529 new ManifestServiceChannel(
530 launch_result.manifest_service_ipc_channel_handle,
531 base::Bind(&PostPPCompletionCallback, callback),
532 manifest_service_proxy.Pass(),
533 content::RenderThread::Get()->GetShutdownEvent()));
534 load_manager->set_manifest_service_channel(
535 manifest_service_channel.Pass());
539 PP_Bool StartPpapiProxy(PP_Instance instance) {
540 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
541 DCHECK(load_manager);
542 if (!load_manager)
543 return PP_FALSE;
545 content::PepperPluginInstance* plugin_instance =
546 content::PepperPluginInstance::Get(instance);
547 if (!plugin_instance) {
548 DLOG(ERROR) << "GetInstance() failed";
549 return PP_FALSE;
552 NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
553 if (!nacl_plugin_instance->instance_info) {
554 DLOG(ERROR) << "Could not find instance ID";
555 return PP_FALSE;
557 scoped_ptr<InstanceInfo> instance_info =
558 nacl_plugin_instance->instance_info.Pass();
560 PP_ExternalPluginResult result = plugin_instance->SwitchToOutOfProcessProxy(
561 base::FilePath().AppendASCII(instance_info->url.spec()),
562 instance_info->permissions,
563 instance_info->channel_handle,
564 instance_info->plugin_pid,
565 instance_info->plugin_child_id);
567 if (result == PP_EXTERNAL_PLUGIN_OK) {
568 // Log the amound of time that has passed between the trusted plugin being
569 // initialized and the untrusted plugin being initialized. This is
570 // (roughly) the cost of using NaCl, in terms of startup time.
571 load_manager->ReportStartupOverhead();
572 return PP_TRUE;
573 } else if (result == PP_EXTERNAL_PLUGIN_ERROR_MODULE) {
574 load_manager->ReportLoadError(PP_NACL_ERROR_START_PROXY_MODULE,
575 "could not initialize module.");
576 } else if (result == PP_EXTERNAL_PLUGIN_ERROR_INSTANCE) {
577 load_manager->ReportLoadError(PP_NACL_ERROR_START_PROXY_MODULE,
578 "could not create instance.");
580 return PP_FALSE;
583 int UrandomFD(void) {
584 #if defined(OS_POSIX)
585 return base::GetUrandomFD();
586 #else
587 return -1;
588 #endif
591 int32_t BrokerDuplicateHandle(PP_FileHandle source_handle,
592 uint32_t process_id,
593 PP_FileHandle* target_handle,
594 uint32_t desired_access,
595 uint32_t options) {
596 #if defined(OS_WIN)
597 return content::BrokerDuplicateHandle(source_handle, process_id,
598 target_handle, desired_access,
599 options);
600 #else
601 return 0;
602 #endif
605 // Convert a URL to a filename for GetReadonlyPnaclFd.
606 // Must be kept in sync with PnaclCanOpenFile() in
607 // components/nacl/browser/nacl_file_host.cc.
608 std::string PnaclComponentURLToFilename(const std::string& url) {
609 // PNaCl component URLs aren't arbitrary URLs; they are always either
610 // generated from ManifestResolveKey or PnaclResources::ReadResourceInfo.
611 // So, it's safe to just use string parsing operations here instead of
612 // URL-parsing ones.
613 DCHECK(base::StartsWith(url, kPNaClTranslatorBaseUrl,
614 base::CompareCase::SENSITIVE));
615 std::string r = url.substr(std::string(kPNaClTranslatorBaseUrl).length());
617 // Use white-listed-chars.
618 size_t replace_pos;
619 static const char* white_list = "abcdefghijklmnopqrstuvwxyz0123456789_";
620 replace_pos = r.find_first_not_of(white_list);
621 while(replace_pos != std::string::npos) {
622 r = r.replace(replace_pos, 1, "_");
623 replace_pos = r.find_first_not_of(white_list);
625 return r;
628 PP_FileHandle GetReadonlyPnaclFd(const char* url,
629 bool is_executable,
630 uint64_t* nonce_lo,
631 uint64_t* nonce_hi) {
632 std::string filename = PnaclComponentURLToFilename(url);
633 IPC::PlatformFileForTransit out_fd = IPC::InvalidPlatformFileForTransit();
634 IPC::Sender* sender = content::RenderThread::Get();
635 DCHECK(sender);
636 if (!sender->Send(new NaClHostMsg_GetReadonlyPnaclFD(
637 std::string(filename), is_executable,
638 &out_fd, nonce_lo, nonce_hi))) {
639 return PP_kInvalidFileHandle;
641 if (out_fd == IPC::InvalidPlatformFileForTransit()) {
642 return PP_kInvalidFileHandle;
644 return IPC::PlatformFileForTransitToPlatformFile(out_fd);
647 void GetReadExecPnaclFd(const char* url,
648 PP_NaClFileInfo* out_file_info) {
649 *out_file_info = kInvalidNaClFileInfo;
650 out_file_info->handle = GetReadonlyPnaclFd(url, true /* is_executable */,
651 &out_file_info->token_lo,
652 &out_file_info->token_hi);
655 PP_FileHandle CreateTemporaryFile(PP_Instance instance) {
656 IPC::PlatformFileForTransit transit_fd = IPC::InvalidPlatformFileForTransit();
657 IPC::Sender* sender = content::RenderThread::Get();
658 DCHECK(sender);
659 if (!sender->Send(new NaClHostMsg_NaClCreateTemporaryFile(
660 &transit_fd))) {
661 return PP_kInvalidFileHandle;
664 if (transit_fd == IPC::InvalidPlatformFileForTransit()) {
665 return PP_kInvalidFileHandle;
668 return IPC::PlatformFileForTransitToPlatformFile(transit_fd);
671 int32_t GetNumberOfProcessors() {
672 IPC::Sender* sender = content::RenderThread::Get();
673 DCHECK(sender);
674 int32_t num_processors = 1;
675 return sender->Send(new NaClHostMsg_NaClGetNumProcessors(&num_processors)) ?
676 num_processors : 1;
679 void GetNexeFd(PP_Instance instance,
680 const std::string& pexe_url,
681 uint32_t opt_level,
682 const base::Time& last_modified_time,
683 const std::string& etag,
684 bool has_no_store_header,
685 bool use_subzero,
686 base::Callback<void(int32_t, bool, PP_FileHandle)> callback) {
687 if (!InitializePnaclResourceHost()) {
688 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
689 FROM_HERE,
690 base::Bind(callback,
691 static_cast<int32_t>(PP_ERROR_FAILED),
692 false,
693 PP_kInvalidFileHandle));
694 return;
697 PnaclCacheInfo cache_info;
698 cache_info.pexe_url = GURL(pexe_url);
699 // TODO(dschuff): Get this value from the pnacl json file after it
700 // rolls in from NaCl.
701 cache_info.abi_version = 1;
702 cache_info.opt_level = opt_level;
703 cache_info.last_modified = last_modified_time;
704 cache_info.etag = etag;
705 cache_info.has_no_store_header = has_no_store_header;
706 cache_info.use_subzero = use_subzero;
707 cache_info.sandbox_isa = GetSandboxArch();
708 cache_info.extra_flags = GetCpuFeatures();
710 g_pnacl_resource_host.Get()->RequestNexeFd(
711 GetRoutingID(instance),
712 instance,
713 cache_info,
714 callback);
717 void LogTranslationFinishedUMA(const std::string& uma_suffix,
718 int32_t opt_level,
719 int32_t unknown_opt_level,
720 int64_t nexe_size,
721 int64_t pexe_size,
722 int64_t compile_time_us,
723 base::TimeDelta total_time) {
724 HistogramEnumerate("NaCl.Options.PNaCl.OptLevel" + uma_suffix, opt_level,
725 unknown_opt_level + 1);
726 HistogramKBPerSec("NaCl.Perf.PNaClLoadTime.CompileKBPerSec" + uma_suffix,
727 pexe_size / 1024, compile_time_us);
728 HistogramSizeKB("NaCl.Perf.Size.PNaClTranslatedNexe" + uma_suffix,
729 nexe_size / 1024);
730 HistogramSizeKB("NaCl.Perf.Size.Pexe" + uma_suffix, pexe_size / 1024);
731 HistogramRatio("NaCl.Perf.Size.PexeNexeSizePct" + uma_suffix, pexe_size,
732 nexe_size);
733 HistogramTimeTranslation(
734 "NaCl.Perf.PNaClLoadTime.TotalUncachedTime" + uma_suffix,
735 total_time.InMilliseconds());
736 HistogramKBPerSec(
737 "NaCl.Perf.PNaClLoadTime.TotalUncachedKBPerSec" + uma_suffix,
738 pexe_size / 1024, total_time.InMicroseconds());
741 void ReportTranslationFinished(PP_Instance instance,
742 PP_Bool success,
743 int32_t opt_level,
744 PP_Bool use_subzero,
745 int64_t nexe_size,
746 int64_t pexe_size,
747 int64_t compile_time_us) {
748 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
749 DCHECK(load_manager);
750 if (success == PP_TRUE && load_manager) {
751 base::TimeDelta total_time =
752 base::Time::Now() - load_manager->pnacl_start_time();
753 static const int32_t kUnknownOptLevel = 4;
754 if (opt_level < 0 || opt_level > 3)
755 opt_level = kUnknownOptLevel;
756 // Log twice: once to cover all PNaCl UMA, and then a second
757 // time with the more specific UMA (Subzero vs LLC).
758 std::string uma_suffix(use_subzero ? ".Subzero" : ".LLC");
759 LogTranslationFinishedUMA("", opt_level, kUnknownOptLevel, nexe_size,
760 pexe_size, compile_time_us, total_time);
761 LogTranslationFinishedUMA(uma_suffix, opt_level, kUnknownOptLevel,
762 nexe_size, pexe_size, compile_time_us,
763 total_time);
766 // If the resource host isn't initialized, don't try to do that here.
767 // Just return because something is already very wrong.
768 if (g_pnacl_resource_host.Get().get() == NULL)
769 return;
770 g_pnacl_resource_host.Get()->ReportTranslationFinished(instance, success);
772 // Record the pexe size for reporting in a later load event.
773 NaClPluginInstance* nacl_plugin_instance = GetNaClPluginInstance(instance);
774 if (nacl_plugin_instance) {
775 nacl_plugin_instance->pexe_size = pexe_size;
779 PP_FileHandle OpenNaClExecutable(PP_Instance instance,
780 const char* file_url,
781 uint64_t* nonce_lo,
782 uint64_t* nonce_hi) {
783 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
784 DCHECK(load_manager);
785 if (!load_manager)
786 return PP_kInvalidFileHandle;
788 content::PepperPluginInstance* plugin_instance =
789 content::PepperPluginInstance::Get(instance);
790 if (!plugin_instance)
791 return PP_kInvalidFileHandle;
793 GURL gurl(file_url);
794 // Important security check. Do not remove.
795 if (!CanOpenViaFastPath(plugin_instance, gurl))
796 return PP_kInvalidFileHandle;
798 IPC::PlatformFileForTransit out_fd = IPC::InvalidPlatformFileForTransit();
799 IPC::Sender* sender = content::RenderThread::Get();
800 DCHECK(sender);
801 *nonce_lo = 0;
802 *nonce_hi = 0;
803 base::FilePath file_path;
804 if (!sender->Send(
805 new NaClHostMsg_OpenNaClExecutable(GetRoutingID(instance),
806 GURL(file_url),
807 !load_manager->nonsfi(),
808 &out_fd,
809 nonce_lo,
810 nonce_hi))) {
811 return PP_kInvalidFileHandle;
814 if (out_fd == IPC::InvalidPlatformFileForTransit())
815 return PP_kInvalidFileHandle;
817 return IPC::PlatformFileForTransitToPlatformFile(out_fd);
820 void DispatchEvent(PP_Instance instance,
821 PP_NaClEventType event_type,
822 const char* resource_url,
823 PP_Bool length_is_computable,
824 uint64_t loaded_bytes,
825 uint64_t total_bytes) {
826 ProgressEvent event(event_type,
827 resource_url,
828 PP_ToBool(length_is_computable),
829 loaded_bytes,
830 total_bytes);
831 DispatchProgressEvent(instance, event);
834 void ReportLoadError(PP_Instance instance,
835 PP_NaClError error,
836 const char* error_message) {
837 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
838 if (load_manager)
839 load_manager->ReportLoadError(error, error_message);
842 void InstanceCreated(PP_Instance instance) {
843 InstanceMap& map = g_instance_map.Get();
844 CHECK(map.find(instance) == map.end()); // Sanity check.
845 scoped_ptr<NaClPluginInstance> new_instance(new NaClPluginInstance(instance));
846 map.add(instance, new_instance.Pass());
849 void InstanceDestroyed(PP_Instance instance) {
850 InstanceMap& map = g_instance_map.Get();
851 InstanceMap::iterator iter = map.find(instance);
852 CHECK(iter != map.end());
853 // The erase may call NexeLoadManager's destructor prior to removing it from
854 // the map. In that case, it is possible for the trusted Plugin to re-enter
855 // the NexeLoadManager (e.g., by calling ReportLoadError). Passing out the
856 // NexeLoadManager to a local scoped_ptr just ensures that its entry is gone
857 // from the map prior to the destructor being invoked.
858 scoped_ptr<NaClPluginInstance> temp(map.take(instance));
859 map.erase(iter);
862 PP_Bool NaClDebugEnabledForURL(const char* alleged_nmf_url) {
863 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
864 switches::kEnableNaClDebug))
865 return PP_FALSE;
866 IPC::Sender* sender = content::RenderThread::Get();
867 DCHECK(sender);
868 bool should_debug = false;
869 return PP_FromBool(
870 sender->Send(new NaClHostMsg_NaClDebugEnabledForURL(GURL(alleged_nmf_url),
871 &should_debug)) &&
872 should_debug);
875 void Vlog(const char* message) {
876 VLOG(1) << message;
879 void InitializePlugin(PP_Instance instance,
880 uint32_t argc,
881 const char* argn[],
882 const char* argv[]) {
883 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
884 DCHECK(load_manager);
885 if (load_manager)
886 load_manager->InitializePlugin(argc, argn, argv);
889 void DownloadManifestToBuffer(PP_Instance instance,
890 struct PP_CompletionCallback callback);
892 bool CreateJsonManifest(PP_Instance instance,
893 const std::string& manifest_url,
894 const std::string& manifest_data);
896 void RequestNaClManifest(PP_Instance instance,
897 PP_CompletionCallback callback) {
898 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
899 DCHECK(load_manager);
900 if (!load_manager) {
901 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
902 FROM_HERE,
903 base::Bind(callback.func, callback.user_data,
904 static_cast<int32_t>(PP_ERROR_FAILED)));
905 return;
908 std::string url = load_manager->GetManifestURLArgument();
909 if (url.empty() || !load_manager->RequestNaClManifest(url)) {
910 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
911 FROM_HERE,
912 base::Bind(callback.func, callback.user_data,
913 static_cast<int32_t>(PP_ERROR_FAILED)));
914 return;
917 const GURL& base_url = load_manager->manifest_base_url();
918 if (base_url.SchemeIs("data")) {
919 GURL gurl(base_url);
920 std::string mime_type;
921 std::string charset;
922 std::string data;
923 int32_t error = PP_ERROR_FAILED;
924 if (net::DataURL::Parse(gurl, &mime_type, &charset, &data)) {
925 if (data.size() <= ManifestDownloader::kNaClManifestMaxFileBytes) {
926 if (CreateJsonManifest(instance, base_url.spec(), data))
927 error = PP_OK;
928 } else {
929 load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_TOO_LARGE,
930 "manifest file too large.");
932 } else {
933 load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL,
934 "could not load manifest url.");
936 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
937 FROM_HERE,
938 base::Bind(callback.func, callback.user_data, error));
939 } else {
940 DownloadManifestToBuffer(instance, callback);
944 PP_Var GetManifestBaseURL(PP_Instance instance) {
945 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
946 DCHECK(load_manager);
947 if (!load_manager)
948 return PP_MakeUndefined();
949 const GURL& gurl = load_manager->manifest_base_url();
950 if (!gurl.is_valid())
951 return PP_MakeUndefined();
952 return ppapi::StringVar::StringToPPVar(gurl.spec());
955 void ProcessNaClManifest(PP_Instance instance, const char* program_url) {
956 nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
957 if (load_manager)
958 load_manager->ProcessNaClManifest(program_url);
961 void DownloadManifestToBufferCompletion(PP_Instance instance,
962 struct PP_CompletionCallback callback,
963 base::Time start_time,
964 PP_NaClError pp_nacl_error,
965 const std::string& data);
967 void DownloadManifestToBuffer(PP_Instance instance,
968 struct PP_CompletionCallback callback) {
969 nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
970 DCHECK(load_manager);
971 content::PepperPluginInstance* plugin_instance =
972 content::PepperPluginInstance::Get(instance);
973 if (!load_manager || !plugin_instance) {
974 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
975 FROM_HERE,
976 base::Bind(callback.func, callback.user_data,
977 static_cast<int32_t>(PP_ERROR_FAILED)));
979 const blink::WebDocument& document =
980 plugin_instance->GetContainer()->element().document();
982 const GURL& gurl = load_manager->manifest_base_url();
983 scoped_ptr<blink::WebURLLoader> url_loader(
984 CreateWebURLLoader(document, gurl));
985 blink::WebURLRequest request = CreateWebURLRequest(document, gurl);
987 // ManifestDownloader deletes itself after invoking the callback.
988 ManifestDownloader* manifest_downloader = new ManifestDownloader(
989 url_loader.Pass(),
990 load_manager->is_installed(),
991 base::Bind(DownloadManifestToBufferCompletion,
992 instance, callback, base::Time::Now()));
993 manifest_downloader->Load(request);
996 void DownloadManifestToBufferCompletion(PP_Instance instance,
997 struct PP_CompletionCallback callback,
998 base::Time start_time,
999 PP_NaClError pp_nacl_error,
1000 const std::string& data) {
1001 base::TimeDelta download_time = base::Time::Now() - start_time;
1002 HistogramTimeSmall("NaCl.Perf.StartupTime.ManifestDownload",
1003 download_time.InMilliseconds());
1005 nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
1006 if (!load_manager) {
1007 callback.func(callback.user_data, PP_ERROR_ABORTED);
1008 return;
1011 int32_t pp_error;
1012 switch (pp_nacl_error) {
1013 case PP_NACL_ERROR_LOAD_SUCCESS:
1014 pp_error = PP_OK;
1015 break;
1016 case PP_NACL_ERROR_MANIFEST_LOAD_URL:
1017 pp_error = PP_ERROR_FAILED;
1018 load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL,
1019 "could not load manifest url.");
1020 break;
1021 case PP_NACL_ERROR_MANIFEST_TOO_LARGE:
1022 pp_error = PP_ERROR_FILETOOBIG;
1023 load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_TOO_LARGE,
1024 "manifest file too large.");
1025 break;
1026 case PP_NACL_ERROR_MANIFEST_NOACCESS_URL:
1027 pp_error = PP_ERROR_NOACCESS;
1028 load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_NOACCESS_URL,
1029 "access to manifest url was denied.");
1030 break;
1031 default:
1032 NOTREACHED();
1033 pp_error = PP_ERROR_FAILED;
1034 load_manager->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL,
1035 "could not load manifest url.");
1038 if (pp_error == PP_OK) {
1039 std::string base_url = load_manager->manifest_base_url().spec();
1040 if (!CreateJsonManifest(instance, base_url, data))
1041 pp_error = PP_ERROR_FAILED;
1043 callback.func(callback.user_data, pp_error);
1046 bool CreateJsonManifest(PP_Instance instance,
1047 const std::string& manifest_url,
1048 const std::string& manifest_data) {
1049 HistogramSizeKB("NaCl.Perf.Size.Manifest",
1050 static_cast<int32_t>(manifest_data.length() / 1024));
1052 nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
1053 if (!load_manager)
1054 return false;
1056 const char* isa_type;
1057 if (load_manager->IsPNaCl())
1058 isa_type = kPortableArch;
1059 else
1060 isa_type = GetSandboxArch();
1062 scoped_ptr<nacl::JsonManifest> j(
1063 new nacl::JsonManifest(
1064 manifest_url.c_str(),
1065 isa_type,
1066 IsNonSFIModeEnabled(),
1067 PP_ToBool(NaClDebugEnabledForURL(manifest_url.c_str()))));
1068 JsonManifest::ErrorInfo error_info;
1069 if (j->Init(manifest_data.c_str(), &error_info)) {
1070 GetNaClPluginInstance(instance)->json_manifest.reset(j.release());
1071 return true;
1073 load_manager->ReportLoadError(error_info.error, error_info.string);
1074 return false;
1077 PP_Bool ManifestGetProgramURL(PP_Instance instance,
1078 PP_Var* pp_full_url,
1079 PP_PNaClOptions* pnacl_options,
1080 PP_Bool* pp_uses_nonsfi_mode) {
1081 nacl::NexeLoadManager* load_manager = GetNexeLoadManager(instance);
1083 JsonManifest* manifest = GetJsonManifest(instance);
1084 if (manifest == NULL)
1085 return PP_FALSE;
1087 bool uses_nonsfi_mode;
1088 std::string full_url;
1089 JsonManifest::ErrorInfo error_info;
1090 if (manifest->GetProgramURL(&full_url, pnacl_options, &uses_nonsfi_mode,
1091 &error_info)) {
1092 *pp_full_url = ppapi::StringVar::StringToPPVar(full_url);
1093 *pp_uses_nonsfi_mode = PP_FromBool(uses_nonsfi_mode);
1094 // Check if we should use Subzero (x86-32 / non-debugging case for now).
1095 if (pnacl_options->opt_level == 0 && !pnacl_options->is_debug &&
1096 strcmp(GetSandboxArch(), "x86-32") == 0 &&
1097 base::CommandLine::ForCurrentProcess()->HasSwitch(
1098 switches::kEnablePNaClSubzero)) {
1099 pnacl_options->use_subzero = PP_TRUE;
1100 // Subzero -O2 is closer to LLC -O0, so indicate -O2.
1101 pnacl_options->opt_level = 2;
1103 return PP_TRUE;
1106 if (load_manager)
1107 load_manager->ReportLoadError(error_info.error, error_info.string);
1108 return PP_FALSE;
1111 bool ManifestResolveKey(PP_Instance instance,
1112 bool is_helper_process,
1113 const std::string& key,
1114 std::string* full_url,
1115 PP_PNaClOptions* pnacl_options) {
1116 // For "helper" processes (llc and ld, for PNaCl translation), we resolve
1117 // keys manually as there is no existing .nmf file to parse.
1118 if (is_helper_process) {
1119 pnacl_options->translate = PP_FALSE;
1120 *full_url = std::string(kPNaClTranslatorBaseUrl) + GetSandboxArch() + "/" +
1121 key;
1122 return true;
1125 JsonManifest* manifest = GetJsonManifest(instance);
1126 if (manifest == NULL)
1127 return false;
1129 return manifest->ResolveKey(key, full_url, pnacl_options);
1132 PP_Bool GetPNaClResourceInfo(PP_Instance instance,
1133 PP_Var* llc_tool_name,
1134 PP_Var* ld_tool_name,
1135 PP_Var* subzero_tool_name) {
1136 static const char kFilename[] = "chrome://pnacl-translator/pnacl.json";
1137 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
1138 DCHECK(load_manager);
1139 if (!load_manager)
1140 return PP_FALSE;
1142 uint64_t nonce_lo = 0;
1143 uint64_t nonce_hi = 0;
1144 base::File file(GetReadonlyPnaclFd(kFilename, false /* is_executable */,
1145 &nonce_lo, &nonce_hi));
1146 if (!file.IsValid()) {
1147 load_manager->ReportLoadError(
1148 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1149 "The Portable Native Client (pnacl) component is not "
1150 "installed. Please consult chrome://components for more "
1151 "information.");
1152 return PP_FALSE;
1155 base::File::Info file_info;
1156 if (!file.GetInfo(&file_info)) {
1157 load_manager->ReportLoadError(
1158 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1159 std::string("GetPNaClResourceInfo, GetFileInfo failed for: ") +
1160 kFilename);
1161 return PP_FALSE;
1164 if (file_info.size > 1 << 20) {
1165 load_manager->ReportLoadError(
1166 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1167 std::string("GetPNaClResourceInfo, file too large: ") + kFilename);
1168 return PP_FALSE;
1171 scoped_ptr<char[]> buffer(new char[file_info.size + 1]);
1172 if (buffer.get() == NULL) {
1173 load_manager->ReportLoadError(
1174 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1175 std::string("GetPNaClResourceInfo, couldn't allocate for: ") +
1176 kFilename);
1177 return PP_FALSE;
1180 int rc = file.Read(0, buffer.get(), file_info.size);
1181 if (rc < 0) {
1182 load_manager->ReportLoadError(
1183 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1184 std::string("GetPNaClResourceInfo, reading failed for: ") + kFilename);
1185 return PP_FALSE;
1188 // Null-terminate the bytes we we read from the file.
1189 buffer.get()[rc] = 0;
1191 // Expect the JSON file to contain a top-level object (dictionary).
1192 base::JSONReader json_reader;
1193 int json_read_error_code;
1194 std::string json_read_error_msg;
1195 scoped_ptr<base::Value> json_data(json_reader.ReadAndReturnError(
1196 buffer.get(),
1197 base::JSON_PARSE_RFC,
1198 &json_read_error_code,
1199 &json_read_error_msg));
1200 if (!json_data) {
1201 load_manager->ReportLoadError(
1202 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1203 std::string("Parsing resource info failed: JSON parse error: ") +
1204 json_read_error_msg);
1205 return PP_FALSE;
1208 base::DictionaryValue* json_dict;
1209 if (!json_data->GetAsDictionary(&json_dict)) {
1210 load_manager->ReportLoadError(
1211 PP_NACL_ERROR_PNACL_RESOURCE_FETCH,
1212 "Parsing resource info failed: Malformed JSON dictionary");
1213 return PP_FALSE;
1216 std::string pnacl_llc_name;
1217 if (json_dict->GetString("pnacl-llc-name", &pnacl_llc_name))
1218 *llc_tool_name = ppapi::StringVar::StringToPPVar(pnacl_llc_name);
1220 std::string pnacl_ld_name;
1221 if (json_dict->GetString("pnacl-ld-name", &pnacl_ld_name))
1222 *ld_tool_name = ppapi::StringVar::StringToPPVar(pnacl_ld_name);
1224 std::string pnacl_sz_name;
1225 if (json_dict->GetString("pnacl-sz-name", &pnacl_sz_name))
1226 *subzero_tool_name = ppapi::StringVar::StringToPPVar(pnacl_sz_name);
1228 return PP_TRUE;
1231 PP_Var GetCpuFeatureAttrs() {
1232 return ppapi::StringVar::StringToPPVar(GetCpuFeatures());
1235 // Encapsulates some of the state for a call to DownloadNexe to prevent
1236 // argument lists from getting too long.
1237 struct DownloadNexeRequest {
1238 PP_Instance instance;
1239 std::string url;
1240 PP_CompletionCallback callback;
1241 base::Time start_time;
1244 // A utility class to ensure that we don't send progress events more often than
1245 // every 10ms for a given file.
1246 class ProgressEventRateLimiter {
1247 public:
1248 explicit ProgressEventRateLimiter(PP_Instance instance)
1249 : instance_(instance) { }
1251 void ReportProgress(const std::string& url,
1252 int64_t total_bytes_received,
1253 int64_t total_bytes_to_be_received) {
1254 base::Time now = base::Time::Now();
1255 if (now - last_event_ > base::TimeDelta::FromMilliseconds(10)) {
1256 DispatchProgressEvent(instance_,
1257 ProgressEvent(PP_NACL_EVENT_PROGRESS,
1258 url,
1259 total_bytes_to_be_received >= 0,
1260 total_bytes_received,
1261 total_bytes_to_be_received));
1262 last_event_ = now;
1266 private:
1267 PP_Instance instance_;
1268 base::Time last_event_;
1271 void DownloadNexeCompletion(const DownloadNexeRequest& request,
1272 PP_NaClFileInfo* out_file_info,
1273 FileDownloader::Status status,
1274 base::File target_file,
1275 int http_status);
1277 void DownloadNexe(PP_Instance instance,
1278 const char* url,
1279 PP_NaClFileInfo* out_file_info,
1280 PP_CompletionCallback callback) {
1281 CHECK(url);
1282 CHECK(out_file_info);
1283 DownloadNexeRequest request;
1284 request.instance = instance;
1285 request.url = url;
1286 request.callback = callback;
1287 request.start_time = base::Time::Now();
1289 // Try the fast path for retrieving the file first.
1290 PP_FileHandle handle = OpenNaClExecutable(instance,
1291 url,
1292 &out_file_info->token_lo,
1293 &out_file_info->token_hi);
1294 if (handle != PP_kInvalidFileHandle) {
1295 DownloadNexeCompletion(request,
1296 out_file_info,
1297 FileDownloader::SUCCESS,
1298 base::File(handle),
1299 200);
1300 return;
1303 // The fast path didn't work, we'll fetch the file using URLLoader and write
1304 // it to local storage.
1305 base::File target_file(CreateTemporaryFile(instance));
1306 GURL gurl(url);
1308 content::PepperPluginInstance* plugin_instance =
1309 content::PepperPluginInstance::Get(instance);
1310 if (!plugin_instance) {
1311 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
1312 FROM_HERE,
1313 base::Bind(callback.func, callback.user_data,
1314 static_cast<int32_t>(PP_ERROR_FAILED)));
1316 const blink::WebDocument& document =
1317 plugin_instance->GetContainer()->element().document();
1318 scoped_ptr<blink::WebURLLoader> url_loader(
1319 CreateWebURLLoader(document, gurl));
1320 blink::WebURLRequest url_request = CreateWebURLRequest(document, gurl);
1322 ProgressEventRateLimiter* tracker = new ProgressEventRateLimiter(instance);
1324 // FileDownloader deletes itself after invoking DownloadNexeCompletion.
1325 FileDownloader* file_downloader = new FileDownloader(
1326 url_loader.Pass(),
1327 target_file.Pass(),
1328 base::Bind(&DownloadNexeCompletion, request, out_file_info),
1329 base::Bind(&ProgressEventRateLimiter::ReportProgress,
1330 base::Owned(tracker), std::string(url)));
1331 file_downloader->Load(url_request);
1334 void DownloadNexeCompletion(const DownloadNexeRequest& request,
1335 PP_NaClFileInfo* out_file_info,
1336 FileDownloader::Status status,
1337 base::File target_file,
1338 int http_status) {
1339 int32_t pp_error = FileDownloaderToPepperError(status);
1340 int64_t bytes_read = -1;
1341 if (pp_error == PP_OK && target_file.IsValid()) {
1342 base::File::Info info;
1343 if (target_file.GetInfo(&info))
1344 bytes_read = info.size;
1347 if (bytes_read == -1) {
1348 target_file.Close();
1349 pp_error = PP_ERROR_FAILED;
1352 base::TimeDelta download_time = base::Time::Now() - request.start_time;
1354 NexeLoadManager* load_manager = GetNexeLoadManager(request.instance);
1355 if (load_manager) {
1356 load_manager->NexeFileDidOpen(pp_error,
1357 target_file,
1358 http_status,
1359 bytes_read,
1360 request.url,
1361 download_time);
1364 if (pp_error == PP_OK && target_file.IsValid())
1365 out_file_info->handle = target_file.TakePlatformFile();
1366 else
1367 out_file_info->handle = PP_kInvalidFileHandle;
1369 request.callback.func(request.callback.user_data, pp_error);
1372 void DownloadFileCompletion(
1373 const DownloadFileCallback& callback,
1374 FileDownloader::Status status,
1375 base::File file,
1376 int http_status) {
1377 int32_t pp_error = FileDownloaderToPepperError(status);
1378 PP_NaClFileInfo file_info;
1379 if (pp_error == PP_OK) {
1380 file_info.handle = file.TakePlatformFile();
1381 file_info.token_lo = 0;
1382 file_info.token_hi = 0;
1383 } else {
1384 file_info = kInvalidNaClFileInfo;
1387 callback.Run(pp_error, file_info);
1390 void DownloadFile(PP_Instance instance,
1391 const std::string& url,
1392 const DownloadFileCallback& callback) {
1393 DCHECK(ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->
1394 BelongsToCurrentThread());
1396 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
1397 DCHECK(load_manager);
1398 if (!load_manager) {
1399 base::ThreadTaskRunnerHandle::Get()->PostTask(
1400 FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
1401 kInvalidNaClFileInfo));
1402 return;
1405 // Handle special PNaCl support files which are installed on the user's
1406 // machine.
1407 if (url.find(kPNaClTranslatorBaseUrl, 0) == 0) {
1408 PP_NaClFileInfo file_info = kInvalidNaClFileInfo;
1409 PP_FileHandle handle = GetReadonlyPnaclFd(url.c_str(),
1410 false /* is_executable */,
1411 &file_info.token_lo,
1412 &file_info.token_hi);
1413 if (handle == PP_kInvalidFileHandle) {
1414 base::ThreadTaskRunnerHandle::Get()->PostTask(
1415 FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
1416 kInvalidNaClFileInfo));
1417 return;
1419 file_info.handle = handle;
1420 base::ThreadTaskRunnerHandle::Get()->PostTask(
1421 FROM_HERE,
1422 base::Bind(callback, static_cast<int32_t>(PP_OK), file_info));
1423 return;
1426 // We have to ensure that this url resolves relative to the plugin base url
1427 // before downloading it.
1428 const GURL& test_gurl = load_manager->plugin_base_url().Resolve(url);
1429 if (!test_gurl.is_valid()) {
1430 base::ThreadTaskRunnerHandle::Get()->PostTask(
1431 FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
1432 kInvalidNaClFileInfo));
1433 return;
1436 // Try the fast path for retrieving the file first.
1437 uint64_t file_token_lo = 0;
1438 uint64_t file_token_hi = 0;
1439 PP_FileHandle file_handle = OpenNaClExecutable(instance,
1440 url.c_str(),
1441 &file_token_lo,
1442 &file_token_hi);
1443 if (file_handle != PP_kInvalidFileHandle) {
1444 PP_NaClFileInfo file_info;
1445 file_info.handle = file_handle;
1446 file_info.token_lo = file_token_lo;
1447 file_info.token_hi = file_token_hi;
1448 base::ThreadTaskRunnerHandle::Get()->PostTask(
1449 FROM_HERE,
1450 base::Bind(callback, static_cast<int32_t>(PP_OK), file_info));
1451 return;
1454 // The fast path didn't work, we'll fetch the file using URLLoader and write
1455 // it to local storage.
1456 base::File target_file(CreateTemporaryFile(instance));
1457 GURL gurl(url);
1459 content::PepperPluginInstance* plugin_instance =
1460 content::PepperPluginInstance::Get(instance);
1461 if (!plugin_instance) {
1462 base::ThreadTaskRunnerHandle::Get()->PostTask(
1463 FROM_HERE, base::Bind(callback, static_cast<int32_t>(PP_ERROR_FAILED),
1464 kInvalidNaClFileInfo));
1466 const blink::WebDocument& document =
1467 plugin_instance->GetContainer()->element().document();
1468 scoped_ptr<blink::WebURLLoader> url_loader(
1469 CreateWebURLLoader(document, gurl));
1470 blink::WebURLRequest url_request = CreateWebURLRequest(document, gurl);
1472 ProgressEventRateLimiter* tracker = new ProgressEventRateLimiter(instance);
1474 // FileDownloader deletes itself after invoking DownloadNexeCompletion.
1475 FileDownloader* file_downloader = new FileDownloader(
1476 url_loader.Pass(),
1477 target_file.Pass(),
1478 base::Bind(&DownloadFileCompletion, callback),
1479 base::Bind(&ProgressEventRateLimiter::ReportProgress,
1480 base::Owned(tracker), std::string(url)));
1481 file_downloader->Load(url_request);
1484 void LogTranslateTime(const char* histogram_name,
1485 int64_t time_in_us) {
1486 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
1487 FROM_HERE,
1488 base::Bind(&HistogramTimeTranslation,
1489 std::string(histogram_name),
1490 time_in_us / 1000));
1493 void LogBytesCompiledVsDowloaded(PP_Bool use_subzero,
1494 int64_t pexe_bytes_compiled,
1495 int64_t pexe_bytes_downloaded) {
1496 HistogramRatio("NaCl.Perf.PNaClLoadTime.PctCompiledWhenFullyDownloaded",
1497 pexe_bytes_compiled, pexe_bytes_downloaded);
1498 HistogramRatio(
1499 use_subzero
1500 ? "NaCl.Perf.PNaClLoadTime.PctCompiledWhenFullyDownloaded.Subzero"
1501 : "NaCl.Perf.PNaClLoadTime.PctCompiledWhenFullyDownloaded.LLC",
1502 pexe_bytes_compiled, pexe_bytes_downloaded);
1505 void SetPNaClStartTime(PP_Instance instance) {
1506 NexeLoadManager* load_manager = GetNexeLoadManager(instance);
1507 if (load_manager)
1508 load_manager->set_pnacl_start_time(base::Time::Now());
1511 // PexeDownloader is responsible for deleting itself when the download
1512 // finishes.
1513 class PexeDownloader : public blink::WebURLLoaderClient {
1514 public:
1515 PexeDownloader(PP_Instance instance,
1516 scoped_ptr<blink::WebURLLoader> url_loader,
1517 const std::string& pexe_url,
1518 int32_t pexe_opt_level,
1519 bool use_subzero,
1520 const PPP_PexeStreamHandler* stream_handler,
1521 void* stream_handler_user_data)
1522 : instance_(instance),
1523 url_loader_(url_loader.Pass()),
1524 pexe_url_(pexe_url),
1525 pexe_opt_level_(pexe_opt_level),
1526 use_subzero_(use_subzero),
1527 stream_handler_(stream_handler),
1528 stream_handler_user_data_(stream_handler_user_data),
1529 success_(false),
1530 expected_content_length_(-1),
1531 weak_factory_(this) {}
1533 void Load(const blink::WebURLRequest& request) {
1534 url_loader_->loadAsynchronously(request, this);
1537 private:
1538 void didReceiveResponse(blink::WebURLLoader* loader,
1539 const blink::WebURLResponse& response) override {
1540 success_ = (response.httpStatusCode() == 200);
1541 if (!success_)
1542 return;
1544 expected_content_length_ = response.expectedContentLength();
1546 // Defer loading after receiving headers. This is because we may already
1547 // have a cached translated nexe, so check for that now.
1548 url_loader_->setDefersLoading(true);
1550 std::string etag = response.httpHeaderField("etag").utf8();
1551 std::string last_modified =
1552 response.httpHeaderField("last-modified").utf8();
1553 base::Time last_modified_time;
1554 base::Time::FromString(last_modified.c_str(), &last_modified_time);
1556 bool has_no_store_header = false;
1557 std::string cache_control =
1558 response.httpHeaderField("cache-control").utf8();
1560 for (const std::string& cur : base::SplitString(
1561 cache_control, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
1562 if (base::ToLowerASCII(cur) == "no-store")
1563 has_no_store_header = true;
1566 GetNexeFd(
1567 instance_, pexe_url_, pexe_opt_level_, last_modified_time, etag,
1568 has_no_store_header, use_subzero_,
1569 base::Bind(&PexeDownloader::didGetNexeFd, weak_factory_.GetWeakPtr()));
1572 void didGetNexeFd(int32_t pp_error,
1573 bool cache_hit,
1574 PP_FileHandle file_handle) {
1575 if (!content::PepperPluginInstance::Get(instance_)) {
1576 delete this;
1577 return;
1580 HistogramEnumerate("NaCl.Perf.PNaClCache.IsHit", cache_hit, 2);
1581 HistogramEnumerate(use_subzero_ ? "NaCl.Perf.PNaClCache.IsHit.Subzero"
1582 : "NaCl.Perf.PNaClCache.IsHit.LLC",
1583 cache_hit, 2);
1584 if (cache_hit) {
1585 stream_handler_->DidCacheHit(stream_handler_user_data_, file_handle);
1587 // We delete the PexeDownloader at this point since we successfully got a
1588 // cached, translated nexe.
1589 delete this;
1590 return;
1592 stream_handler_->DidCacheMiss(stream_handler_user_data_,
1593 expected_content_length_,
1594 file_handle);
1596 // No translated nexe was found in the cache, so we should download the
1597 // file to start streaming it.
1598 url_loader_->setDefersLoading(false);
1601 void didReceiveData(blink::WebURLLoader* loader,
1602 const char* data,
1603 int data_length,
1604 int encoded_data_length) override {
1605 if (content::PepperPluginInstance::Get(instance_)) {
1606 // Stream the data we received to the stream callback.
1607 stream_handler_->DidStreamData(stream_handler_user_data_,
1608 data,
1609 data_length);
1613 void didFinishLoading(blink::WebURLLoader* loader,
1614 double finish_time,
1615 int64_t total_encoded_data_length) override {
1616 int32_t result = success_ ? PP_OK : PP_ERROR_FAILED;
1618 if (content::PepperPluginInstance::Get(instance_))
1619 stream_handler_->DidFinishStream(stream_handler_user_data_, result);
1620 delete this;
1623 void didFail(blink::WebURLLoader* loader,
1624 const blink::WebURLError& error) override {
1625 if (content::PepperPluginInstance::Get(instance_))
1626 stream_handler_->DidFinishStream(stream_handler_user_data_,
1627 PP_ERROR_FAILED);
1628 delete this;
1631 PP_Instance instance_;
1632 scoped_ptr<blink::WebURLLoader> url_loader_;
1633 std::string pexe_url_;
1634 int32_t pexe_opt_level_;
1635 bool use_subzero_;
1636 const PPP_PexeStreamHandler* stream_handler_;
1637 void* stream_handler_user_data_;
1638 bool success_;
1639 int64_t expected_content_length_;
1640 base::WeakPtrFactory<PexeDownloader> weak_factory_;
1643 void StreamPexe(PP_Instance instance,
1644 const char* pexe_url,
1645 int32_t opt_level,
1646 PP_Bool use_subzero,
1647 const PPP_PexeStreamHandler* handler,
1648 void* handler_user_data) {
1649 content::PepperPluginInstance* plugin_instance =
1650 content::PepperPluginInstance::Get(instance);
1651 if (!plugin_instance) {
1652 base::ThreadTaskRunnerHandle::Get()->PostTask(
1653 FROM_HERE, base::Bind(handler->DidFinishStream, handler_user_data,
1654 static_cast<int32_t>(PP_ERROR_FAILED)));
1655 return;
1658 GURL gurl(pexe_url);
1659 const blink::WebDocument& document =
1660 plugin_instance->GetContainer()->element().document();
1661 scoped_ptr<blink::WebURLLoader> url_loader(
1662 CreateWebURLLoader(document, gurl));
1663 PexeDownloader* downloader =
1664 new PexeDownloader(instance, url_loader.Pass(), pexe_url, opt_level,
1665 PP_ToBool(use_subzero), handler, handler_user_data);
1667 blink::WebURLRequest url_request = CreateWebURLRequest(document, gurl);
1668 // Mark the request as requesting a PNaCl bitcode file,
1669 // so that component updater can detect this user action.
1670 url_request.addHTTPHeaderField(
1671 blink::WebString::fromUTF8("Accept"),
1672 blink::WebString::fromUTF8("application/x-pnacl, */*"));
1673 url_request.setRequestContext(blink::WebURLRequest::RequestContextObject);
1674 downloader->Load(url_request);
1677 const PPB_NaCl_Private nacl_interface = {
1678 &LaunchSelLdr,
1679 &UrandomFD,
1680 &BrokerDuplicateHandle,
1681 &GetReadExecPnaclFd,
1682 &CreateTemporaryFile,
1683 &GetNumberOfProcessors,
1684 &ReportTranslationFinished,
1685 &DispatchEvent,
1686 &ReportLoadError,
1687 &InstanceCreated,
1688 &InstanceDestroyed,
1689 &GetSandboxArch,
1690 &Vlog,
1691 &InitializePlugin,
1692 &RequestNaClManifest,
1693 &GetManifestBaseURL,
1694 &ProcessNaClManifest,
1695 &ManifestGetProgramURL,
1696 &GetPNaClResourceInfo,
1697 &GetCpuFeatureAttrs,
1698 &DownloadNexe,
1699 &LogTranslateTime,
1700 &LogBytesCompiledVsDowloaded,
1701 &SetPNaClStartTime,
1702 &StreamPexe
1705 } // namespace
1707 const PPB_NaCl_Private* GetNaClPrivateInterface() {
1708 return &nacl_interface;
1711 } // namespace nacl