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/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_webkitplatformsupport_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 extern sandbox::TargetServices
* g_target_services
;
59 // Used by EnumSystemLocales for warming up.
60 static BOOL CALLBACK
EnumLocalesProc(LPTSTR lpLocaleString
) {
64 static BOOL CALLBACK
EnumLocalesProcEx(
65 LPWSTR lpLocaleString
,
71 // Warm up language subsystems before the sandbox is turned on.
72 static void WarmupWindowsLocales(const ppapi::PpapiPermissions
& permissions
) {
73 ::GetUserDefaultLangID();
74 ::GetUserDefaultLCID();
76 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
)) {
77 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
78 typedef BOOL (WINAPI
*PfnEnumSystemLocalesEx
)
79 (LOCALE_ENUMPROCEX
, DWORD
, LPARAM
, LPVOID
);
81 HMODULE handle_kern32
= GetModuleHandleW(L
"Kernel32.dll");
82 PfnEnumSystemLocalesEx enum_sys_locales_ex
=
83 reinterpret_cast<PfnEnumSystemLocalesEx
>
84 (GetProcAddress(handle_kern32
, "EnumSystemLocalesEx"));
86 enum_sys_locales_ex(EnumLocalesProcEx
, LOCALE_WINDOWS
, 0, 0);
88 EnumSystemLocalesW(EnumLocalesProc
, LCID_INSTALLED
);
93 extern void* g_target_services
;
98 typedef int32_t (*InitializeBrokerFunc
)
99 (PP_ConnectInstance_Func
* connect_instance_func
);
101 PpapiThread::PpapiThread(const CommandLine
& command_line
, bool is_broker
)
102 : is_broker_(is_broker
),
103 connect_instance_func_(NULL
),
105 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
->set_plugin_proxy_delegate(this);
109 globals
->set_command_line(
110 command_line
.GetSwitchValueASCII(switches::kPpapiFlashArgs
));
112 webkit_platform_support_
.reset(new PpapiWebKitPlatformSupportImpl
);
113 blink::initialize(webkit_platform_support_
.get());
116 channel()->AddFilter(
117 new ppapi::proxy::PluginMessageFilter(
118 NULL
, globals
->resource_reply_thread_registrar()));
122 PpapiThread::~PpapiThread() {
125 void PpapiThread::Shutdown() {
126 ppapi::proxy::PluginGlobals::Get()->set_plugin_proxy_delegate(NULL
);
127 if (plugin_entry_points_
.shutdown_module
)
128 plugin_entry_points_
.shutdown_module();
129 webkit_platform_support_
->Shutdown();
133 bool PpapiThread::Send(IPC::Message
* msg
) {
134 // Allow access from multiple threads.
135 if (base::MessageLoop::current() == message_loop())
136 return ChildThread::Send(msg
);
138 return sync_message_filter()->Send(msg
);
141 // Note that this function is called only for messages from the channel to the
142 // browser process. Messages from the renderer process are sent via a different
143 // channel that ends up at Dispatcher::OnMessageReceived.
144 bool PpapiThread::OnControlMessageReceived(const IPC::Message
& msg
) {
146 IPC_BEGIN_MESSAGE_MAP(PpapiThread
, msg
)
147 IPC_MESSAGE_HANDLER(PpapiMsg_LoadPlugin
, OnLoadPlugin
)
148 IPC_MESSAGE_HANDLER(PpapiMsg_CreateChannel
, OnCreateChannel
)
149 IPC_MESSAGE_HANDLER(PpapiMsg_SetNetworkState
, OnSetNetworkState
)
150 IPC_MESSAGE_HANDLER(PpapiMsg_Crash
, OnCrash
)
151 IPC_MESSAGE_HANDLER(PpapiMsg_Hang
, OnHang
)
152 IPC_MESSAGE_UNHANDLED(handled
= false)
153 IPC_END_MESSAGE_MAP()
157 void PpapiThread::OnChannelConnected(int32 peer_pid
) {
158 ChildThread::OnChannelConnected(peer_pid
);
161 peer_handle_
.Set(::OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, peer_pid
));
165 base::MessageLoopProxy
* PpapiThread::GetIPCMessageLoop() {
166 return ChildProcess::current()->io_message_loop_proxy();
169 base::WaitableEvent
* PpapiThread::GetShutdownEvent() {
170 return ChildProcess::current()->GetShutDownEvent();
173 IPC::PlatformFileForTransit
PpapiThread::ShareHandleWithRemote(
174 base::PlatformFile handle
,
175 base::ProcessId peer_pid
,
176 bool should_close_source
) {
178 if (peer_handle_
.IsValid()) {
180 return IPC::GetFileHandleForProcess(handle
, peer_handle_
,
181 should_close_source
);
185 DCHECK(peer_pid
!= base::kNullProcessId
);
186 return BrokerGetFileHandleForProcess(handle
, peer_pid
, should_close_source
);
189 std::set
<PP_Instance
>* PpapiThread::GetGloballySeenInstanceIDSet() {
190 return &globally_seen_instance_ids_
;
193 IPC::Sender
* PpapiThread::GetBrowserSender() {
197 std::string
PpapiThread::GetUILanguage() {
198 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
199 return command_line
->GetSwitchValueASCII(switches::kLang
);
202 void PpapiThread::PreCacheFont(const void* logfontw
) {
204 Send(new ChildProcessHostMsg_PreCacheFont(
205 *static_cast<const LOGFONTW
*>(logfontw
)));
209 void PpapiThread::SetActiveURL(const std::string
& url
) {
210 GetContentClient()->SetActiveURL(GURL(url
));
213 PP_Resource
PpapiThread::CreateBrowserFont(
214 ppapi::proxy::Connection connection
,
215 PP_Instance instance
,
216 const PP_BrowserFont_Trusted_Description
& desc
,
217 const ppapi::Preferences
& prefs
) {
218 if (!BrowserFontResource_Trusted::IsPPFontDescriptionValid(desc
))
220 return (new BrowserFontResource_Trusted(
221 connection
, instance
, desc
, prefs
))->GetReference();
224 uint32
PpapiThread::Register(ppapi::proxy::PluginDispatcher
* plugin_dispatcher
) {
225 if (!plugin_dispatcher
||
226 plugin_dispatchers_
.size() >= std::numeric_limits
<uint32
>::max()) {
232 // Although it is unlikely, make sure that we won't cause any trouble when
233 // the counter overflows.
234 id
= next_plugin_dispatcher_id_
++;
236 plugin_dispatchers_
.find(id
) != plugin_dispatchers_
.end());
237 plugin_dispatchers_
[id
] = plugin_dispatcher
;
241 void PpapiThread::Unregister(uint32 plugin_dispatcher_id
) {
242 plugin_dispatchers_
.erase(plugin_dispatcher_id
);
245 void PpapiThread::OnLoadPlugin(const base::FilePath
& path
,
246 const ppapi::PpapiPermissions
& permissions
) {
247 // In case of crashes, the crash dump doesn't indicate which plugin
249 base::debug::SetCrashKeyValue("ppapi_path", path
.MaybeAsASCII());
251 SavePluginName(path
);
253 // This must be set before calling into the plugin so it can get the
254 // interfaces it has permission for.
255 ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(permissions
);
256 permissions_
= permissions
;
258 // Trusted Pepper plugins may be "internal", i.e. built-in to the browser
259 // binary. If we're being asked to load such a plugin (e.g. the Chromoting
260 // client) then fetch the entry points from the embedder, rather than a DLL.
261 std::vector
<PepperPluginInfo
> plugins
;
262 GetContentClient()->AddPepperPlugins(&plugins
);
263 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
264 if (plugins
[i
].is_internal
&& plugins
[i
].path
== path
) {
265 // An internal plugin is being loaded, so fetch the entry points.
266 plugin_entry_points_
= plugins
[i
].internal_entry_points
;
270 // If the plugin isn't internal then load it from |path|.
271 base::ScopedNativeLibrary library
;
272 if (plugin_entry_points_
.initialize_module
== NULL
) {
273 // Load the plugin from the specified library.
274 base::NativeLibraryLoadError error
;
275 library
.Reset(base::LoadNativeLibrary(path
, &error
));
276 if (!library
.is_valid()) {
277 LOG(ERROR
) << "Failed to load Pepper module from " << path
.value()
278 << " (error: " << error
.ToString() << ")";
279 if (!base::PathExists(path
)) {
280 ReportLoadResult(path
, FILE_MISSING
);
283 ReportLoadResult(path
, LOAD_FAILED
);
284 // Report detailed reason for load failure.
285 ReportLoadErrorCode(path
, error
);
289 // Get the GetInterface function (required).
290 plugin_entry_points_
.get_interface
=
291 reinterpret_cast<PP_GetInterface_Func
>(
292 library
.GetFunctionPointer("PPP_GetInterface"));
293 if (!plugin_entry_points_
.get_interface
) {
294 LOG(WARNING
) << "No PPP_GetInterface in plugin library";
295 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
299 // The ShutdownModule/ShutdownBroker function is optional.
300 plugin_entry_points_
.shutdown_module
=
302 reinterpret_cast<PP_ShutdownModule_Func
>(
303 library
.GetFunctionPointer("PPP_ShutdownBroker")) :
304 reinterpret_cast<PP_ShutdownModule_Func
>(
305 library
.GetFunctionPointer("PPP_ShutdownModule"));
308 // Get the InitializeModule function (required for non-broker code).
309 plugin_entry_points_
.initialize_module
=
310 reinterpret_cast<PP_InitializeModule_Func
>(
311 library
.GetFunctionPointer("PPP_InitializeModule"));
312 if (!plugin_entry_points_
.initialize_module
) {
313 LOG(WARNING
) << "No PPP_InitializeModule in plugin library";
314 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
321 // If code subsequently tries to exit using abort(), force a crash (since
322 // otherwise these would be silent terminations and fly under the radar).
323 base::win::SetAbortBehaviorForCrashReporting();
325 // Once we lower the token the sandbox is locked down and no new modules
326 // can be loaded. TODO(cpu): consider changing to the loading style of
328 if (g_target_services
) {
329 // Let Flash load DXVA before lockdown on Vista+.
330 if (permissions
.HasPermission(ppapi::PERMISSION_FLASH
)) {
331 if (base::win::OSInfo::GetInstance()->version() >=
332 base::win::VERSION_VISTA
) {
333 LoadLibraryA("dxva2.dll");
336 if (base::win::OSInfo::GetInstance()->version() >=
337 base::win::VERSION_WIN7
) {
339 if (cpu
.vendor_name() == "AuthenticAMD") {
340 // The AMD crypto acceleration is only AMD Bulldozer and above.
342 LoadLibraryA("amdhcp64.dll");
344 LoadLibraryA("amdhcp32.dll");
350 // Cause advapi32 to load before the sandbox is turned on.
351 unsigned int dummy_rand
;
354 WarmupWindowsLocales(permissions
);
356 g_target_services
->LowerToken();
361 // Get the InitializeBroker function (required).
362 InitializeBrokerFunc init_broker
=
363 reinterpret_cast<InitializeBrokerFunc
>(
364 library
.GetFunctionPointer("PPP_InitializeBroker"));
366 LOG(WARNING
) << "No PPP_InitializeBroker in plugin library";
367 ReportLoadResult(path
, ENTRY_POINT_MISSING
);
371 int32_t init_error
= init_broker(&connect_instance_func_
);
372 if (init_error
!= PP_OK
) {
373 LOG(WARNING
) << "InitBroker failed with error " << init_error
;
374 ReportLoadResult(path
, INIT_FAILED
);
377 if (!connect_instance_func_
) {
378 LOG(WARNING
) << "InitBroker did not provide PP_ConnectInstance_Func";
379 ReportLoadResult(path
, INIT_FAILED
);
383 #if defined(OS_MACOSX)
384 // We need to do this after getting |PPP_GetInterface()| (or presumably
385 // doing something nontrivial with the library), else the sandbox
387 CHECK(InitializeSandbox());
390 int32_t init_error
= plugin_entry_points_
.initialize_module(
392 &ppapi::proxy::PluginDispatcher::GetBrowserInterface
);
393 if (init_error
!= PP_OK
) {
394 LOG(WARNING
) << "InitModule failed with error " << init_error
;
395 ReportLoadResult(path
, INIT_FAILED
);
400 // Initialization succeeded, so keep the plugin DLL loaded.
401 library_
.Reset(library
.Release());
403 ReportLoadResult(path
, LOAD_SUCCESS
);
406 void PpapiThread::OnCreateChannel(base::ProcessId renderer_pid
,
407 int renderer_child_id
,
409 IPC::ChannelHandle channel_handle
;
411 if (!plugin_entry_points_
.get_interface
|| // Plugin couldn't be loaded.
412 !SetupRendererChannel(renderer_pid
, renderer_child_id
, incognito
,
414 Send(new PpapiHostMsg_ChannelCreated(IPC::ChannelHandle()));
418 Send(new PpapiHostMsg_ChannelCreated(channel_handle
));
421 void PpapiThread::OnSetNetworkState(bool online
) {
422 // Note the browser-process side shouldn't send us these messages in the
423 // first unless the plugin has dev permissions, so we don't need to check
424 // again here. We don't want random plugins depending on this dev interface.
425 if (!plugin_entry_points_
.get_interface
)
427 const PPP_NetworkState_Dev
* ns
= static_cast<const PPP_NetworkState_Dev
*>(
428 plugin_entry_points_
.get_interface(PPP_NETWORK_STATE_DEV_INTERFACE
));
430 ns
->SetOnLine(PP_FromBool(online
));
433 void PpapiThread::OnCrash() {
434 // Intentionally crash upon the request of the browser.
435 volatile int* null_pointer
= NULL
;
439 void PpapiThread::OnHang() {
440 // Intentionally hang upon the request of the browser.
442 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
445 bool PpapiThread::SetupRendererChannel(base::ProcessId renderer_pid
,
446 int renderer_child_id
,
448 IPC::ChannelHandle
* handle
) {
449 DCHECK(is_broker_
== (connect_instance_func_
!= NULL
));
450 IPC::ChannelHandle plugin_handle
;
451 plugin_handle
.name
= IPC::Channel::GenerateVerifiedChannelID(
453 "%d.r%d", base::GetCurrentProcId(), renderer_child_id
));
455 ppapi::proxy::ProxyChannel
* dispatcher
= NULL
;
456 bool init_result
= false;
458 BrokerProcessDispatcher
* broker_dispatcher
=
459 new BrokerProcessDispatcher(plugin_entry_points_
.get_interface
,
460 connect_instance_func_
);
461 init_result
= broker_dispatcher
->InitBrokerWithChannel(this,
465 dispatcher
= broker_dispatcher
;
467 PluginProcessDispatcher
* plugin_dispatcher
=
468 new PluginProcessDispatcher(plugin_entry_points_
.get_interface
,
471 init_result
= plugin_dispatcher
->InitPluginWithChannel(this,
475 dispatcher
= plugin_dispatcher
;
483 handle
->name
= plugin_handle
.name
;
484 #if defined(OS_POSIX)
485 // On POSIX, transfer ownership of the renderer-side (client) FD.
486 // This ensures this process will be notified when it is closed even if a
487 // connection is not established.
488 handle
->socket
= base::FileDescriptor(dispatcher
->TakeRendererFD(), true);
489 if (handle
->socket
.fd
== -1)
493 // From here, the dispatcher will manage its own lifetime according to the
494 // lifetime of the attached channel.
498 void PpapiThread::SavePluginName(const base::FilePath
& path
) {
499 ppapi::proxy::PluginGlobals::Get()->set_plugin_name(
500 path
.BaseName().AsUTF8Unsafe());
502 // plugin() is NULL when in-process, which is fine, because this is
503 // just a hook for setting the process name.
504 if (GetContentClient()->plugin()) {
505 GetContentClient()->plugin()->PluginProcessStarted(
506 path
.BaseName().RemoveExtension().LossyDisplayName());
510 void PpapiThread::ReportLoadResult(const base::FilePath
& path
,
512 DCHECK_LT(result
, LOAD_RESULT_MAX
);
513 std::string histogram_name
= std::string("Plugin.Ppapi") +
514 (is_broker_
? "Broker" : "Plugin") +
515 "LoadResult_" + path
.BaseName().MaybeAsASCII();
517 // Note: This leaks memory, which is expected behavior.
518 base::HistogramBase
* histogram
=
519 base::LinearHistogram::FactoryGet(
524 base::HistogramBase::kUmaTargetedHistogramFlag
);
526 histogram
->Add(result
);
529 void PpapiThread::ReportLoadErrorCode(
530 const base::FilePath
& path
,
531 const base::NativeLibraryLoadError
& error
) {
533 // Only report load error code on Windows because that's the only platform
534 // that has a numerical error value.
535 std::string histogram_name
=
536 std::string("Plugin.Ppapi") + (is_broker_
? "Broker" : "Plugin") +
537 "LoadErrorCode_" + path
.BaseName().MaybeAsASCII();
539 // For sparse histograms, we can use the macro, as it does not incorporate a
541 UMA_HISTOGRAM_SPARSE_SLOWLY(histogram_name
, error
.code
);
545 } // namespace content