Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / browser / plugin_process_host.cc
blob4b6f361c7aea466786911c44fb27bdc00186b630
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"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #elif defined(OS_POSIX)
10 #include <utility> // for pair<>
11 #endif
13 #include <vector>
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/gpu/gpu_data_manager_impl.h"
28 #include "content/browser/loader/resource_message_filter.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/geometry/rect.h"
51 #endif
53 #if defined(OS_WIN)
54 #include "base/win/windows_version.h"
55 #include "content/common/plugin_constants_win.h"
56 #endif
58 namespace content {
60 namespace {
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))
72 return false;
74 *info = g_process_webplugin_info.Get()[pid];
75 return true;
78 #if defined(OS_WIN)
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())
85 return;
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 {
99 public:
100 explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
101 #if defined(OS_POSIX)
102 : ipc_fd_(host->TakeClientFileDescriptor())
103 #endif // OS_POSIX
106 ~PluginSandboxedProcessLauncherDelegate() override {}
108 #if defined(OS_WIN)
109 virtual bool ShouldSandbox() override {
110 return false;
113 #elif defined(OS_POSIX)
114 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
115 #endif // OS_WIN
117 private:
118 #if defined(OS_POSIX)
119 base::ScopedFD ipc_fd_;
120 #endif // OS_POSIX
122 DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
125 PluginProcessHost::PluginProcessHost()
126 : pid_(base::kNullProcessId)
127 #if defined(OS_MACOSX)
128 , plugin_cursor_visible_(true)
129 #endif
131 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_PLUGIN, this));
134 PluginProcessHost::~PluginProcessHost() {
135 #if defined(OS_WIN)
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();
145 ++window_index) {
146 PostMessage(*window_index, WM_CLOSE, 0, 0);
148 #elif defined(OS_MACOSX)
149 DCHECK_CURRENTLY_ON(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));
162 #endif
163 // Cancel all pending and sent requests.
164 CancelRequests();
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) {
177 info_ = info;
178 process_->SetName(info_.name);
180 std::string channel_id = process_->GetHost()->CreateChannel();
181 if (channel_id.empty())
182 return false;
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 plugin process in a mode tolerant of heap execution without
193 // explicit mprotect calls. Some plugins 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;
199 #else
200 int flags = ChildProcessHost::CHILD_NORMAL;
201 #endif
203 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
204 if (exe_path.empty())
205 return false;
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,
225 switches::kUseGL,
226 switches::kForceDeviceScaleFactor,
227 #if defined(OS_MACOSX)
228 switches::kDisableCoreAnimationPlugins,
229 switches::kEnableSandboxLogging,
230 #endif
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);
251 // The plugin needs to be shutdown gracefully, i.e. NP_Shutdown needs to be
252 // called on the plugin. The plugin process exits when it receives the
253 // OnChannelError notification indicating that the browser plugin channel has
254 // been destroyed.
255 bool terminate_on_shutdown = false;
256 process_->Launch(
257 new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
258 cmd_line,
259 terminate_on_shutdown);
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, file
266 // system and host zoom level context. If NPAPI plugins actually use this,
267 // we'll have to plumb them.
268 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
269 process_->GetData().id, PROCESS_TYPE_PLUGIN, NULL, NULL, NULL, NULL, NULL,
270 get_contexts_callback);
271 process_->AddFilter(resource_message_filter);
272 return true;
275 void PluginProcessHost::ForceShutdown() {
276 DCHECK_CURRENTLY_ON(BrowserThread::IO);
277 Send(new PluginProcessMsg_NotifyRenderersOfPendingShutdown());
278 process_->ForceShutdown();
281 bool PluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
282 bool handled = true;
283 IPC_BEGIN_MESSAGE_MAP(PluginProcessHost, msg)
284 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelCreated, OnChannelCreated)
285 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelDestroyed,
286 OnChannelDestroyed)
287 #if defined(OS_WIN)
288 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginWindowDestroyed,
289 OnPluginWindowDestroyed)
290 #endif
291 #if defined(OS_MACOSX)
292 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginShowWindow,
293 OnPluginShowWindow)
294 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginHideWindow,
295 OnPluginHideWindow)
296 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSetCursorVisibility,
297 OnPluginSetCursorVisibility)
298 #endif
299 IPC_MESSAGE_UNHANDLED(handled = false)
300 IPC_END_MESSAGE_MAP()
302 return handled;
305 void PluginProcessHost::OnChannelConnected(int32 peer_pid) {
306 for (size_t i = 0; i < pending_requests_.size(); ++i) {
307 RequestPluginChannel(pending_requests_[i]);
310 pending_requests_.clear();
312 pid_ = peer_pid;
314 base::AutoLock lock(g_process_webplugin_info_lock.Get());
315 g_process_webplugin_info.Get()[pid_] = info_;
319 void PluginProcessHost::OnChannelError() {
320 CancelRequests();
323 bool PluginProcessHost::CanShutdown() {
324 return sent_requests_.empty();
327 void PluginProcessHost::OnProcessCrashed(int exit_code) {
328 PluginServiceImpl::GetInstance()->RegisterPluginCrash(info_.path);
331 void PluginProcessHost::CancelRequests() {
332 for (size_t i = 0; i < pending_requests_.size(); ++i)
333 pending_requests_[i]->OnError();
334 pending_requests_.clear();
336 while (!sent_requests_.empty()) {
337 Client* client = sent_requests_.front();
338 if (client)
339 client->OnError();
340 sent_requests_.pop_front();
344 void PluginProcessHost::OpenChannelToPlugin(Client* client) {
345 BrowserThread::PostTask(
346 BrowserThread::UI, FROM_HERE,
347 base::Bind(&BrowserChildProcessHostImpl::NotifyProcessInstanceCreated,
348 process_->GetData()));
349 client->SetPluginInfo(info_);
350 if (process_->GetHost()->IsChannelOpening()) {
351 // The channel is already in the process of being opened. Put
352 // this "open channel" request into a queue of requests that will
353 // be run once the channel is open.
354 pending_requests_.push_back(client);
355 return;
358 // We already have an open channel, send a request right away to plugin.
359 RequestPluginChannel(client);
362 void PluginProcessHost::CancelPendingRequest(Client* client) {
363 std::vector<Client*>::iterator it = pending_requests_.begin();
364 while (it != pending_requests_.end()) {
365 if (client == *it) {
366 pending_requests_.erase(it);
367 return;
369 ++it;
371 DCHECK(it != pending_requests_.end());
374 void PluginProcessHost::CancelSentRequest(Client* client) {
375 std::list<Client*>::iterator it = sent_requests_.begin();
376 while (it != sent_requests_.end()) {
377 if (client == *it) {
378 *it = NULL;
379 return;
381 ++it;
383 DCHECK(it != sent_requests_.end());
386 void PluginProcessHost::RequestPluginChannel(Client* client) {
387 // We can't send any sync messages from the browser because it might lead to
388 // a hang. However this async messages must be answered right away by the
389 // plugin process (i.e. unblocks a Send() call like a sync message) otherwise
390 // a deadlock can occur if the plugin creation request from the renderer is
391 // a result of a sync message by the plugin process.
392 PluginProcessMsg_CreateChannel* msg =
393 new PluginProcessMsg_CreateChannel(
394 client->ID(),
395 client->OffTheRecord());
396 msg->set_unblock(true);
397 if (Send(msg)) {
398 sent_requests_.push_back(client);
399 client->OnSentPluginChannelRequest();
400 } else {
401 client->OnError();
405 void PluginProcessHost::OnChannelCreated(
406 const IPC::ChannelHandle& channel_handle) {
407 Client* client = sent_requests_.front();
409 if (client) {
410 if (!resource_context_map_.count(client->ID())) {
411 ResourceContextEntry entry;
412 entry.ref_count = 0;
413 entry.resource_context = client->GetResourceContext();
414 resource_context_map_[client->ID()] = entry;
416 resource_context_map_[client->ID()].ref_count++;
417 client->OnChannelOpened(channel_handle);
419 sent_requests_.pop_front();
422 void PluginProcessHost::OnChannelDestroyed(int renderer_id) {
423 resource_context_map_[renderer_id].ref_count--;
424 if (!resource_context_map_[renderer_id].ref_count)
425 resource_context_map_.erase(renderer_id);
428 void PluginProcessHost::GetContexts(const ResourceHostMsg_Request& request,
429 ResourceContext** resource_context,
430 net::URLRequestContext** request_context) {
431 *resource_context =
432 resource_context_map_[request.origin_pid].resource_context;
433 *request_context = (*resource_context)->GetRequestContext();
436 } // namespace content