IndexedDBFactory now ForceCloses databases.
[chromium-blink-merge.git] / content / ppapi_plugin / ppapi_thread.cc
blob5ed1873cce87364ef7a0aeb231b58a3bebd2cf44
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"
7 #include <limits>
9 #include "base/command_line.h"
10 #include "base/debug/crash_logging.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/rand_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/platform_thread.h"
17 #include "base/time/time.h"
18 #include "content/child/browser_font_resource_trusted.h"
19 #include "content/child/child_process.h"
20 #include "content/common/child_process_messages.h"
21 #include "content/common/sandbox_util.h"
22 #include "content/ppapi_plugin/broker_process_dispatcher.h"
23 #include "content/ppapi_plugin/plugin_process_dispatcher.h"
24 #include "content/ppapi_plugin/ppapi_webkitplatformsupport_impl.h"
25 #include "content/public/common/content_client.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/pepper_plugin_info.h"
28 #include "content/public/common/sandbox_init.h"
29 #include "content/public/plugin/content_plugin_client.h"
30 #include "ipc/ipc_channel_handle.h"
31 #include "ipc/ipc_platform_file.h"
32 #include "ipc/ipc_sync_channel.h"
33 #include "ipc/ipc_sync_message_filter.h"
34 #include "ppapi/c/dev/ppp_network_state_dev.h"
35 #include "ppapi/c/pp_errors.h"
36 #include "ppapi/c/ppp.h"
37 #include "ppapi/proxy/interface_list.h"
38 #include "ppapi/proxy/plugin_globals.h"
39 #include "ppapi/proxy/plugin_message_filter.h"
40 #include "ppapi/proxy/ppapi_messages.h"
41 #include "ppapi/proxy/resource_reply_thread_registrar.h"
42 #include "third_party/WebKit/public/web/WebKit.h"
43 #include "ui/base/ui_base_switches.h"
45 #if defined(OS_WIN)
46 #include "base/win/win_util.h"
47 #include "base/win/windows_version.h"
48 #include "sandbox/win/src/sandbox.h"
49 #elif defined(OS_MACOSX)
50 #include "content/common/sandbox_init_mac.h"
51 #endif
53 #if defined(OS_WIN)
54 extern sandbox::TargetServices* g_target_services;
55 #else
56 extern void* g_target_services;
57 #endif
59 namespace content {
61 typedef int32_t (*InitializeBrokerFunc)
62 (PP_ConnectInstance_Func* connect_instance_func);
64 PpapiThread::PpapiThread(const CommandLine& command_line, bool is_broker)
65 : is_broker_(is_broker),
66 connect_instance_func_(NULL),
67 local_pp_module_(
68 base::RandInt(0, std::numeric_limits<PP_Module>::max())),
69 next_plugin_dispatcher_id_(1) {
70 ppapi::proxy::PluginGlobals* globals = ppapi::proxy::PluginGlobals::Get();
71 globals->set_plugin_proxy_delegate(this);
72 globals->set_command_line(
73 command_line.GetSwitchValueASCII(switches::kPpapiFlashArgs));
75 webkit_platform_support_.reset(new PpapiWebKitPlatformSupportImpl);
76 blink::initialize(webkit_platform_support_.get());
78 if (!is_broker_) {
79 channel()->AddFilter(
80 new ppapi::proxy::PluginMessageFilter(
81 NULL, globals->resource_reply_thread_registrar()));
85 PpapiThread::~PpapiThread() {
88 void PpapiThread::Shutdown() {
89 ppapi::proxy::PluginGlobals::Get()->set_plugin_proxy_delegate(NULL);
90 if (plugin_entry_points_.shutdown_module)
91 plugin_entry_points_.shutdown_module();
92 webkit_platform_support_->Shutdown();
93 blink::shutdown();
96 bool PpapiThread::Send(IPC::Message* msg) {
97 // Allow access from multiple threads.
98 if (base::MessageLoop::current() == message_loop())
99 return ChildThread::Send(msg);
101 return sync_message_filter()->Send(msg);
104 // Note that this function is called only for messages from the channel to the
105 // browser process. Messages from the renderer process are sent via a different
106 // channel that ends up at Dispatcher::OnMessageReceived.
107 bool PpapiThread::OnControlMessageReceived(const IPC::Message& msg) {
108 bool handled = true;
109 IPC_BEGIN_MESSAGE_MAP(PpapiThread, msg)
110 IPC_MESSAGE_HANDLER(PpapiMsg_LoadPlugin, OnLoadPlugin)
111 IPC_MESSAGE_HANDLER(PpapiMsg_CreateChannel, OnCreateChannel)
112 IPC_MESSAGE_HANDLER(PpapiMsg_SetNetworkState, OnSetNetworkState)
113 IPC_MESSAGE_HANDLER(PpapiMsg_Crash, OnCrash)
114 IPC_MESSAGE_HANDLER(PpapiMsg_Hang, OnHang)
115 IPC_MESSAGE_UNHANDLED(handled = false)
116 IPC_END_MESSAGE_MAP()
117 return handled;
120 void PpapiThread::OnChannelConnected(int32 peer_pid) {
121 ChildThread::OnChannelConnected(peer_pid);
122 #if defined(OS_WIN)
123 if (is_broker_)
124 peer_handle_.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, peer_pid));
125 #endif
128 base::MessageLoopProxy* PpapiThread::GetIPCMessageLoop() {
129 return ChildProcess::current()->io_message_loop_proxy();
132 base::WaitableEvent* PpapiThread::GetShutdownEvent() {
133 return ChildProcess::current()->GetShutDownEvent();
136 IPC::PlatformFileForTransit PpapiThread::ShareHandleWithRemote(
137 base::PlatformFile handle,
138 base::ProcessId peer_pid,
139 bool should_close_source) {
140 #if defined(OS_WIN)
141 if (peer_handle_.IsValid()) {
142 DCHECK(is_broker_);
143 return IPC::GetFileHandleForProcess(handle, peer_handle_,
144 should_close_source);
146 #endif
148 DCHECK(peer_pid != base::kNullProcessId);
149 return BrokerGetFileHandleForProcess(handle, peer_pid, should_close_source);
152 std::set<PP_Instance>* PpapiThread::GetGloballySeenInstanceIDSet() {
153 return &globally_seen_instance_ids_;
156 IPC::Sender* PpapiThread::GetBrowserSender() {
157 return this;
160 std::string PpapiThread::GetUILanguage() {
161 CommandLine* command_line = CommandLine::ForCurrentProcess();
162 return command_line->GetSwitchValueASCII(switches::kLang);
165 void PpapiThread::PreCacheFont(const void* logfontw) {
166 #if defined(OS_WIN)
167 Send(new ChildProcessHostMsg_PreCacheFont(
168 *static_cast<const LOGFONTW*>(logfontw)));
169 #endif
172 void PpapiThread::SetActiveURL(const std::string& url) {
173 GetContentClient()->SetActiveURL(GURL(url));
176 PP_Resource PpapiThread::CreateBrowserFont(
177 ppapi::proxy::Connection connection,
178 PP_Instance instance,
179 const PP_BrowserFont_Trusted_Description& desc,
180 const ppapi::Preferences& prefs) {
181 if (!BrowserFontResource_Trusted::IsPPFontDescriptionValid(desc))
182 return 0;
183 return (new BrowserFontResource_Trusted(
184 connection, instance, desc, prefs))->GetReference();
187 uint32 PpapiThread::Register(ppapi::proxy::PluginDispatcher* plugin_dispatcher) {
188 if (!plugin_dispatcher ||
189 plugin_dispatchers_.size() >= std::numeric_limits<uint32>::max()) {
190 return 0;
193 uint32 id = 0;
194 do {
195 // Although it is unlikely, make sure that we won't cause any trouble when
196 // the counter overflows.
197 id = next_plugin_dispatcher_id_++;
198 } while (id == 0 ||
199 plugin_dispatchers_.find(id) != plugin_dispatchers_.end());
200 plugin_dispatchers_[id] = plugin_dispatcher;
201 return id;
204 void PpapiThread::Unregister(uint32 plugin_dispatcher_id) {
205 plugin_dispatchers_.erase(plugin_dispatcher_id);
208 void PpapiThread::OnLoadPlugin(const base::FilePath& path,
209 const ppapi::PpapiPermissions& permissions) {
210 // In case of crashes, the crash dump doesn't indicate which plugin
211 // it came from.
212 base::debug::SetCrashKeyValue("ppapi_path", path.MaybeAsASCII());
214 SavePluginName(path);
216 // This must be set before calling into the plugin so it can get the
217 // interfaces it has permission for.
218 ppapi::proxy::InterfaceList::SetProcessGlobalPermissions(permissions);
219 permissions_ = permissions;
221 // Trusted Pepper plugins may be "internal", i.e. built-in to the browser
222 // binary. If we're being asked to load such a plugin (e.g. the Chromoting
223 // client) then fetch the entry points from the embedder, rather than a DLL.
224 std::vector<PepperPluginInfo> plugins;
225 GetContentClient()->AddPepperPlugins(&plugins);
226 for (size_t i = 0; i < plugins.size(); ++i) {
227 if (plugins[i].is_internal && plugins[i].path == path) {
228 // An internal plugin is being loaded, so fetch the entry points.
229 plugin_entry_points_ = plugins[i].internal_entry_points;
233 // If the plugin isn't internal then load it from |path|.
234 base::ScopedNativeLibrary library;
235 if (plugin_entry_points_.initialize_module == NULL) {
236 // Load the plugin from the specified library.
237 std::string error;
238 library.Reset(base::LoadNativeLibrary(path, &error));
239 if (!library.is_valid()) {
240 LOG(ERROR) << "Failed to load Pepper module from "
241 << path.value() << " (error: " << error << ")";
242 ReportLoadResult(path, LOAD_FAILED);
243 return;
246 // Get the GetInterface function (required).
247 plugin_entry_points_.get_interface =
248 reinterpret_cast<PP_GetInterface_Func>(
249 library.GetFunctionPointer("PPP_GetInterface"));
250 if (!plugin_entry_points_.get_interface) {
251 LOG(WARNING) << "No PPP_GetInterface in plugin library";
252 ReportLoadResult(path, ENTRY_POINT_MISSING);
253 return;
256 // The ShutdownModule/ShutdownBroker function is optional.
257 plugin_entry_points_.shutdown_module =
258 is_broker_ ?
259 reinterpret_cast<PP_ShutdownModule_Func>(
260 library.GetFunctionPointer("PPP_ShutdownBroker")) :
261 reinterpret_cast<PP_ShutdownModule_Func>(
262 library.GetFunctionPointer("PPP_ShutdownModule"));
264 if (!is_broker_) {
265 // Get the InitializeModule function (required for non-broker code).
266 plugin_entry_points_.initialize_module =
267 reinterpret_cast<PP_InitializeModule_Func>(
268 library.GetFunctionPointer("PPP_InitializeModule"));
269 if (!plugin_entry_points_.initialize_module) {
270 LOG(WARNING) << "No PPP_InitializeModule in plugin library";
271 ReportLoadResult(path, ENTRY_POINT_MISSING);
272 return;
277 #if defined(OS_WIN)
278 // If code subsequently tries to exit using abort(), force a crash (since
279 // otherwise these would be silent terminations and fly under the radar).
280 base::win::SetAbortBehaviorForCrashReporting();
282 // Once we lower the token the sandbox is locked down and no new modules
283 // can be loaded. TODO(cpu): consider changing to the loading style of
284 // regular plugins.
285 if (g_target_services) {
286 // Let Flash load DRM before lockdown on Vista+.
287 if (permissions.HasPermission(ppapi::PERMISSION_FLASH) &&
288 base::win::OSInfo::GetInstance()->version() >=
289 base::win::VERSION_VISTA ) {
290 LoadLibrary(L"dxva2.dll");
293 // Cause advapi32 to load before the sandbox is turned on.
294 unsigned int dummy_rand;
295 rand_s(&dummy_rand);
296 // Warm up language subsystems before the sandbox is turned on.
297 ::GetUserDefaultLangID();
298 ::GetUserDefaultLCID();
300 g_target_services->LowerToken();
302 #endif
304 if (is_broker_) {
305 // Get the InitializeBroker function (required).
306 InitializeBrokerFunc init_broker =
307 reinterpret_cast<InitializeBrokerFunc>(
308 library.GetFunctionPointer("PPP_InitializeBroker"));
309 if (!init_broker) {
310 LOG(WARNING) << "No PPP_InitializeBroker in plugin library";
311 ReportLoadResult(path, ENTRY_POINT_MISSING);
312 return;
315 int32_t init_error = init_broker(&connect_instance_func_);
316 if (init_error != PP_OK) {
317 LOG(WARNING) << "InitBroker failed with error " << init_error;
318 ReportLoadResult(path, INIT_FAILED);
319 return;
321 if (!connect_instance_func_) {
322 LOG(WARNING) << "InitBroker did not provide PP_ConnectInstance_Func";
323 ReportLoadResult(path, INIT_FAILED);
324 return;
326 } else {
327 #if defined(OS_MACOSX)
328 // We need to do this after getting |PPP_GetInterface()| (or presumably
329 // doing something nontrivial with the library), else the sandbox
330 // intercedes.
331 CHECK(InitializeSandbox());
332 #endif
334 int32_t init_error = plugin_entry_points_.initialize_module(
335 local_pp_module_,
336 &ppapi::proxy::PluginDispatcher::GetBrowserInterface);
337 if (init_error != PP_OK) {
338 LOG(WARNING) << "InitModule failed with error " << init_error;
339 ReportLoadResult(path, INIT_FAILED);
340 return;
344 // Initialization succeeded, so keep the plugin DLL loaded.
345 library_.Reset(library.Release());
347 ReportLoadResult(path, LOAD_SUCCESS);
350 void PpapiThread::OnCreateChannel(base::ProcessId renderer_pid,
351 int renderer_child_id,
352 bool incognito) {
353 IPC::ChannelHandle channel_handle;
355 if (!plugin_entry_points_.get_interface || // Plugin couldn't be loaded.
356 !SetupRendererChannel(renderer_pid, renderer_child_id, incognito,
357 &channel_handle)) {
358 Send(new PpapiHostMsg_ChannelCreated(IPC::ChannelHandle()));
359 return;
362 Send(new PpapiHostMsg_ChannelCreated(channel_handle));
365 void PpapiThread::OnSetNetworkState(bool online) {
366 // Note the browser-process side shouldn't send us these messages in the
367 // first unless the plugin has dev permissions, so we don't need to check
368 // again here. We don't want random plugins depending on this dev interface.
369 if (!plugin_entry_points_.get_interface)
370 return;
371 const PPP_NetworkState_Dev* ns = static_cast<const PPP_NetworkState_Dev*>(
372 plugin_entry_points_.get_interface(PPP_NETWORK_STATE_DEV_INTERFACE));
373 if (ns)
374 ns->SetOnLine(PP_FromBool(online));
377 void PpapiThread::OnCrash() {
378 // Intentionally crash upon the request of the browser.
379 volatile int* null_pointer = NULL;
380 *null_pointer = 0;
383 void PpapiThread::OnHang() {
384 // Intentionally hang upon the request of the browser.
385 for (;;)
386 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
389 bool PpapiThread::SetupRendererChannel(base::ProcessId renderer_pid,
390 int renderer_child_id,
391 bool incognito,
392 IPC::ChannelHandle* handle) {
393 DCHECK(is_broker_ == (connect_instance_func_ != NULL));
394 IPC::ChannelHandle plugin_handle;
395 plugin_handle.name = IPC::Channel::GenerateVerifiedChannelID(
396 base::StringPrintf(
397 "%d.r%d", base::GetCurrentProcId(), renderer_child_id));
399 ppapi::proxy::ProxyChannel* dispatcher = NULL;
400 bool init_result = false;
401 if (is_broker_) {
402 BrokerProcessDispatcher* broker_dispatcher =
403 new BrokerProcessDispatcher(plugin_entry_points_.get_interface,
404 connect_instance_func_);
405 init_result = broker_dispatcher->InitBrokerWithChannel(this,
406 renderer_pid,
407 plugin_handle,
408 false);
409 dispatcher = broker_dispatcher;
410 } else {
411 PluginProcessDispatcher* plugin_dispatcher =
412 new PluginProcessDispatcher(plugin_entry_points_.get_interface,
413 permissions_,
414 incognito);
415 init_result = plugin_dispatcher->InitPluginWithChannel(this,
416 renderer_pid,
417 plugin_handle,
418 false);
419 dispatcher = plugin_dispatcher;
422 if (!init_result) {
423 delete dispatcher;
424 return false;
427 handle->name = plugin_handle.name;
428 #if defined(OS_POSIX)
429 // On POSIX, transfer ownership of the renderer-side (client) FD.
430 // This ensures this process will be notified when it is closed even if a
431 // connection is not established.
432 handle->socket = base::FileDescriptor(dispatcher->TakeRendererFD(), true);
433 if (handle->socket.fd == -1)
434 return false;
435 #endif
437 // From here, the dispatcher will manage its own lifetime according to the
438 // lifetime of the attached channel.
439 return true;
442 void PpapiThread::SavePluginName(const base::FilePath& path) {
443 ppapi::proxy::PluginGlobals::Get()->set_plugin_name(
444 path.BaseName().AsUTF8Unsafe());
446 // plugin() is NULL when in-process, which is fine, because this is
447 // just a hook for setting the process name.
448 if (GetContentClient()->plugin()) {
449 GetContentClient()->plugin()->PluginProcessStarted(
450 path.BaseName().RemoveExtension().LossyDisplayName());
454 void PpapiThread::ReportLoadResult(const base::FilePath& path,
455 LoadResult result) {
456 DCHECK_LT(result, LOAD_RESULT_MAX);
458 std::ostringstream histogram_name;
459 histogram_name << "Plugin.Ppapi" << (is_broker_ ? "Broker" : "Plugin")
460 << "LoadResult_" << path.BaseName().MaybeAsASCII();
462 // Note: This leaks memory, which is expected behavior.
463 base::HistogramBase* histogram =
464 base::LinearHistogram::FactoryGet(
465 histogram_name.str(),
467 LOAD_RESULT_MAX,
468 LOAD_RESULT_MAX + 1,
469 base::HistogramBase::kUmaTargetedHistogramFlag);
471 histogram->Add(result);
474 } // namespace content