When enabling new profile management programmatically, make sure to set the
[chromium-blink-merge.git] / content / browser / plugin_process_host.cc
blob6c65dbf3c9218bab456161b34f13aab6cf39ad06
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/logging.h"
20 #include "base/metrics/histogram.h"
21 #include "base/path_service.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 "content/browser/browser_child_process_host_impl.h"
26 #include "content/browser/loader/resource_message_filter.h"
27 #include "content/browser/gpu/gpu_data_manager_impl.h"
28 #include "content/browser/plugin_service_impl.h"
29 #include "content/common/child_process_host_impl.h"
30 #include "content/common/plugin_process_messages.h"
31 #include "content/common/resource_messages.h"
32 #include "content/public/browser/browser_thread.h"
33 #include "content/public/browser/content_browser_client.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/plugin_service.h"
36 #include "content/public/browser/resource_context.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/process_type.h"
39 #include "content/public/common/sandboxed_process_launcher_delegate.h"
40 #include "ipc/ipc_switches.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "ui/base/ui_base_switches.h"
43 #include "ui/gfx/native_widget_types.h"
44 #include "ui/gfx/switches.h"
45 #include "ui/gl/gl_switches.h"
47 #if defined(OS_MACOSX)
48 #include "base/mac/mac_util.h"
49 #include "content/common/plugin_carbon_interpose_constants_mac.h"
50 #include "ui/gfx/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 #if defined(OS_WIN)
61 void PluginProcessHost::OnPluginWindowDestroyed(HWND window, HWND parent) {
62 // The window is destroyed at this point, we just care about its parent, which
63 // is the intermediate window we created.
64 std::set<HWND>::iterator window_index =
65 plugin_parent_windows_set_.find(parent);
66 if (window_index == plugin_parent_windows_set_.end())
67 return;
69 plugin_parent_windows_set_.erase(window_index);
70 PostMessage(parent, WM_CLOSE, 0, 0);
73 void PluginProcessHost::AddWindow(HWND window) {
74 plugin_parent_windows_set_.insert(window);
76 #endif // defined(OS_WIN)
78 // NOTE: changes to this class need to be reviewed by the security team.
79 class PluginSandboxedProcessLauncherDelegate
80 : public SandboxedProcessLauncherDelegate {
81 public:
82 explicit PluginSandboxedProcessLauncherDelegate(ChildProcessHost* host)
83 #if defined(OS_POSIX)
84 : ipc_fd_(host->TakeClientFileDescriptor())
85 #endif // OS_POSIX
88 virtual ~PluginSandboxedProcessLauncherDelegate() {}
90 #if defined(OS_WIN)
91 virtual bool ShouldSandbox() OVERRIDE {
92 return false;
95 #elif defined(OS_POSIX)
96 virtual int GetIpcFd() OVERRIDE {
97 return ipc_fd_;
99 #endif // OS_WIN
101 private:
102 #if defined(OS_POSIX)
103 int ipc_fd_;
104 #endif // OS_POSIX
106 DISALLOW_COPY_AND_ASSIGN(PluginSandboxedProcessLauncherDelegate);
109 PluginProcessHost::PluginProcessHost()
110 #if defined(OS_MACOSX)
111 : plugin_cursor_visible_(true)
112 #endif
114 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_PLUGIN, this));
117 PluginProcessHost::~PluginProcessHost() {
118 #if defined(OS_WIN)
119 // We erase HWNDs from the plugin_parent_windows_set_ when we receive a
120 // notification that the window is being destroyed. If we don't receive this
121 // notification and the PluginProcessHost instance is being destroyed, it
122 // means that the plugin process crashed. We paint a sad face in this case in
123 // the renderer process. To ensure that the sad face shows up, and we don't
124 // leak HWNDs, we should destroy existing plugin parent windows.
125 std::set<HWND>::iterator window_index;
126 for (window_index = plugin_parent_windows_set_.begin();
127 window_index != plugin_parent_windows_set_.end();
128 ++window_index) {
129 PostMessage(*window_index, WM_CLOSE, 0, 0);
131 #elif defined(OS_MACOSX)
132 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
133 // If the plugin process crashed but had fullscreen windows open at the time,
134 // make sure that the menu bar is visible.
135 for (size_t i = 0; i < plugin_fullscreen_windows_set_.size(); ++i) {
136 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
137 base::Bind(base::mac::ReleaseFullScreen,
138 base::mac::kFullScreenModeHideAll));
140 // If the plugin hid the cursor, reset that.
141 if (!plugin_cursor_visible_) {
142 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
143 base::Bind(base::mac::SetCursorVisibility, true));
145 #endif
146 // Cancel all pending and sent requests.
147 CancelRequests();
150 bool PluginProcessHost::Send(IPC::Message* message) {
151 return process_->Send(message);
154 bool PluginProcessHost::Init(const WebPluginInfo& info) {
155 info_ = info;
156 process_->SetName(info_.name);
158 std::string channel_id = process_->GetHost()->CreateChannel();
159 if (channel_id.empty())
160 return false;
162 // Build command line for plugin. When we have a plugin launcher, we can't
163 // allow "self" on linux and we need the real file path.
164 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
165 CommandLine::StringType plugin_launcher =
166 browser_command_line.GetSwitchValueNative(switches::kPluginLauncher);
168 #if defined(OS_MACOSX)
169 // Run the plug-in process in a mode tolerant of heap execution without
170 // explicit mprotect calls. Some plug-ins still rely on this quaint and
171 // archaic "feature." See http://crbug.com/93551.
172 int flags = ChildProcessHost::CHILD_ALLOW_HEAP_EXECUTION;
173 #elif defined(OS_LINUX)
174 int flags = plugin_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
175 ChildProcessHost::CHILD_NORMAL;
176 #else
177 int flags = ChildProcessHost::CHILD_NORMAL;
178 #endif
180 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
181 if (exe_path.empty())
182 return false;
184 CommandLine* cmd_line = new CommandLine(exe_path);
185 // Put the process type and plugin path first so they're easier to see
186 // in process listings using native process management tools.
187 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kPluginProcess);
188 cmd_line->AppendSwitchPath(switches::kPluginPath, info.path);
190 // Propagate the following switches to the plugin command line (along with
191 // any associated values) if present in the browser command line
192 static const char* const kSwitchNames[] = {
193 switches::kDisableBreakpad,
194 switches::kDisableDirectNPAPIRequests,
195 switches::kEnableStatsTable,
196 switches::kFullMemoryCrashReport,
197 switches::kLoggingLevel,
198 switches::kLogPluginMessages,
199 switches::kNoSandbox,
200 switches::kPluginStartupDialog,
201 switches::kTraceStartup,
202 switches::kUseGL,
203 switches::kForceDeviceScaleFactor,
204 #if defined(OS_MACOSX)
205 switches::kDisableCoreAnimationPlugins,
206 switches::kEnableSandboxLogging,
207 #endif
210 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
211 arraysize(kSwitchNames));
213 GpuDataManagerImpl::GetInstance()->AppendPluginCommandLine(cmd_line);
215 // If specified, prepend a launcher program to the command line.
216 if (!plugin_launcher.empty())
217 cmd_line->PrependWrapper(plugin_launcher);
219 std::string locale = GetContentClient()->browser()->GetApplicationLocale();
220 if (!locale.empty()) {
221 // Pass on the locale so the null plugin will use the right language in the
222 // prompt to install the desired plugin.
223 cmd_line->AppendSwitchASCII(switches::kLang, locale);
226 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
228 #if defined(OS_POSIX)
229 base::EnvironmentMap env;
230 #if defined(OS_MACOSX) && !defined(__LP64__)
231 if (browser_command_line.HasSwitch(switches::kEnableCarbonInterposing)) {
232 std::string interpose_list = GetContentClient()->GetCarbonInterposePath();
233 if (!interpose_list.empty()) {
234 // Add our interposing library for Carbon. This is stripped back out in
235 // plugin_main.cc, so changes here should be reflected there.
236 const char* existing_list = getenv(kDYLDInsertLibrariesKey);
237 if (existing_list) {
238 interpose_list.insert(0, ":");
239 interpose_list.insert(0, existing_list);
242 env[kDYLDInsertLibrariesKey] = interpose_list;
244 #endif
245 #endif
247 process_->Launch(
248 new PluginSandboxedProcessLauncherDelegate(process_->GetHost()),
249 cmd_line);
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 process_->SetTerminateChildOnShutdown(false);
257 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
258 base::Bind(&PluginProcessHost::GetContexts,
259 base::Unretained(this)));
261 // TODO(jam): right now we're passing NULL for appcache, blob storage, and
262 // file system. If NPAPI plugins actually use this, we'll have to plumb them.
263 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
264 process_->GetData().id, PROCESS_TYPE_PLUGIN, NULL, NULL, NULL, NULL,
265 get_contexts_callback);
266 process_->AddFilter(resource_message_filter);
267 return true;
270 void PluginProcessHost::ForceShutdown() {
271 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
272 Send(new PluginProcessMsg_NotifyRenderersOfPendingShutdown());
273 process_->ForceShutdown();
276 bool PluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
277 bool handled = true;
278 IPC_BEGIN_MESSAGE_MAP(PluginProcessHost, msg)
279 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelCreated, OnChannelCreated)
280 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_ChannelDestroyed,
281 OnChannelDestroyed)
282 #if defined(OS_WIN)
283 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginWindowDestroyed,
284 OnPluginWindowDestroyed)
285 #endif
286 #if defined(OS_MACOSX)
287 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSelectWindow,
288 OnPluginSelectWindow)
289 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginShowWindow,
290 OnPluginShowWindow)
291 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginHideWindow,
292 OnPluginHideWindow)
293 IPC_MESSAGE_HANDLER(PluginProcessHostMsg_PluginSetCursorVisibility,
294 OnPluginSetCursorVisibility)
295 #endif
296 IPC_MESSAGE_UNHANDLED(handled = false)
297 IPC_END_MESSAGE_MAP()
299 return handled;
302 void PluginProcessHost::OnChannelConnected(int32 peer_pid) {
303 for (size_t i = 0; i < pending_requests_.size(); ++i) {
304 RequestPluginChannel(pending_requests_[i]);
307 pending_requests_.clear();
310 void PluginProcessHost::OnChannelError() {
311 CancelRequests();
314 bool PluginProcessHost::CanShutdown() {
315 return sent_requests_.empty();
318 void PluginProcessHost::OnProcessCrashed(int exit_code) {
319 PluginServiceImpl::GetInstance()->RegisterPluginCrash(info_.path);
322 void PluginProcessHost::CancelRequests() {
323 for (size_t i = 0; i < pending_requests_.size(); ++i)
324 pending_requests_[i]->OnError();
325 pending_requests_.clear();
327 while (!sent_requests_.empty()) {
328 Client* client = sent_requests_.front();
329 if (client)
330 client->OnError();
331 sent_requests_.pop_front();
335 void PluginProcessHost::OpenChannelToPlugin(Client* client) {
336 BrowserThread::PostTask(
337 BrowserThread::UI, FROM_HERE,
338 base::Bind(&BrowserChildProcessHostImpl::NotifyProcessInstanceCreated,
339 process_->GetData()));
340 client->SetPluginInfo(info_);
341 if (process_->GetHost()->IsChannelOpening()) {
342 // The channel is already in the process of being opened. Put
343 // this "open channel" request into a queue of requests that will
344 // be run once the channel is open.
345 pending_requests_.push_back(client);
346 return;
349 // We already have an open channel, send a request right away to plugin.
350 RequestPluginChannel(client);
353 void PluginProcessHost::CancelPendingRequest(Client* client) {
354 std::vector<Client*>::iterator it = pending_requests_.begin();
355 while (it != pending_requests_.end()) {
356 if (client == *it) {
357 pending_requests_.erase(it);
358 return;
360 ++it;
362 DCHECK(it != pending_requests_.end());
365 void PluginProcessHost::CancelSentRequest(Client* client) {
366 std::list<Client*>::iterator it = sent_requests_.begin();
367 while (it != sent_requests_.end()) {
368 if (client == *it) {
369 *it = NULL;
370 return;
372 ++it;
374 DCHECK(it != sent_requests_.end());
377 void PluginProcessHost::RequestPluginChannel(Client* client) {
378 // We can't send any sync messages from the browser because it might lead to
379 // a hang. However this async messages must be answered right away by the
380 // plugin process (i.e. unblocks a Send() call like a sync message) otherwise
381 // a deadlock can occur if the plugin creation request from the renderer is
382 // a result of a sync message by the plugin process.
383 PluginProcessMsg_CreateChannel* msg =
384 new PluginProcessMsg_CreateChannel(
385 client->ID(),
386 client->OffTheRecord());
387 msg->set_unblock(true);
388 if (Send(msg)) {
389 sent_requests_.push_back(client);
390 client->OnSentPluginChannelRequest();
391 } else {
392 client->OnError();
396 void PluginProcessHost::OnChannelCreated(
397 const IPC::ChannelHandle& channel_handle) {
398 Client* client = sent_requests_.front();
400 if (client) {
401 if (!resource_context_map_.count(client->ID())) {
402 ResourceContextEntry entry;
403 entry.ref_count = 0;
404 entry.resource_context = client->GetResourceContext();
405 resource_context_map_[client->ID()] = entry;
407 resource_context_map_[client->ID()].ref_count++;
408 client->OnChannelOpened(channel_handle);
410 sent_requests_.pop_front();
413 void PluginProcessHost::OnChannelDestroyed(int renderer_id) {
414 resource_context_map_[renderer_id].ref_count--;
415 if (!resource_context_map_[renderer_id].ref_count)
416 resource_context_map_.erase(renderer_id);
419 void PluginProcessHost::GetContexts(const ResourceHostMsg_Request& request,
420 ResourceContext** resource_context,
421 net::URLRequestContext** request_context) {
422 *resource_context =
423 resource_context_map_[request.origin_pid].resource_context;
424 *request_context = (*resource_context)->GetRequestContext();
427 } // namespace content