Apply _RELATIVE relocations ahead of others.
[chromium-blink-merge.git] / content / browser / plugin_process_host.cc
blob2c10b09889b8ebd0461335627bd128e2e80c9fd6
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/path_service.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/synchronization/lock.h"
27 #include "content/browser/browser_child_process_host_impl.h"
28 #include "content/browser/loader/resource_message_filter.h"
29 #include "content/browser/gpu/gpu_data_manager_impl.h"
30 #include "content/browser/plugin_service_impl.h"
31 #include "content/common/child_process_host_impl.h"
32 #include "content/common/plugin_process_messages.h"
33 #include "content/common/resource_messages.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "content/public/browser/content_browser_client.h"
36 #include "content/public/browser/notification_types.h"
37 #include "content/public/browser/plugin_service.h"
38 #include "content/public/browser/resource_context.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/process_type.h"
41 #include "content/public/common/sandboxed_process_launcher_delegate.h"
42 #include "ipc/ipc_switches.h"
43 #include "net/url_request/url_request_context_getter.h"
44 #include "ui/base/ui_base_switches.h"
45 #include "ui/gfx/native_widget_types.h"
46 #include "ui/gfx/switches.h"
47 #include "ui/gl/gl_switches.h"
49 #if defined(OS_MACOSX)
50 #include "base/mac/mac_util.h"
51 #include "ui/gfx/rect.h"
52 #endif
54 #if defined(OS_WIN)
55 #include "base/win/windows_version.h"
56 #include "content/common/plugin_constants_win.h"
57 #endif
59 namespace content {
61 namespace {
63 base::LazyInstance<std::map<base::ProcessId, WebPluginInfo> >
64 g_process_webplugin_info = LAZY_INSTANCE_INITIALIZER;
65 base::LazyInstance<base::Lock>::Leaky
66 g_process_webplugin_info_lock = LAZY_INSTANCE_INITIALIZER;
69 bool PluginProcessHost::GetWebPluginInfoFromPluginPid(base::ProcessId pid,
70 WebPluginInfo* info) {
71 base::AutoLock lock(g_process_webplugin_info_lock.Get());
72 if (!g_process_webplugin_info.Get().count(pid))
73 return false;
75 *info = g_process_webplugin_info.Get()[pid];
76 return true;
79 #if defined(OS_WIN)
80 void PluginProcessHost::OnPluginWindowDestroyed(HWND window, HWND parent) {
81 // The window is destroyed at this point, we just care about its parent, which
82 // is the intermediate window we created.
83 std::set<HWND>::iterator window_index =
84 plugin_parent_windows_set_.find(parent);
85 if (window_index == plugin_parent_windows_set_.end())
86 return;
88 plugin_parent_windows_set_.erase(window_index);
89 PostMessage(parent, WM_CLOSE, 0, 0);
92 void PluginProcessHost::AddWindow(HWND window) {
93 plugin_parent_windows_set_.insert(window);
95 #endif // defined(OS_WIN)
97 // NOTE: changes to this class need to be reviewed by the security team.
98 class PluginSandboxedProcessLauncherDelegate
99 : public SandboxedProcessLauncherDelegate {
100 public:
101 explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
102 #if defined(OS_POSIX)
103 : ipc_fd_(host->TakeClientFileDescriptor())
104 #endif // OS_POSIX
107 ~PluginSandboxedProcessLauncherDelegate() override {}
109 #if defined(OS_WIN)
110 virtual bool ShouldSandbox() override {
111 return false;
114 #elif defined(OS_POSIX)
115 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
116 #endif // OS_WIN
118 private:
119 #if defined(OS_POSIX)
120 base::ScopedFD ipc_fd_;
121 #endif // OS_POSIX
123 DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
126 PluginProcessHost::PluginProcessHost()
127 : pid_(base::kNullProcessId)
128 #if defined(OS_MACOSX)
129 , plugin_cursor_visible_(true)
130 #endif
132 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_PLUGIN, this));
135 PluginProcessHost::~PluginProcessHost() {
136 #if defined(OS_WIN)
137 // We erase HWNDs from the plugin_parent_windows_set_ when we receive a
138 // notification that the window is being destroyed. If we don't receive this
139 // notification and the PluginProcessHost instance is being destroyed, it
140 // means that the plugin process crashed. We paint a sad face in this case in
141 // the renderer process. To ensure that the sad face shows up, and we don't
142 // leak HWNDs, we should destroy existing plugin parent windows.
143 std::set<HWND>::iterator window_index;
144 for (window_index = plugin_parent_windows_set_.begin();
145 window_index != plugin_parent_windows_set_.end();
146 ++window_index) {
147 PostMessage(*window_index, WM_CLOSE, 0, 0);
149 #elif defined(OS_MACOSX)
150 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
151 // If the plugin process crashed but had fullscreen windows open at the time,
152 // make sure that the menu bar is visible.
153 for (size_t i = 0; i < plugin_fullscreen_windows_set_.size(); ++i) {
154 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
155 base::Bind(base::mac::ReleaseFullScreen,
156 base::mac::kFullScreenModeHideAll));
158 // If the plugin hid the cursor, reset that.
159 if (!plugin_cursor_visible_) {
160 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
161 base::Bind(base::mac::SetCursorVisibility, true));
163 #endif
164 // Cancel all pending and sent requests.
165 CancelRequests();
168 base::AutoLock lock(g_process_webplugin_info_lock.Get());
169 g_process_webplugin_info.Get()[pid_] = info_;
173 bool PluginProcessHost::Send(IPC::Message* message) {
174 return process_->Send(message);
177 bool PluginProcessHost::Init(const WebPluginInfo& info) {
178 info_ = info;
179 process_->SetName(info_.name);
181 std::string channel_id = process_->GetHost()->CreateChannel();
182 if (channel_id.empty())
183 return false;
185 // Build command line for plugin. When we have a plugin launcher, we can't
186 // allow "self" on linux and we need the real file path.
187 const base::CommandLine& browser_command_line =
188 *base::CommandLine::ForCurrentProcess();
189 base::CommandLine::StringType plugin_launcher =
190 browser_command_line.GetSwitchValueNative(switches::kPluginLauncher);
192 #if defined(OS_MACOSX)
193 // Run the plug-in process in a mode tolerant of heap execution without
194 // explicit mprotect calls. Some plug-ins still rely on this quaint and
195 // archaic "feature." See http://crbug.com/93551.
196 int flags = ChildProcessHost::CHILD_ALLOW_HEAP_EXECUTION;
197 #elif defined(OS_LINUX)
198 int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
199 ChildProcessHost::CHILD_NORMAL;
200 #else
201 int flags = ChildProcessHost::CHILD_NORMAL;
202 #endif
204 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
205 if (exe_path.empty())
206 return false;
208 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
209 // Put the process type and plugin path first so they're easier to see
210 // in process listings using native process management tools.
211 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kPluginProcess);
212 cmd_line->AppendSwitchPath(switches::kPluginPath, info.path);
214 // Propagate the following switches to the plugin command line (along with
215 // any associated values) if present in the browser command line
216 static const char* const kSwitchNames[] = {
217 switches::kDisableBreakpad,
218 switches::kDisableDirectNPAPIRequests,
219 switches::kEnableStatsTable,
220 switches::kFullMemoryCrashReport,
221 switches::kLoggingLevel,
222 switches::kLogPluginMessages,
223 switches::kNoSandbox,
224 switches::kPluginStartupDialog,
225 switches::kTraceStartup,
226 switches::kUseGL,
227 switches::kForceDeviceScaleFactor,
228 #if defined(OS_MACOSX)
229 switches::kDisableCoreAnimationPlugins,
230 switches::kEnableSandboxLogging,
231 #endif
234 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
235 arraysize(kSwitchNames));
237 GpuDataManagerImpl::GetInstance()->AppendPluginCommandLine(cmd_line);
239 // If specified, prepend a launcher program to the command line.
240 if (!plugin_launcher.empty())
241 cmd_line->PrependWrapper(plugin_launcher);
243 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
244 if (!locale.empty()) {
245 // Pass on the locale so the null plugin will use the right language in the
246 // prompt to install the desired plugin.
247 cmd_line->AppendSwitchASCII(switches::kLang, locale);
250 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
252 process_->Launch(
253 new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
254 cmd_line);
256 // The plugin needs to be shutdown gracefully, i.e. NP_Shutdown needs to be
257 // called on the plugin. The plugin process exits when it receives the
258 // OnChannelError notification indicating that the browser plugin channel has
259 // been destroyed.
260 process_->SetTerminateChildOnShutdown(false);
262 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
263 base::Bind(&PluginProcessHost::GetContexts,
264 base::Unretained(this)));
266 // TODO(jam): right now we're passing NULL for appcache, blob storage, and
267 // file system. If NPAPI plugins actually use this, we'll have to plumb them.
268 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
269 process_->GetData().id, PROCESS_TYPE_PLUGIN, NULL, NULL, NULL, NULL,
270 get_contexts_callback);
271 process_->AddFilter(resource_message_filter);
272 return true;
275 void PluginProcessHost::ForceShutdown() {
276 DCHECK(BrowserThread::CurrentlyOn(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