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/browser/plugin_process_host.h"
9 #elif defined(OS_POSIX)
10 #include <utility> // for pair<>
15 #include "base/base_switches.h"
16 #include "base/bind.h"
17 #include "base/command_line.h"
18 #include "base/files/file_path.h"
19 #include "base/lazy_instance.h"
20 #include "base/logging.h"
21 #include "base/metrics/histogram.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/synchronization/lock.h"
26 #include "content/browser/browser_child_process_host_impl.h"
27 #include "content/browser/loader/resource_message_filter.h"
28 #include "content/browser/gpu/gpu_data_manager_impl.h"
29 #include "content/browser/plugin_service_impl.h"
30 #include "content/common/child_process_host_impl.h"
31 #include "content/common/plugin_process_messages.h"
32 #include "content/common/resource_messages.h"
33 #include "content/public/browser/browser_thread.h"
34 #include "content/public/browser/content_browser_client.h"
35 #include "content/public/browser/notification_types.h"
36 #include "content/public/browser/plugin_service.h"
37 #include "content/public/browser/resource_context.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/process_type.h"
40 #include "content/public/common/sandboxed_process_launcher_delegate.h"
41 #include "ipc/ipc_switches.h"
42 #include "net/url_request/url_request_context_getter.h"
43 #include "ui/base/ui_base_switches.h"
44 #include "ui/gfx/native_widget_types.h"
45 #include "ui/gfx/switches.h"
46 #include "ui/gl/gl_switches.h"
48 #if defined(OS_MACOSX)
49 #include "base/mac/mac_util.h"
50 #include "ui/gfx/rect.h"
54 #include "base/win/windows_version.h"
55 #include "content/common/plugin_constants_win.h"
62 base::LazyInstance<std::map<base::ProcessId, WebPluginInfo> >
63 g_process_webplugin_info = LAZY_INSTANCE_INITIALIZER;
64 base::LazyInstance<base::Lock>::Leaky
65 g_process_webplugin_info_lock = LAZY_INSTANCE_INITIALIZER;
68 bool PluginProcessHost::GetWebPluginInfoFromPluginPid(base::ProcessId pid,
69 WebPluginInfo* info) {
70 base::AutoLock lock(g_process_webplugin_info_lock.Get());
71 if (!g_process_webplugin_info.Get().count(pid))
74 *info = g_process_webplugin_info.Get()[pid];
79 void PluginProcessHost::OnPluginWindowDestroyed(HWND window, HWND parent) {
80 // The window is destroyed at this point, we just care about its parent, which
81 // is the intermediate window we created.
82 std::set<HWND>::iterator window_index =
83 plugin_parent_windows_set_.find(parent);
84 if (window_index == plugin_parent_windows_set_.end())
87 plugin_parent_windows_set_.erase(window_index);
88 PostMessage(parent, WM_CLOSE, 0, 0);
91 void PluginProcessHost::AddWindow(HWND window) {
92 plugin_parent_windows_set_.insert(window);
94 #endif // defined(OS_WIN)
96 // NOTE: changes to this class need to be reviewed by the security team.
97 class PluginSandboxedProcessLauncherDelegate
98 : public SandboxedProcessLauncherDelegate {
100 explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
101 #if defined(OS_POSIX)
102 : ipc_fd_(host->TakeClientFileDescriptor())
106 ~PluginSandboxedProcessLauncherDelegate() override {}
109 virtual bool ShouldSandbox() override {
113 #elif defined(OS_POSIX)
114 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
118 #if defined(OS_POSIX)
119 base::ScopedFD ipc_fd_;
122 DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
125 PluginProcessHost::PluginProcessHost()
126 : pid_(base::kNullProcessId)
127 #if defined(OS_MACOSX)
128 , plugin_cursor_visible_(true)
131 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_PLUGIN, this));
134 PluginProcessHost::~PluginProcessHost() {
136 // We erase HWNDs from the plugin_parent_windows_set_ when we receive a
137 // notification that the window is being destroyed. If we don't receive this
138 // notification and the PluginProcessHost instance is being destroyed, it
139 // means that the plugin process crashed. We paint a sad face in this case in
140 // the renderer process. To ensure that the sad face shows up, and we don't
141 // leak HWNDs, we should destroy existing plugin parent windows.
142 std::set<HWND>::iterator window_index;
143 for (window_index = plugin_parent_windows_set_.begin();
144 window_index != plugin_parent_windows_set_.end();
146 PostMessage(*window_index, WM_CLOSE, 0, 0);
148 #elif defined(OS_MACOSX)
149 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
150 // If the plugin process crashed but had fullscreen windows open at the time,
151 // make sure that the menu bar is visible.
152 for (size_t i = 0; i < plugin_fullscreen_windows_set_.size(); ++i) {
153 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
154 base::Bind(base::mac::ReleaseFullScreen,
155 base::mac::kFullScreenModeHideAll));
157 // If the plugin hid the cursor, reset that.
158 if (!plugin_cursor_visible_) {
159 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
160 base::Bind(base::mac::SetCursorVisibility, true));
163 // Cancel all pending and sent requests.
167 base::AutoLock lock(g_process_webplugin_info_lock.Get());
168 g_process_webplugin_info.Get()[pid_] = info_;
172 bool PluginProcessHost::Send(IPC::Message* message) {
173 return process_->Send(message);
176 bool PluginProcessHost::Init(const WebPluginInfo& info) {
178 process_->SetName(info_.name);
180 std::string channel_id = process_->GetHost()->CreateChannel();
181 if (channel_id.empty())
184 // Build command line for plugin. When we have a plugin launcher, we can't
185 // allow "self" on linux and we need the real file path.
186 const base::CommandLine& browser_command_line =
187 *base::CommandLine::ForCurrentProcess();
188 base::CommandLine::StringType plugin_launcher =
189 browser_command_line.GetSwitchValueNative(switches::kPluginLauncher);
191 #if defined(OS_MACOSX)
192 // Run the plug-in process in a mode tolerant of heap execution without
193 // explicit mprotect calls. Some plug-ins still rely on this quaint and
194 // archaic "feature." See http://crbug.com/93551.
195 int flags = ChildProcessHost::CHILD_ALLOW_HEAP_EXECUTION;
196 #elif defined(OS_LINUX)
197 int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
198 ChildProcessHost::CHILD_NORMAL;
200 int flags = ChildProcessHost::CHILD_NORMAL;
203 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
204 if (exe_path.empty())
207 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
208 // Put the process type and plugin path first so they're easier to see
209 // in process listings using native process management tools.
210 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kPluginProcess);
211 cmd_line->AppendSwitchPath(switches::kPluginPath, info.path);
213 // Propagate the following switches to the plugin command line (along with
214 // any associated values) if present in the browser command line
215 static const char* const kSwitchNames[] = {
216 switches::kDisableBreakpad,
217 switches::kDisableDirectNPAPIRequests,
218 switches::kEnableStatsTable,
219 switches::kFullMemoryCrashReport,
220 switches::kLoggingLevel,
221 switches::kLogPluginMessages,
222 switches::kNoSandbox,
223 switches::kPluginStartupDialog,
224 switches::kTraceStartup,
226 switches::kForceDeviceScaleFactor,
227 #if defined(OS_MACOSX)
228 switches::kDisableCoreAnimationPlugins,
229 switches::kEnableSandboxLogging,
233 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
234 arraysize(kSwitchNames));
236 GpuDataManagerImpl::GetInstance()->AppendPluginCommandLine(cmd_line);
238 // If specified, prepend a launcher program to the command line.
239 if (!plugin_launcher.empty())
240 cmd_line->PrependWrapper(plugin_launcher);
242 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
243 if (!locale.empty()) {
244 // Pass on the locale so the null plugin will use the right language in the
245 // prompt to install the desired plugin.
246 cmd_line->AppendSwitchASCII(switches::kLang, locale);
249 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
252 new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
255 // The plugin needs to be shutdown gracefully, i.e. NP_Shutdown needs to be
256 // called on the plugin. The plugin process exits when it receives the
257 // OnChannelError notification indicating that the browser plugin channel has
259 process_->SetTerminateChildOnShutdown(false);
261 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
262 base::Bind(&PluginProcessHost::GetContexts,
263 base::Unretained(this)));
265 // TODO(jam): right now we're passing NULL for appcache, blob storage, and
266 // file system. If NPAPI plugins actually use this, we'll have to plumb them.
267 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
268 process_->GetData().id, PROCESS_TYPE_PLUGIN, NULL, NULL, NULL, NULL,
269 get_contexts_callback);
270 process_->AddFilter(resource_message_filter);
274 void PluginProcessHost::ForceShutdown() {
275 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
276 Send(new PluginProcessMsg_NotifyRenderersOfPendingShutdown());
277 process_->ForceShutdown();
280 bool PluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
282 IPC_BEGIN_MESSAGE_MAP(PluginProcessHost, msg)
283 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelCreated, OnChannelCreated)
284 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelDestroyed,
287 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginWindowDestroyed,
288 OnPluginWindowDestroyed)
290 #if defined(OS_MACOSX)
291 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginShowWindow,
293 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginHideWindow,
295 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSetCursorVisibility,
296 OnPluginSetCursorVisibility)
298 IPC_MESSAGE_UNHANDLED(handled = false)
299 IPC_END_MESSAGE_MAP()
304 void PluginProcessHost::OnChannelConnected(int32 peer_pid) {
305 for (size_t i = 0; i < pending_requests_.size(); ++i) {
306 RequestPluginChannel(pending_requests_[i]);
309 pending_requests_.clear();
313 base::AutoLock lock(g_process_webplugin_info_lock.Get());
314 g_process_webplugin_info.Get()[pid_] = info_;
318 void PluginProcessHost::OnChannelError() {
322 bool PluginProcessHost::CanShutdown() {
323 return sent_requests_.empty();
326 void PluginProcessHost::OnProcessCrashed(int exit_code) {
327 PluginServiceImpl::GetInstance()->RegisterPluginCrash(info_.path);
330 void PluginProcessHost::CancelRequests() {
331 for (size_t i = 0; i < pending_requests_.size(); ++i)
332 pending_requests_[i]->OnError();
333 pending_requests_.clear();
335 while (!sent_requests_.empty()) {
336 Client* client = sent_requests_.front();
339 sent_requests_.pop_front();
343 void PluginProcessHost::OpenChannelToPlugin(Client* client) {
344 BrowserThread::PostTask(
345 BrowserThread::UI, FROM_HERE,
346 base::Bind(&BrowserChildProcessHostImpl::NotifyProcessInstanceCreated,
347 process_->GetData()));
348 client->SetPluginInfo(info_);
349 if (process_->GetHost()->IsChannelOpening()) {
350 // The channel is already in the process of being opened. Put
351 // this "open channel" request into a queue of requests that will
352 // be run once the channel is open.
353 pending_requests_.push_back(client);
357 // We already have an open channel, send a request right away to plugin.
358 RequestPluginChannel(client);
361 void PluginProcessHost::CancelPendingRequest(Client* client) {
362 std::vector<Client*>::iterator it = pending_requests_.begin();
363 while (it != pending_requests_.end()) {
365 pending_requests_.erase(it);
370 DCHECK(it != pending_requests_.end());
373 void PluginProcessHost::CancelSentRequest(Client* client) {
374 std::list<Client*>::iterator it = sent_requests_.begin();
375 while (it != sent_requests_.end()) {
382 DCHECK(it != sent_requests_.end());
385 void PluginProcessHost::RequestPluginChannel(Client* client) {
386 // We can't send any sync messages from the browser because it might lead to
387 // a hang. However this async messages must be answered right away by the
388 // plugin process (i.e. unblocks a Send() call like a sync message) otherwise
389 // a deadlock can occur if the plugin creation request from the renderer is
390 // a result of a sync message by the plugin process.
391 PluginProcessMsg_CreateChannel* msg =
392 new PluginProcessMsg_CreateChannel(
394 client->OffTheRecord());
395 msg->set_unblock(true);
397 sent_requests_.push_back(client);
398 client->OnSentPluginChannelRequest();
404 void PluginProcessHost::OnChannelCreated(
405 const IPC::ChannelHandle& channel_handle) {
406 Client* client = sent_requests_.front();
409 if (!resource_context_map_.count(client->ID())) {
410 ResourceContextEntry entry;
412 entry.resource_context = client->GetResourceContext();
413 resource_context_map_[client->ID()] = entry;
415 resource_context_map_[client->ID()].ref_count++;
416 client->OnChannelOpened(channel_handle);
418 sent_requests_.pop_front();
421 void PluginProcessHost::OnChannelDestroyed(int renderer_id) {
422 resource_context_map_[renderer_id].ref_count--;
423 if (!resource_context_map_[renderer_id].ref_count)
424 resource_context_map_.erase(renderer_id);
427 void PluginProcessHost::GetContexts(const ResourceHostMsg_Request& request,
428 ResourceContext** resource_context,
429 net::URLRequestContext** request_context) {
431 resource_context_map_[request.origin_pid].resource_context;
432 *request_context = (*resource_context)->GetRequestContext();
435 } // namespace content