1 // Copyright (c) 2012 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 "content/ppapi_plugin/ppapi_thread.h"
9 #include "base/command_line.h"
11 #include "base/debug/crash_logging.h"
12 #include "base/files/file_util.h"
13 #include "base/logging.h"
14 #include "base/memory/discardable_memory_allocator.h"
15 #include "base/metrics/histogram.h"
16 #include "base/metrics/sparse_histogram.h"
17 #include "base/rand_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/threading/platform_thread.h"
21 #include "base/time/time.h"
22 #include "content/child/browser_font_resource_trusted.h"
23 #include "content/child/child_discardable_shared_memory_manager.h"
24 #include "content/child/child_process.h"
25 #include "content/common/child_process_messages.h"
26 #include "content/common/sandbox_util.h"
27 #include "content/ppapi_plugin/broker_process_dispatcher.h"
28 #include "content/ppapi_plugin/plugin_process_dispatcher.h"
29 #include "content/ppapi_plugin/ppapi_blink_platform_impl.h"
30 #include "content/public/common/content_client.h"
31 #include "content/public/common/content_switches.h"
32 #include "content/public/common/pepper_plugin_info.h"
33 #include "content/public/common/sandbox_init.h"
34 #include "content/public/plugin/content_plugin_client.h"
35 #include "ipc/ipc_channel_handle.h"
36 #include "ipc/ipc_platform_file.h"
37 #include "ipc/ipc_sync_channel.h"
38 #include "ipc/ipc_sync_message_filter.h"
39 #include "ppapi/c/dev/ppp_network_state_dev.h"
40 #include "ppapi/c/pp_errors.h"
41 #include "ppapi/c/ppp.h"
42 #include "ppapi/proxy/interface_list.h"
43 #include "ppapi/proxy/plugin_globals.h"
44 #include "ppapi/proxy/plugin_message_filter.h"
45 #include "ppapi/proxy/ppapi_messages.h"
46 #include "ppapi/proxy/resource_reply_thread_registrar.h"
47 #include "third_party/WebKit/public/web/WebKit.h"
48 #include "ui/base/ui_base_switches.h"
51 #include "base/win/win_util.h"
52 #include "base/win/windows_version.h"
53 #include "sandbox/win/src/sandbox.h"
54 #elif defined(OS_MACOSX)
55 #include "content/common/sandbox_init_mac.h"
59 const char kWidevineCdmAdapterFileName
[] = "widevinecdmadapter.dll";
61 extern sandbox::TargetServices
* g_target_services
;
63 // Used by EnumSystemLocales for warming up.
64 static BOOL CALLBACK
EnumLocalesProc(LPTSTR lpLocaleString
) {
68 static BOOL CALLBACK
EnumLocalesProcEx(
69 LPWSTR lpLocaleString
,
75 // Warm up language subsystems before the sandbox is turned on.
76 static void WarmupWindowsLocales(const ppapi::PpapiPermissions
& permissions
) {
77 ::GetUserDefaultLangID();
78 ::GetUserDefaultLCID();
80 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
)) {
81 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
82 typedef BOOL (WINAPI
*PfnEnumSystemLocalesEx
)
83 (LOCALE_ENUMPROCEX
, DWORD
, LPARAM
, LPVOID
);
85 HMODULE handle_kern32
= GetModuleHandleW(L
"Kernel32.dll");
86 PfnEnumSystemLocalesEx enum_sys_locales_ex
=
87 reinterpret_cast<PfnEnumSystemLocalesEx
>
88 (GetProcAddress(handle_kern32
, "EnumSystemLocalesEx"));
90 enum_sys_locales_ex(EnumLocalesProcEx
, LOCALE_WINDOWS
, 0, 0);
92 EnumSystemLocalesW(EnumLocalesProc
, LCID_INSTALLED
);
101 typedef int32_t (*InitializeBrokerFunc
)
102 (PP_ConnectInstance_Func
* connect_instance_func
);
104 PpapiThread::PpapiThread(const base::CommandLine
& command_line
, bool is_broker
)
105 : is_broker_(is_broker
),
106 plugin_globals_(GetIOTaskRunner()),
107 connect_instance_func_(NULL
),
108 local_pp_module_(base::RandInt(0, std::numeric_limits
<PP_Module
>::max())),
109 next_plugin_dispatcher_id_(1) {
110 plugin_globals_
.SetPluginProxyDelegate(this);
111 plugin_globals_
.set_command_line(
112 command_line
.GetSwitchValueASCII(switches::kPpapiFlashArgs
));
114 blink_platform_impl_
.reset(new PpapiBlinkPlatformImpl
);
115 blink::initialize(blink_platform_impl_
.get());
118 scoped_refptr
<ppapi::proxy::PluginMessageFilter
> plugin_filter(
119 new ppapi::proxy::PluginMessageFilter(
120 NULL
, plugin_globals_
.resource_reply_thread_registrar()));
121 channel()->AddFilter(plugin_filter
.get());
122 plugin_globals_
.RegisterResourceMessageFilters(plugin_filter
.get());
125 // In single process, browser main loop set up the discardable memory
127 if (!command_line
.HasSwitch(switches::kSingleProcess
)) {
128 base::DiscardableMemoryAllocator::SetInstance(
129 ChildThreadImpl::discardable_shared_memory_manager());
133 PpapiThread::~PpapiThread() {
136 void PpapiThread::Shutdown() {
137 ChildThreadImpl::Shutdown();
139 ppapi::proxy::PluginGlobals::Get()->ResetPluginProxyDelegate();
140 if (plugin_entry_points_
.shutdown_module
)
141 plugin_entry_points_
.shutdown_module();
142 blink_platform_impl_
->Shutdown();
146 bool PpapiThread::Send(IPC::Message
* msg
) {
147 // Allow access from multiple threads.
148 if (base::MessageLoop::current() == message_loop())
149 return ChildThreadImpl::Send(msg
);
151 return sync_message_filter()->Send(msg
);
154 // Note that this function is called only for messages from the channel to the
155 // browser process. Messages from the renderer process are sent via a different
156 // channel that ends up at Dispatcher::OnMessageReceived.
157 bool PpapiThread::OnControlMessageReceived(const IPC::Message
& msg
) {
159 IPC_BEGIN_MESSAGE_MAP(PpapiThread
, msg
)
160 IPC_MESSAGE_HANDLER(PpapiMsg_LoadPlugin
, OnLoadPlugin
)
161 IPC_MESSAGE_HANDLER(PpapiMsg_CreateChannel
, OnCreateChannel
)
162 IPC_MESSAGE_HANDLER(PpapiMsg_SetNetworkState
, OnSetNetworkState
)
163 IPC_MESSAGE_HANDLER(PpapiMsg_Crash
, OnCrash
)
164 IPC_MESSAGE_HANDLER(PpapiMsg_Hang
, OnHang
)
165 IPC_MESSAGE_UNHANDLED(handled
= false)
166 IPC_END_MESSAGE_MAP()
170 void PpapiThread::OnChannelConnected(int32 peer_pid
) {
171 ChildThreadImpl::OnChannelConnected(peer_pid
);
174 peer_handle_
.Set(::OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, peer_pid
));
178 base::SingleThreadTaskRunner
* PpapiThread::GetIPCTaskRunner() {
179 return ChildProcess::current()->io_task_runner();
182 base::WaitableEvent
* PpapiThread::GetShutdownEvent() {
183 return ChildProcess::current()->GetShutDownEvent();
186 IPC::PlatformFileForTransit
PpapiThread::ShareHandleWithRemote(
187 base::PlatformFile handle
,
188 base::ProcessId peer_pid
,
189 bool should_close_source
) {
191 if (peer_handle_
.IsValid()) {
193 return IPC::GetFileHandleForProcess(handle
, peer_handle_
.Get(),
194 should_close_source
);
198 DCHECK(peer_pid
!= base::kNullProcessId
);
199 return BrokerGetFileHandleForProcess(handle
, peer_pid
, should_close_source
);
202 base::SharedMemoryHandle
PpapiThread::ShareSharedMemoryHandleWithRemote(
203 const base::SharedMemoryHandle
& handle
,
204 base::ProcessId remote_pid
) {
206 if (peer_handle_
.IsValid()) {
208 return IPC::GetFileHandleForProcess(handle
, peer_handle_
.Get(), false);
212 DCHECK(remote_pid
!= base::kNullProcessId
);
213 #if defined(OS_WIN) || defined(OS_MACOSX)
214 base::SharedMemoryHandle duped_handle
;
216 BrokerDuplicateSharedMemoryHandle(handle
, remote_pid
, &duped_handle
);
219 return base::SharedMemory::NULLHandle();
221 return base::SharedMemory::DuplicateHandle(handle
);
222 #endif // defined(OS_WIN) || defined(OS_MACOSX)
225 std::set
<PP_Instance
>* PpapiThread::GetGloballySeenInstanceIDSet() {
226 return &globally_seen_instance_ids_
;
229 IPC::Sender
* PpapiThread::GetBrowserSender() {
233 std::string
PpapiThread::GetUILanguage() {
234 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
235 return command_line
->GetSwitchValueASCII(switches::kLang
);
238 void PpapiThread::PreCacheFont(const void* logfontw
) {
240 ChildThreadImpl::PreCacheFont(*static_cast<const LOGFONTW
*>(logfontw
));
244 void PpapiThread::SetActiveURL(const std::string
& url
) {
245 GetContentClient()->SetActiveURL(GURL(url
));
248 PP_Resource
PpapiThread::CreateBrowserFont(
249 ppapi::proxy::Connection connection
,
250 PP_Instance instance
,
251 const PP_BrowserFont_Trusted_Description
& desc
,
252 const ppapi::Preferences
& prefs
) {
253 if (!BrowserFontResource_Trusted::IsPPFontDescriptionValid(desc
))
255 return (new BrowserFontResource_Trusted(
256 connection
, instance
, desc
, prefs
))->GetReference();
259 uint32
PpapiThread::Register(ppapi::proxy::PluginDispatcher
* plugin_dispatcher
) {
260 if (!plugin_dispatcher
||
261 plugin_dispatchers_
.size() >= std::numeric_limits
<uint32
>::max()) {
267 // Although it is unlikely, make sure that we won't cause any trouble when
268 // the counter overflows.
269 id
= next_plugin_dispatcher_id_
++;
271 plugin_dispatchers_
.find(id
) != plugin_dispatchers_
.end());
272 plugin_dispatchers_
[id
] = plugin_dispatcher
;
276 void PpapiThread::Unregister(uint32 plugin_dispatcher_id
) {
277 plugin_dispatchers_
.erase(plugin_dispatcher_id
);
280 void PpapiThread::OnLoadPlugin(const base::FilePath
& path
,
281 const ppapi::PpapiPermissions
& permissions
) {
282 // In case of crashes, the crash dump doesn't indicate which plugin
284 base::debug::SetCrashKeyValue("ppapi_path", path
.MaybeAsASCII());
286 SavePluginName(path
);
288 // This must be set before calling into the plugin so it can get the
289 // interfaces it has permission for.
290 ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(permissions
);
291 permissions_
= permissions
;
293 // Trusted Pepper plugins may be "internal", i.e. built-in to the browser
294 // binary. If we're being asked to load such a plugin (e.g. the Chromoting
295 // client) then fetch the entry points from the embedder, rather than a DLL.
296 std::vector
<PepperPluginInfo
> plugins
;
297 GetContentClient()->AddPepperPlugins(&plugins
);
298 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
299 if (plugins
[i
].is_internal
&& plugins
[i
].path
== path
) {
300 // An internal plugin is being loaded, so fetch the entry points.
301 plugin_entry_points_
= plugins
[i
].internal_entry_points
;
305 // If the plugin isn't internal then load it from |path|.
306 base::ScopedNativeLibrary library
;
307 if (plugin_entry_points_
.initialize_module
== NULL
) {
308 // Load the plugin from the specified library.
309 base::NativeLibraryLoadError error
;
310 library
.Reset(base::LoadNativeLibrary(path
, &error
));
311 if (!library
.is_valid()) {
312 LOG(ERROR
) << "Failed to load Pepper module from " << path
.value()
313 << " (error: " << error
.ToString() << ")";
314 if (!base::PathExists(path
)) {
315 ReportLoadResult(path
, FILE_MISSING
);
318 ReportLoadResult(path
, LOAD_FAILED
);
319 // Report detailed reason for load failure.
320 ReportLoadErrorCode(path
, error
);
324 // Get the GetInterface function (required).
325 plugin_entry_points_
.get_interface
=
326 reinterpret_cast<PP_GetInterface_Func
>(
327 library
.GetFunctionPointer("PPP_GetInterface"));
328 if (!plugin_entry_points_
.get_interface
) {
329 LOG(WARNING
) << "No PPP_GetInterface in plugin library";
330 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
334 // The ShutdownModule/ShutdownBroker function is optional.
335 plugin_entry_points_
.shutdown_module
=
337 reinterpret_cast<PP_ShutdownModule_Func
>(
338 library
.GetFunctionPointer("PPP_ShutdownBroker")) :
339 reinterpret_cast<PP_ShutdownModule_Func
>(
340 library
.GetFunctionPointer("PPP_ShutdownModule"));
343 // Get the InitializeModule function (required for non-broker code).
344 plugin_entry_points_
.initialize_module
=
345 reinterpret_cast<PP_InitializeModule_Func
>(
346 library
.GetFunctionPointer("PPP_InitializeModule"));
347 if (!plugin_entry_points_
.initialize_module
) {
348 LOG(WARNING
) << "No PPP_InitializeModule in plugin library";
349 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
356 // If code subsequently tries to exit using abort(), force a crash (since
357 // otherwise these would be silent terminations and fly under the radar).
358 base::win::SetAbortBehaviorForCrashReporting();
360 // Once we lower the token the sandbox is locked down and no new modules
361 // can be loaded. TODO(cpu): consider changing to the loading style of
363 if (g_target_services
) {
364 // Let Flash and Widevine CDM adapter load DXVA before lockdown on Vista+.
365 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
) ||
366 path
.BaseName().MaybeAsASCII() == kWidevineCdmAdapterFileName
) {
367 if (base::win::OSInfo::GetInstance()->version() >=
368 base::win::VERSION_VISTA
) {
369 LoadLibraryA("dxva2.dll");
373 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
)) {
374 if (base::win::OSInfo::GetInstance()->version() >=
375 base::win::VERSION_WIN7
) {
377 if (cpu
.vendor_name() == "AuthenticAMD") {
378 // The AMD crypto acceleration is only AMD Bulldozer and above.
380 LoadLibraryA("amdhcp64.dll");
382 LoadLibraryA("amdhcp32.dll");
388 // Cause advapi32 to load before the sandbox is turned on.
389 unsigned int dummy_rand
;
392 WarmupWindowsLocales(permissions
);
394 #if defined(ADDRESS_SANITIZER)
395 // Bind and leak dbghelp.dll before the token is lowered, otherwise
396 // AddressSanitizer will crash when trying to symbolize a report.
397 LoadLibraryA("dbghelp.dll");
400 g_target_services
->LowerToken();
405 // Get the InitializeBroker function (required).
406 InitializeBrokerFunc init_broker
=
407 reinterpret_cast<InitializeBrokerFunc
>(
408 library
.GetFunctionPointer("PPP_InitializeBroker"));
410 LOG(WARNING
) << "No PPP_InitializeBroker in plugin library";
411 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
415 int32_t init_error
= init_broker(&connect_instance_func_
);
416 if (init_error
!= PP_OK
) {
417 LOG(WARNING
) << "InitBroker failed with error " << init_error
;
418 ReportLoadResult(path
, INIT_FAILED
);
421 if (!connect_instance_func_
) {
422 LOG(WARNING
) << "InitBroker did not provide PP_ConnectInstance_Func";
423 ReportLoadResult(path
, INIT_FAILED
);
427 #if defined(OS_MACOSX)
428 // We need to do this after getting |PPP_GetInterface()| (or presumably
429 // doing something nontrivial with the library), else the sandbox
431 CHECK(InitializeSandbox());
434 int32_t init_error
= plugin_entry_points_
.initialize_module(
436 &ppapi::proxy::PluginDispatcher::GetBrowserInterface
);
437 if (init_error
!= PP_OK
) {
438 LOG(WARNING
) << "InitModule failed with error " << init_error
;
439 ReportLoadResult(path
, INIT_FAILED
);
444 // Initialization succeeded, so keep the plugin DLL loaded.
445 library_
.Reset(library
.Release());
447 ReportLoadResult(path
, LOAD_SUCCESS
);
450 void PpapiThread::OnCreateChannel(base::ProcessId renderer_pid
,
451 int renderer_child_id
,
453 IPC::ChannelHandle channel_handle
;
455 if (!plugin_entry_points_
.get_interface
|| // Plugin couldn't be loaded.
456 !SetupRendererChannel(renderer_pid
, renderer_child_id
, incognito
,
458 Send(new PpapiHostMsg_ChannelCreated(IPC::ChannelHandle()));
462 Send(new PpapiHostMsg_ChannelCreated(channel_handle
));
465 void PpapiThread::OnSetNetworkState(bool online
) {
466 // Note the browser-process side shouldn't send us these messages in the
467 // first unless the plugin has dev permissions, so we don't need to check
468 // again here. We don't want random plugins depending on this dev interface.
469 if (!plugin_entry_points_
.get_interface
)
471 const PPP_NetworkState_Dev
* ns
= static_cast<const PPP_NetworkState_Dev
*>(
472 plugin_entry_points_
.get_interface(PPP_NETWORK_STATE_DEV_INTERFACE
));
474 ns
->SetOnLine(PP_FromBool(online
));
477 void PpapiThread::OnCrash() {
478 // Intentionally crash upon the request of the browser.
479 volatile int* null_pointer
= NULL
;
483 void PpapiThread::OnHang() {
484 // Intentionally hang upon the request of the browser.
486 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
489 bool PpapiThread::SetupRendererChannel(base::ProcessId renderer_pid
,
490 int renderer_child_id
,
492 IPC::ChannelHandle
* handle
) {
493 DCHECK(is_broker_
== (connect_instance_func_
!= NULL
));
494 IPC::ChannelHandle plugin_handle
;
495 plugin_handle
.name
= IPC::Channel::GenerateVerifiedChannelID(
497 "%d.r%d", base::GetCurrentProcId(), renderer_child_id
));
499 ppapi::proxy::ProxyChannel
* dispatcher
= NULL
;
500 bool init_result
= false;
502 BrokerProcessDispatcher
* broker_dispatcher
=
503 new BrokerProcessDispatcher(plugin_entry_points_
.get_interface
,
504 connect_instance_func_
);
505 init_result
= broker_dispatcher
->InitBrokerWithChannel(this,
509 dispatcher
= broker_dispatcher
;
511 PluginProcessDispatcher
* plugin_dispatcher
=
512 new PluginProcessDispatcher(plugin_entry_points_
.get_interface
,
515 init_result
= plugin_dispatcher
->InitPluginWithChannel(this,
519 dispatcher
= plugin_dispatcher
;
527 handle
->name
= plugin_handle
.name
;
528 #if defined(OS_POSIX)
529 // On POSIX, transfer ownership of the renderer-side (client) FD.
530 // This ensures this process will be notified when it is closed even if a
531 // connection is not established.
532 handle
->socket
= base::FileDescriptor(dispatcher
->TakeRendererFD());
533 if (handle
->socket
.fd
== -1)
537 // From here, the dispatcher will manage its own lifetime according to the
538 // lifetime of the attached channel.
542 void PpapiThread::SavePluginName(const base::FilePath
& path
) {
543 ppapi::proxy::PluginGlobals::Get()->set_plugin_name(
544 path
.BaseName().AsUTF8Unsafe());
546 // plugin() is NULL when in-process, which is fine, because this is
547 // just a hook for setting the process name.
548 if (GetContentClient()->plugin()) {
549 GetContentClient()->plugin()->PluginProcessStarted(
550 path
.BaseName().RemoveExtension().LossyDisplayName());
554 void PpapiThread::ReportLoadResult(const base::FilePath
& path
,
556 DCHECK_LT(result
, LOAD_RESULT_MAX
);
557 std::string histogram_name
= std::string("Plugin.Ppapi") +
558 (is_broker_
? "Broker" : "Plugin") +
559 "LoadResult_" + path
.BaseName().MaybeAsASCII();
561 // Note: This leaks memory, which is expected behavior.
562 base::HistogramBase
* histogram
=
563 base::LinearHistogram::FactoryGet(
568 base::HistogramBase::kUmaTargetedHistogramFlag
);
570 histogram
->Add(result
);
573 void PpapiThread::ReportLoadErrorCode(
574 const base::FilePath
& path
,
575 const base::NativeLibraryLoadError
& error
) {
577 // Only report load error code on Windows because that's the only platform
578 // that has a numerical error value.
579 std::string histogram_name
=
580 std::string("Plugin.Ppapi") + (is_broker_
? "Broker" : "Plugin") +
581 "LoadErrorCode_" + path
.BaseName().MaybeAsASCII();
583 // For sparse histograms, we can use the macro, as it does not incorporate a
585 UMA_HISTOGRAM_SPARSE_SLOWLY(histogram_name
, error
.code
);
589 } // namespace content