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/metrics/histogram.h"
15 #include "base/metrics/sparse_histogram.h"
16 #include "base/rand_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/threading/platform_thread.h"
20 #include "base/time/time.h"
21 #include "content/child/browser_font_resource_trusted.h"
22 #include "content/child/child_process.h"
23 #include "content/common/child_process_messages.h"
24 #include "content/common/sandbox_util.h"
25 #include "content/ppapi_plugin/broker_process_dispatcher.h"
26 #include "content/ppapi_plugin/plugin_process_dispatcher.h"
27 #include "content/ppapi_plugin/ppapi_blink_platform_impl.h"
28 #include "content/public/common/content_client.h"
29 #include "content/public/common/content_switches.h"
30 #include "content/public/common/pepper_plugin_info.h"
31 #include "content/public/common/sandbox_init.h"
32 #include "content/public/plugin/content_plugin_client.h"
33 #include "ipc/ipc_channel_handle.h"
34 #include "ipc/ipc_platform_file.h"
35 #include "ipc/ipc_sync_channel.h"
36 #include "ipc/ipc_sync_message_filter.h"
37 #include "ppapi/c/dev/ppp_network_state_dev.h"
38 #include "ppapi/c/pp_errors.h"
39 #include "ppapi/c/ppp.h"
40 #include "ppapi/proxy/interface_list.h"
41 #include "ppapi/proxy/plugin_globals.h"
42 #include "ppapi/proxy/plugin_message_filter.h"
43 #include "ppapi/proxy/ppapi_messages.h"
44 #include "ppapi/proxy/resource_reply_thread_registrar.h"
45 #include "third_party/WebKit/public/web/WebKit.h"
46 #include "ui/base/ui_base_switches.h"
49 #include "base/win/win_util.h"
50 #include "base/win/windows_version.h"
51 #include "sandbox/win/src/sandbox.h"
52 #elif defined(OS_MACOSX)
53 #include "content/common/sandbox_init_mac.h"
57 const char kWidevineCdmAdapterFileName
[] = "widevinecdmadapter.dll";
59 extern sandbox::TargetServices
* g_target_services
;
61 // Used by EnumSystemLocales for warming up.
62 static BOOL CALLBACK
EnumLocalesProc(LPTSTR lpLocaleString
) {
66 static BOOL CALLBACK
EnumLocalesProcEx(
67 LPWSTR lpLocaleString
,
73 // Warm up language subsystems before the sandbox is turned on.
74 static void WarmupWindowsLocales(const ppapi::PpapiPermissions
& permissions
) {
75 ::GetUserDefaultLangID();
76 ::GetUserDefaultLCID();
78 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
)) {
79 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
80 typedef BOOL (WINAPI
*PfnEnumSystemLocalesEx
)
81 (LOCALE_ENUMPROCEX
, DWORD
, LPARAM
, LPVOID
);
83 HMODULE handle_kern32
= GetModuleHandleW(L
"Kernel32.dll");
84 PfnEnumSystemLocalesEx enum_sys_locales_ex
=
85 reinterpret_cast<PfnEnumSystemLocalesEx
>
86 (GetProcAddress(handle_kern32
, "EnumSystemLocalesEx"));
88 enum_sys_locales_ex(EnumLocalesProcEx
, LOCALE_WINDOWS
, 0, 0);
90 EnumSystemLocalesW(EnumLocalesProc
, LCID_INSTALLED
);
99 typedef int32_t (*InitializeBrokerFunc
)
100 (PP_ConnectInstance_Func
* connect_instance_func
);
102 PpapiThread::PpapiThread(const base::CommandLine
& command_line
, bool is_broker
)
103 : is_broker_(is_broker
),
104 connect_instance_func_(NULL
),
105 local_pp_module_(base::RandInt(0, std::numeric_limits
<PP_Module
>::max())),
106 next_plugin_dispatcher_id_(1) {
107 ppapi::proxy::PluginGlobals
* globals
= ppapi::proxy::PluginGlobals::Get();
108 globals
->SetPluginProxyDelegate(this);
109 globals
->set_command_line(
110 command_line
.GetSwitchValueASCII(switches::kPpapiFlashArgs
));
112 blink_platform_impl_
.reset(new PpapiBlinkPlatformImpl
);
113 blink::initialize(blink_platform_impl_
.get());
116 channel()->AddFilter(
117 new ppapi::proxy::PluginMessageFilter(
118 NULL
, globals
->resource_reply_thread_registrar()));
122 PpapiThread::~PpapiThread() {
125 void PpapiThread::Shutdown() {
126 ChildThreadImpl::Shutdown();
128 ppapi::proxy::PluginGlobals::Get()->ResetPluginProxyDelegate();
129 if (plugin_entry_points_
.shutdown_module
)
130 plugin_entry_points_
.shutdown_module();
131 blink_platform_impl_
->Shutdown();
135 bool PpapiThread::Send(IPC::Message
* msg
) {
136 // Allow access from multiple threads.
137 if (base::MessageLoop::current() == message_loop())
138 return ChildThreadImpl::Send(msg
);
140 return sync_message_filter()->Send(msg
);
143 // Note that this function is called only for messages from the channel to the
144 // browser process. Messages from the renderer process are sent via a different
145 // channel that ends up at Dispatcher::OnMessageReceived.
146 bool PpapiThread::OnControlMessageReceived(const IPC::Message
& msg
) {
148 IPC_BEGIN_MESSAGE_MAP(PpapiThread
, msg
)
149 IPC_MESSAGE_HANDLER(PpapiMsg_LoadPlugin
, OnLoadPlugin
)
150 IPC_MESSAGE_HANDLER(PpapiMsg_CreateChannel
, OnCreateChannel
)
151 IPC_MESSAGE_HANDLER(PpapiMsg_SetNetworkState
, OnSetNetworkState
)
152 IPC_MESSAGE_HANDLER(PpapiMsg_Crash
, OnCrash
)
153 IPC_MESSAGE_HANDLER(PpapiMsg_Hang
, OnHang
)
154 IPC_MESSAGE_UNHANDLED(handled
= false)
155 IPC_END_MESSAGE_MAP()
159 void PpapiThread::OnChannelConnected(int32 peer_pid
) {
160 ChildThreadImpl::OnChannelConnected(peer_pid
);
163 peer_handle_
.Set(::OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, peer_pid
));
167 base::MessageLoopProxy
* PpapiThread::GetIPCMessageLoop() {
168 return ChildProcess::current()->io_message_loop_proxy();
171 base::WaitableEvent
* PpapiThread::GetShutdownEvent() {
172 return ChildProcess::current()->GetShutDownEvent();
175 IPC::PlatformFileForTransit
PpapiThread::ShareHandleWithRemote(
176 base::PlatformFile handle
,
177 base::ProcessId peer_pid
,
178 bool should_close_source
) {
180 if (peer_handle_
.IsValid()) {
182 return IPC::GetFileHandleForProcess(handle
, peer_handle_
.Get(),
183 should_close_source
);
187 DCHECK(peer_pid
!= base::kNullProcessId
);
188 return BrokerGetFileHandleForProcess(handle
, peer_pid
, should_close_source
);
191 std::set
<PP_Instance
>* PpapiThread::GetGloballySeenInstanceIDSet() {
192 return &globally_seen_instance_ids_
;
195 IPC::Sender
* PpapiThread::GetBrowserSender() {
199 std::string
PpapiThread::GetUILanguage() {
200 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
201 return command_line
->GetSwitchValueASCII(switches::kLang
);
204 void PpapiThread::PreCacheFont(const void* logfontw
) {
206 ChildThreadImpl::PreCacheFont(*static_cast<const LOGFONTW
*>(logfontw
));
210 void PpapiThread::SetActiveURL(const std::string
& url
) {
211 GetContentClient()->SetActiveURL(GURL(url
));
214 PP_Resource
PpapiThread::CreateBrowserFont(
215 ppapi::proxy::Connection connection
,
216 PP_Instance instance
,
217 const PP_BrowserFont_Trusted_Description
& desc
,
218 const ppapi::Preferences
& prefs
) {
219 if (!BrowserFontResource_Trusted::IsPPFontDescriptionValid(desc
))
221 return (new BrowserFontResource_Trusted(
222 connection
, instance
, desc
, prefs
))->GetReference();
225 uint32
PpapiThread::Register(ppapi::proxy::PluginDispatcher
* plugin_dispatcher
) {
226 if (!plugin_dispatcher
||
227 plugin_dispatchers_
.size() >= std::numeric_limits
<uint32
>::max()) {
233 // Although it is unlikely, make sure that we won't cause any trouble when
234 // the counter overflows.
235 id
= next_plugin_dispatcher_id_
++;
237 plugin_dispatchers_
.find(id
) != plugin_dispatchers_
.end());
238 plugin_dispatchers_
[id
] = plugin_dispatcher
;
242 void PpapiThread::Unregister(uint32 plugin_dispatcher_id
) {
243 plugin_dispatchers_
.erase(plugin_dispatcher_id
);
246 void PpapiThread::OnLoadPlugin(const base::FilePath
& path
,
247 const ppapi::PpapiPermissions
& permissions
) {
248 // In case of crashes, the crash dump doesn't indicate which plugin
250 base::debug::SetCrashKeyValue("ppapi_path", path
.MaybeAsASCII());
252 SavePluginName(path
);
254 // This must be set before calling into the plugin so it can get the
255 // interfaces it has permission for.
256 ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(permissions
);
257 permissions_
= permissions
;
259 // Trusted Pepper plugins may be "internal", i.e. built-in to the browser
260 // binary. If we're being asked to load such a plugin (e.g. the Chromoting
261 // client) then fetch the entry points from the embedder, rather than a DLL.
262 std::vector
<PepperPluginInfo
> plugins
;
263 GetContentClient()->AddPepperPlugins(&plugins
);
264 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
265 if (plugins
[i
].is_internal
&& plugins
[i
].path
== path
) {
266 // An internal plugin is being loaded, so fetch the entry points.
267 plugin_entry_points_
= plugins
[i
].internal_entry_points
;
271 // If the plugin isn't internal then load it from |path|.
272 base::ScopedNativeLibrary library
;
273 if (plugin_entry_points_
.initialize_module
== NULL
) {
274 // Load the plugin from the specified library.
275 base::NativeLibraryLoadError error
;
276 library
.Reset(base::LoadNativeLibrary(path
, &error
));
277 if (!library
.is_valid()) {
278 LOG(ERROR
) << "Failed to load Pepper module from " << path
.value()
279 << " (error: " << error
.ToString() << ")";
280 if (!base::PathExists(path
)) {
281 ReportLoadResult(path
, FILE_MISSING
);
284 ReportLoadResult(path
, LOAD_FAILED
);
285 // Report detailed reason for load failure.
286 ReportLoadErrorCode(path
, error
);
290 // Get the GetInterface function (required).
291 plugin_entry_points_
.get_interface
=
292 reinterpret_cast<PP_GetInterface_Func
>(
293 library
.GetFunctionPointer("PPP_GetInterface"));
294 if (!plugin_entry_points_
.get_interface
) {
295 LOG(WARNING
) << "No PPP_GetInterface in plugin library";
296 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
300 // The ShutdownModule/ShutdownBroker function is optional.
301 plugin_entry_points_
.shutdown_module
=
303 reinterpret_cast<PP_ShutdownModule_Func
>(
304 library
.GetFunctionPointer("PPP_ShutdownBroker")) :
305 reinterpret_cast<PP_ShutdownModule_Func
>(
306 library
.GetFunctionPointer("PPP_ShutdownModule"));
309 // Get the InitializeModule function (required for non-broker code).
310 plugin_entry_points_
.initialize_module
=
311 reinterpret_cast<PP_InitializeModule_Func
>(
312 library
.GetFunctionPointer("PPP_InitializeModule"));
313 if (!plugin_entry_points_
.initialize_module
) {
314 LOG(WARNING
) << "No PPP_InitializeModule in plugin library";
315 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
322 // If code subsequently tries to exit using abort(), force a crash (since
323 // otherwise these would be silent terminations and fly under the radar).
324 base::win::SetAbortBehaviorForCrashReporting();
326 // Once we lower the token the sandbox is locked down and no new modules
327 // can be loaded. TODO(cpu): consider changing to the loading style of
329 if (g_target_services
) {
330 // Let Flash and Widevine CDM adapter load DXVA before lockdown on Vista+.
331 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
) ||
332 path
.BaseName().MaybeAsASCII() == kWidevineCdmAdapterFileName
) {
333 if (base::win::OSInfo::GetInstance()->version() >=
334 base::win::VERSION_VISTA
) {
335 LoadLibraryA("dxva2.dll");
339 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
)) {
340 if (base::win::OSInfo::GetInstance()->version() >=
341 base::win::VERSION_WIN7
) {
343 if (cpu
.vendor_name() == "AuthenticAMD") {
344 // The AMD crypto acceleration is only AMD Bulldozer and above.
346 LoadLibraryA("amdhcp64.dll");
348 LoadLibraryA("amdhcp32.dll");
354 // Cause advapi32 to load before the sandbox is turned on.
355 unsigned int dummy_rand
;
358 WarmupWindowsLocales(permissions
);
360 #if defined(ADDRESS_SANITIZER)
361 // Bind and leak dbghelp.dll before the token is lowered, otherwise
362 // AddressSanitizer will crash when trying to symbolize a report.
363 LoadLibraryA("dbghelp.dll");
366 g_target_services
->LowerToken();
371 // Get the InitializeBroker function (required).
372 InitializeBrokerFunc init_broker
=
373 reinterpret_cast<InitializeBrokerFunc
>(
374 library
.GetFunctionPointer("PPP_InitializeBroker"));
376 LOG(WARNING
) << "No PPP_InitializeBroker in plugin library";
377 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
381 int32_t init_error
= init_broker(&connect_instance_func_
);
382 if (init_error
!= PP_OK
) {
383 LOG(WARNING
) << "InitBroker failed with error " << init_error
;
384 ReportLoadResult(path
, INIT_FAILED
);
387 if (!connect_instance_func_
) {
388 LOG(WARNING
) << "InitBroker did not provide PP_ConnectInstance_Func";
389 ReportLoadResult(path
, INIT_FAILED
);
393 #if defined(OS_MACOSX)
394 // We need to do this after getting |PPP_GetInterface()| (or presumably
395 // doing something nontrivial with the library), else the sandbox
397 CHECK(InitializeSandbox());
400 int32_t init_error
= plugin_entry_points_
.initialize_module(
402 &ppapi::proxy::PluginDispatcher::GetBrowserInterface
);
403 if (init_error
!= PP_OK
) {
404 LOG(WARNING
) << "InitModule failed with error " << init_error
;
405 ReportLoadResult(path
, INIT_FAILED
);
410 // Initialization succeeded, so keep the plugin DLL loaded.
411 library_
.Reset(library
.Release());
413 ReportLoadResult(path
, LOAD_SUCCESS
);
416 void PpapiThread::OnCreateChannel(base::ProcessId renderer_pid
,
417 int renderer_child_id
,
419 IPC::ChannelHandle channel_handle
;
421 if (!plugin_entry_points_
.get_interface
|| // Plugin couldn't be loaded.
422 !SetupRendererChannel(renderer_pid
, renderer_child_id
, incognito
,
424 Send(new PpapiHostMsg_ChannelCreated(IPC::ChannelHandle()));
428 Send(new PpapiHostMsg_ChannelCreated(channel_handle
));
431 void PpapiThread::OnSetNetworkState(bool online
) {
432 // Note the browser-process side shouldn't send us these messages in the
433 // first unless the plugin has dev permissions, so we don't need to check
434 // again here. We don't want random plugins depending on this dev interface.
435 if (!plugin_entry_points_
.get_interface
)
437 const PPP_NetworkState_Dev
* ns
= static_cast<const PPP_NetworkState_Dev
*>(
438 plugin_entry_points_
.get_interface(PPP_NETWORK_STATE_DEV_INTERFACE
));
440 ns
->SetOnLine(PP_FromBool(online
));
443 void PpapiThread::OnCrash() {
444 // Intentionally crash upon the request of the browser.
445 volatile int* null_pointer
= NULL
;
449 void PpapiThread::OnHang() {
450 // Intentionally hang upon the request of the browser.
452 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
455 bool PpapiThread::SetupRendererChannel(base::ProcessId renderer_pid
,
456 int renderer_child_id
,
458 IPC::ChannelHandle
* handle
) {
459 DCHECK(is_broker_
== (connect_instance_func_
!= NULL
));
460 IPC::ChannelHandle plugin_handle
;
461 plugin_handle
.name
= IPC::Channel::GenerateVerifiedChannelID(
463 "%d.r%d", base::GetCurrentProcId(), renderer_child_id
));
465 ppapi::proxy::ProxyChannel
* dispatcher
= NULL
;
466 bool init_result
= false;
468 BrokerProcessDispatcher
* broker_dispatcher
=
469 new BrokerProcessDispatcher(plugin_entry_points_
.get_interface
,
470 connect_instance_func_
);
471 init_result
= broker_dispatcher
->InitBrokerWithChannel(this,
475 dispatcher
= broker_dispatcher
;
477 PluginProcessDispatcher
* plugin_dispatcher
=
478 new PluginProcessDispatcher(plugin_entry_points_
.get_interface
,
481 init_result
= plugin_dispatcher
->InitPluginWithChannel(this,
485 dispatcher
= plugin_dispatcher
;
493 handle
->name
= plugin_handle
.name
;
494 #if defined(OS_POSIX)
495 // On POSIX, transfer ownership of the renderer-side (client) FD.
496 // This ensures this process will be notified when it is closed even if a
497 // connection is not established.
498 handle
->socket
= base::FileDescriptor(dispatcher
->TakeRendererFD());
499 if (handle
->socket
.fd
== -1)
503 // From here, the dispatcher will manage its own lifetime according to the
504 // lifetime of the attached channel.
508 void PpapiThread::SavePluginName(const base::FilePath
& path
) {
509 ppapi::proxy::PluginGlobals::Get()->set_plugin_name(
510 path
.BaseName().AsUTF8Unsafe());
512 // plugin() is NULL when in-process, which is fine, because this is
513 // just a hook for setting the process name.
514 if (GetContentClient()->plugin()) {
515 GetContentClient()->plugin()->PluginProcessStarted(
516 path
.BaseName().RemoveExtension().LossyDisplayName());
520 void PpapiThread::ReportLoadResult(const base::FilePath
& path
,
522 DCHECK_LT(result
, LOAD_RESULT_MAX
);
523 std::string histogram_name
= std::string("Plugin.Ppapi") +
524 (is_broker_
? "Broker" : "Plugin") +
525 "LoadResult_" + path
.BaseName().MaybeAsASCII();
527 // Note: This leaks memory, which is expected behavior.
528 base::HistogramBase
* histogram
=
529 base::LinearHistogram::FactoryGet(
534 base::HistogramBase::kUmaTargetedHistogramFlag
);
536 histogram
->Add(result
);
539 void PpapiThread::ReportLoadErrorCode(
540 const base::FilePath
& path
,
541 const base::NativeLibraryLoadError
& error
) {
543 // Only report load error code on Windows because that's the only platform
544 // that has a numerical error value.
545 std::string histogram_name
=
546 std::string("Plugin.Ppapi") + (is_broker_
? "Broker" : "Plugin") +
547 "LoadErrorCode_" + path
.BaseName().MaybeAsASCII();
549 // For sparse histograms, we can use the macro, as it does not incorporate a
551 UMA_HISTOGRAM_SPARSE_SLOWLY(histogram_name
, error
.code
);
555 } // namespace content