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"
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"
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"
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();
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());
94 bool CanOpenViaFastPath(content::PepperPluginInstance
* plugin_instance
,
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
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) {}
114 ppapi::PpapiPermissions permissions
;
115 base::ProcessId plugin_pid
;
117 IPC::ChannelHandle channel_handle
;
120 class NaClPluginInstance
{
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.
134 typedef base::ScopedPtrHashMap
<PP_Instance
, scoped_ptr
<NaClPluginInstance
>>
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())
146 NexeLoadManager
* GetNexeLoadManager(PP_Instance instance
) {
147 NaClPluginInstance
* nacl_plugin_instance
= GetNaClPluginInstance(instance
);
148 if (!nacl_plugin_instance
)
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
)
157 return nacl_plugin_instance
->json_manifest
.get();
160 static const PP_NaClFileInfo kInvalidNaClFileInfo
= {
161 PP_kInvalidFileHandle
,
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
);
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()) {
182 #if defined(OS_POSIX)
183 if (channel_handle
.socket
.fd
== -1) {
191 void PostPPCompletionCallback(PP_CompletionCallback callback
,
193 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
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
217 class ManifestServiceProxy
: public ManifestServiceChannel::Delegate
{
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
,
240 int64_t exe_size
= nacl_plugin_instance
->pexe_size
;
242 exe_size
= load_manager
->nexe_size();
243 load_manager
->ReportLoadSuccess(full_url
, exe_size
, exe_size
);
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
) {
261 base::ThreadTaskRunnerHandle::Get()->PostTask(
262 FROM_HERE
, base::Bind(callback
, base::Passed(base::File()), 0, 0));
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
,
277 base::ThreadTaskRunnerHandle::Get()->PostTask(
278 FROM_HERE
, base::Bind(callback
, base::Passed(base::File()), 0, 0));
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
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
));
294 static void DidDownloadFile(
295 ManifestServiceChannel::OpenResourceCallback callback
,
297 const PP_NaClFileInfo
& file_info
) {
298 if (pp_error
!= PP_OK
) {
299 callback
.Run(base::File(), 0, 0);
302 callback
.Run(base::File(file_info
.handle
),
307 PP_Instance pp_instance_
;
308 NaClAppProcessType process_type_
;
309 DISALLOW_COPY_AND_ASSIGN(ManifestServiceProxy
);
312 blink::WebURLLoader
* CreateWebURLLoader(const blink::WebDocument
& document
,
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;
323 options
.crossOriginRequestPolicy
=
324 blink::WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl
;
326 return document
.frame()->createAssociatedURLLoader(options
);
329 blink::WebURLRequest
CreateWebURLRequest(const blink::WebDocument
& document
,
331 blink::WebURLRequest request
;
332 request
.initialize();
333 request
.setURL(gurl
);
334 request
.setFirstPartyForCookies(document
.firstPartyForCookies());
338 int32_t FileDownloaderToPepperError(FileDownloader::Status status
) {
340 case FileDownloader::SUCCESS
:
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
,
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
,
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();
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
)));
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
);
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();
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
;
447 # error Unsupported target platform.
450 std::string error_message_string
;
451 NaClLaunchResult launch_result
;
452 if (!sender
->Send(new NaClHostMsg_LaunchNaCl(
454 instance_info
.url
.spec(),
456 nexe_file_info
->token_lo
,
457 nexe_file_info
->token_hi
,
458 resource_prefetch_request_list
,
461 PP_ToBool(uses_nonsfi_mode
),
464 &error_message_string
))) {
465 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
467 base::Bind(callback
.func
, callback
.user_data
,
468 static_cast<int32_t>(PP_ERROR_FAILED
)));
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(
488 base::Bind(callback
.func
, callback
.user_data
,
489 static_cast<int32_t>(PP_ERROR_FAILED
)));
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(
517 launch_result
.trusted_ipc_channel_handle
,
518 content::RenderThread::Get()->GetShutdownEvent(),
520 load_manager
->set_trusted_plugin_channel(trusted_plugin_channel
.Pass());
522 PostPPCompletionCallback(callback
, PP_ERROR_FAILED
);
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
);
545 content::PepperPluginInstance
* plugin_instance
=
546 content::PepperPluginInstance::Get(instance
);
547 if (!plugin_instance
) {
548 DLOG(ERROR
) << "GetInstance() failed";
552 NaClPluginInstance
* nacl_plugin_instance
= GetNaClPluginInstance(instance
);
553 if (!nacl_plugin_instance
->instance_info
) {
554 DLOG(ERROR
) << "Could not find instance ID";
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();
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.");
583 int UrandomFD(void) {
584 #if defined(OS_POSIX)
585 return base::GetUrandomFD();
591 int32_t BrokerDuplicateHandle(PP_FileHandle source_handle
,
593 PP_FileHandle
* target_handle
,
594 uint32_t desired_access
,
597 return content::BrokerDuplicateHandle(source_handle
, process_id
,
598 target_handle
, desired_access
,
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
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.
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
);
628 PP_FileHandle
GetReadonlyPnaclFd(const char* url
,
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();
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();
659 if (!sender
->Send(new NaClHostMsg_NaClCreateTemporaryFile(
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();
674 int32_t num_processors
= 1;
675 return sender
->Send(new NaClHostMsg_NaClGetNumProcessors(&num_processors
)) ?
679 void GetNexeFd(PP_Instance instance
,
680 const std::string
& pexe_url
,
682 const base::Time
& last_modified_time
,
683 const std::string
& etag
,
684 bool has_no_store_header
,
686 base::Callback
<void(int32_t, bool, PP_FileHandle
)> callback
) {
687 if (!InitializePnaclResourceHost()) {
688 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
691 static_cast<int32_t>(PP_ERROR_FAILED
),
693 PP_kInvalidFileHandle
));
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
),
717 void LogTranslationFinishedUMA(const std::string
& uma_suffix
,
719 int32_t unknown_opt_level
,
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
,
730 HistogramSizeKB("NaCl.Perf.Size.Pexe" + uma_suffix
, pexe_size
/ 1024);
731 HistogramRatio("NaCl.Perf.Size.PexeNexeSizePct" + uma_suffix
, pexe_size
,
733 HistogramTimeTranslation(
734 "NaCl.Perf.PNaClLoadTime.TotalUncachedTime" + uma_suffix
,
735 total_time
.InMilliseconds());
737 "NaCl.Perf.PNaClLoadTime.TotalUncachedKBPerSec" + uma_suffix
,
738 pexe_size
/ 1024, total_time
.InMicroseconds());
741 void ReportTranslationFinished(PP_Instance instance
,
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
,
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
)
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
,
782 uint64_t* nonce_hi
) {
783 NexeLoadManager
* load_manager
= GetNexeLoadManager(instance
);
784 DCHECK(load_manager
);
786 return PP_kInvalidFileHandle
;
788 content::PepperPluginInstance
* plugin_instance
=
789 content::PepperPluginInstance::Get(instance
);
790 if (!plugin_instance
)
791 return PP_kInvalidFileHandle
;
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();
803 base::FilePath file_path
;
805 new NaClHostMsg_OpenNaClExecutable(GetRoutingID(instance
),
807 !load_manager
->nonsfi(),
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
,
828 PP_ToBool(length_is_computable
),
831 DispatchProgressEvent(instance
, event
);
834 void ReportLoadError(PP_Instance instance
,
836 const char* error_message
) {
837 NexeLoadManager
* load_manager
= GetNexeLoadManager(instance
);
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
));
862 PP_Bool
NaClDebugEnabledForURL(const char* alleged_nmf_url
) {
863 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
864 switches::kEnableNaClDebug
))
866 IPC::Sender
* sender
= content::RenderThread::Get();
868 bool should_debug
= false;
870 sender
->Send(new NaClHostMsg_NaClDebugEnabledForURL(GURL(alleged_nmf_url
),
875 void Vlog(const char* message
) {
879 void InitializePlugin(PP_Instance instance
,
882 const char* argv
[]) {
883 NexeLoadManager
* load_manager
= GetNexeLoadManager(instance
);
884 DCHECK(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
);
901 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
903 base::Bind(callback
.func
, callback
.user_data
,
904 static_cast<int32_t>(PP_ERROR_FAILED
)));
908 std::string url
= load_manager
->GetManifestURLArgument();
909 if (url
.empty() || !load_manager
->RequestNaClManifest(url
)) {
910 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
912 base::Bind(callback
.func
, callback
.user_data
,
913 static_cast<int32_t>(PP_ERROR_FAILED
)));
917 const GURL
& base_url
= load_manager
->manifest_base_url();
918 if (base_url
.SchemeIs("data")) {
920 std::string mime_type
;
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
))
929 load_manager
->ReportLoadError(PP_NACL_ERROR_MANIFEST_TOO_LARGE
,
930 "manifest file too large.");
933 load_manager
->ReportLoadError(PP_NACL_ERROR_MANIFEST_LOAD_URL
,
934 "could not load manifest url.");
936 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
938 base::Bind(callback
.func
, callback
.user_data
, error
));
940 DownloadManifestToBuffer(instance
, callback
);
944 PP_Var
GetManifestBaseURL(PP_Instance instance
) {
945 NexeLoadManager
* load_manager
= GetNexeLoadManager(instance
);
946 DCHECK(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
);
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(
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(
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
);
1012 switch (pp_nacl_error
) {
1013 case PP_NACL_ERROR_LOAD_SUCCESS
:
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.");
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.");
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.");
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
);
1056 const char* isa_type
;
1057 if (load_manager
->IsPNaCl())
1058 isa_type
= kPortableArch
;
1060 isa_type
= GetSandboxArch();
1062 scoped_ptr
<nacl::JsonManifest
> j(
1063 new nacl::JsonManifest(
1064 manifest_url
.c_str(),
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());
1073 load_manager
->ReportLoadError(error_info
.error
, error_info
.string
);
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
)
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
,
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;
1107 load_manager
->ReportLoadError(error_info
.error
, error_info
.string
);
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() + "/" +
1125 JsonManifest
* manifest
= GetJsonManifest(instance
);
1126 if (manifest
== NULL
)
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
);
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 "
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: ") +
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
);
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: ") +
1180 int rc
= file
.Read(0, buffer
.get(), file_info
.size
);
1182 load_manager
->ReportLoadError(
1183 PP_NACL_ERROR_PNACL_RESOURCE_FETCH
,
1184 std::string("GetPNaClResourceInfo, reading failed for: ") + kFilename
);
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(
1197 base::JSON_PARSE_RFC
,
1198 &json_read_error_code
,
1199 &json_read_error_msg
));
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
);
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");
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
);
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
;
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
{
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
,
1259 total_bytes_to_be_received
>= 0,
1260 total_bytes_received
,
1261 total_bytes_to_be_received
));
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
,
1277 void DownloadNexe(PP_Instance instance
,
1279 PP_NaClFileInfo
* out_file_info
,
1280 PP_CompletionCallback callback
) {
1282 CHECK(out_file_info
);
1283 DownloadNexeRequest request
;
1284 request
.instance
= instance
;
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
,
1292 &out_file_info
->token_lo
,
1293 &out_file_info
->token_hi
);
1294 if (handle
!= PP_kInvalidFileHandle
) {
1295 DownloadNexeCompletion(request
,
1297 FileDownloader::SUCCESS
,
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
));
1308 content::PepperPluginInstance
* plugin_instance
=
1309 content::PepperPluginInstance::Get(instance
);
1310 if (!plugin_instance
) {
1311 ppapi::PpapiGlobals::Get()->GetMainThreadMessageLoop()->PostTask(
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(
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
,
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
);
1356 load_manager
->NexeFileDidOpen(pp_error
,
1364 if (pp_error
== PP_OK
&& target_file
.IsValid())
1365 out_file_info
->handle
= target_file
.TakePlatformFile();
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
,
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;
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
));
1405 // Handle special PNaCl support files which are installed on the user's
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
));
1419 file_info
.handle
= handle
;
1420 base::ThreadTaskRunnerHandle::Get()->PostTask(
1422 base::Bind(callback
, static_cast<int32_t>(PP_OK
), file_info
));
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
));
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
,
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(
1450 base::Bind(callback
, static_cast<int32_t>(PP_OK
), file_info
));
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
));
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(
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(
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
);
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
);
1508 load_manager
->set_pnacl_start_time(base::Time::Now());
1511 // PexeDownloader is responsible for deleting itself when the download
1513 class PexeDownloader
: public blink::WebURLLoaderClient
{
1515 PexeDownloader(PP_Instance instance
,
1516 scoped_ptr
<blink::WebURLLoader
> url_loader
,
1517 const std::string
& pexe_url
,
1518 int32_t pexe_opt_level
,
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
),
1530 expected_content_length_(-1),
1531 weak_factory_(this) {}
1533 void Load(const blink::WebURLRequest
& request
) {
1534 url_loader_
->loadAsynchronously(request
, this);
1538 void didReceiveResponse(blink::WebURLLoader
* loader
,
1539 const blink::WebURLResponse
& response
) override
{
1540 success_
= (response
.httpStatusCode() == 200);
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;
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
,
1574 PP_FileHandle file_handle
) {
1575 if (!content::PepperPluginInstance::Get(instance_
)) {
1580 HistogramEnumerate("NaCl.Perf.PNaClCache.IsHit", cache_hit
, 2);
1581 HistogramEnumerate(use_subzero_
? "NaCl.Perf.PNaClCache.IsHit.Subzero"
1582 : "NaCl.Perf.PNaClCache.IsHit.LLC",
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.
1592 stream_handler_
->DidCacheMiss(stream_handler_user_data_
,
1593 expected_content_length_
,
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
,
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_
,
1613 void didFinishLoading(blink::WebURLLoader
* loader
,
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
);
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_
,
1631 PP_Instance instance_
;
1632 scoped_ptr
<blink::WebURLLoader
> url_loader_
;
1633 std::string pexe_url_
;
1634 int32_t pexe_opt_level_
;
1636 const PPP_PexeStreamHandler
* stream_handler_
;
1637 void* stream_handler_user_data_
;
1639 int64_t expected_content_length_
;
1640 base::WeakPtrFactory
<PexeDownloader
> weak_factory_
;
1643 void StreamPexe(PP_Instance instance
,
1644 const char* pexe_url
,
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
)));
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
= {
1680 &BrokerDuplicateHandle
,
1681 &GetReadExecPnaclFd
,
1682 &CreateTemporaryFile
,
1683 &GetNumberOfProcessors
,
1684 &ReportTranslationFinished
,
1692 &RequestNaClManifest
,
1693 &GetManifestBaseURL
,
1694 &ProcessNaClManifest
,
1695 &ManifestGetProgramURL
,
1696 &GetPNaClResourceInfo
,
1697 &GetCpuFeatureAttrs
,
1700 &LogBytesCompiledVsDowloaded
,
1707 const PPB_NaCl_Private
* GetNaClPrivateInterface() {
1708 return &nacl_interface
;