Plugin Power Saver: Add flag to experiment behind.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blob76a77177c8e43b2322461cb6437603dbaeca71f3
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 // Represents the browser side of the browser <--> renderer communication
6 // channel. There will be one RenderProcessHost per renderer process.
8 #include "content/browser/renderer_host/render_process_host_impl.h"
10 #include <algorithm>
11 #include <limits>
12 #include <vector>
14 #if defined(OS_POSIX)
15 #include <utility> // for pair<>
16 #endif
18 #include "base/base_switches.h"
19 #include "base/bind.h"
20 #include "base/bind_helpers.h"
21 #include "base/callback.h"
22 #include "base/command_line.h"
23 #include "base/debug/trace_event.h"
24 #include "base/files/file.h"
25 #include "base/lazy_instance.h"
26 #include "base/logging.h"
27 #include "base/metrics/field_trial.h"
28 #include "base/metrics/histogram.h"
29 #include "base/path_service.h"
30 #include "base/process/process_handle.h"
31 #include "base/rand_util.h"
32 #include "base/stl_util.h"
33 #include "base/strings/string_number_conversions.h"
34 #include "base/strings/string_util.h"
35 #include "base/supports_user_data.h"
36 #include "base/sys_info.h"
37 #include "base/threading/thread.h"
38 #include "base/threading/thread_restrictions.h"
39 #include "base/tracked_objects.h"
40 #include "cc/base/switches.h"
41 #include "content/browser/appcache/appcache_dispatcher_host.h"
42 #include "content/browser/appcache/chrome_appcache_service.h"
43 #include "content/browser/battery_status/battery_status_message_filter.h"
44 #include "content/browser/browser_child_process_host_impl.h"
45 #include "content/browser/browser_main.h"
46 #include "content/browser/browser_main_loop.h"
47 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
48 #include "content/browser/child_process_security_policy_impl.h"
49 #include "content/browser/device_sensors/device_light_message_filter.h"
50 #include "content/browser/device_sensors/device_motion_message_filter.h"
51 #include "content/browser/device_sensors/device_orientation_message_filter.h"
52 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
53 #include "content/browser/dom_storage/dom_storage_message_filter.h"
54 #include "content/browser/download/mhtml_generation_manager.h"
55 #include "content/browser/fileapi/chrome_blob_storage_context.h"
56 #include "content/browser/fileapi/fileapi_message_filter.h"
57 #include "content/browser/frame_host/render_frame_message_filter.h"
58 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
59 #include "content/browser/gpu/compositor_util.h"
60 #include "content/browser/gpu/gpu_data_manager_impl.h"
61 #include "content/browser/gpu/gpu_process_host.h"
62 #include "content/browser/gpu/shader_disk_cache.h"
63 #include "content/browser/histogram_message_filter.h"
64 #include "content/browser/indexed_db/indexed_db_context_impl.h"
65 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
66 #include "content/browser/loader/resource_message_filter.h"
67 #include "content/browser/loader/resource_scheduler_filter.h"
68 #include "content/browser/media/capture/audio_mirroring_manager.h"
69 #include "content/browser/media/media_internals.h"
70 #include "content/browser/media/midi_host.h"
71 #include "content/browser/message_port_message_filter.h"
72 #include "content/browser/mime_registry_message_filter.h"
73 #include "content/browser/mojo/mojo_application_host.h"
74 #include "content/browser/profiler_message_filter.h"
75 #include "content/browser/push_messaging_message_filter.h"
76 #include "content/browser/quota_dispatcher_host.h"
77 #include "content/browser/renderer_host/clipboard_message_filter.h"
78 #include "content/browser/renderer_host/database_message_filter.h"
79 #include "content/browser/renderer_host/file_utilities_message_filter.h"
80 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
81 #include "content/browser/renderer_host/gpu_message_filter.h"
82 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
83 #include "content/browser/renderer_host/media/audio_renderer_host.h"
84 #include "content/browser/renderer_host/media/device_request_message_filter.h"
85 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
86 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
87 #include "content/browser/renderer_host/media/video_capture_host.h"
88 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
89 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
90 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
91 #include "content/browser/renderer_host/render_message_filter.h"
92 #include "content/browser/renderer_host/render_view_host_delegate.h"
93 #include "content/browser/renderer_host/render_view_host_impl.h"
94 #include "content/browser/renderer_host/render_widget_helper.h"
95 #include "content/browser/renderer_host/render_widget_host_impl.h"
96 #include "content/browser/renderer_host/socket_stream_dispatcher_host.h"
97 #include "content/browser/renderer_host/text_input_client_message_filter.h"
98 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
99 #include "content/browser/resolve_proxy_msg_helper.h"
100 #include "content/browser/service_worker/service_worker_context_wrapper.h"
101 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
102 #include "content/browser/shared_worker/shared_worker_message_filter.h"
103 #include "content/browser/shared_worker/worker_storage_partition.h"
104 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
105 #include "content/browser/storage_partition_impl.h"
106 #include "content/browser/streams/stream_context.h"
107 #include "content/browser/tracing/trace_message_filter.h"
108 #include "content/browser/vibration/vibration_message_filter.h"
109 #include "content/browser/webui/web_ui_controller_factory_registry.h"
110 #include "content/common/child_process_host_impl.h"
111 #include "content/common/child_process_messages.h"
112 #include "content/common/content_switches_internal.h"
113 #include "content/common/gpu/gpu_messages.h"
114 #include "content/common/mojo/mojo_messages.h"
115 #include "content/common/resource_messages.h"
116 #include "content/common/view_messages.h"
117 #include "content/public/browser/browser_context.h"
118 #include "content/public/browser/content_browser_client.h"
119 #include "content/public/browser/notification_service.h"
120 #include "content/public/browser/notification_types.h"
121 #include "content/public/browser/render_process_host_factory.h"
122 #include "content/public/browser/render_process_host_observer.h"
123 #include "content/public/browser/render_widget_host.h"
124 #include "content/public/browser/render_widget_host_iterator.h"
125 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
126 #include "content/public/browser/resource_context.h"
127 #include "content/public/browser/user_metrics.h"
128 #include "content/public/browser/worker_service.h"
129 #include "content/public/common/content_constants.h"
130 #include "content/public/common/content_switches.h"
131 #include "content/public/common/process_type.h"
132 #include "content/public/common/resource_type.h"
133 #include "content/public/common/result_codes.h"
134 #include "content/public/common/sandboxed_process_launcher_delegate.h"
135 #include "content/public/common/url_constants.h"
136 #include "gpu/command_buffer/client/gpu_switches.h"
137 #include "gpu/command_buffer/service/gpu_switches.h"
138 #include "ipc/ipc_channel.h"
139 #include "ipc/ipc_logging.h"
140 #include "ipc/ipc_switches.h"
141 #include "ipc/mojo/ipc_channel_mojo.h"
142 #include "ipc/mojo/ipc_channel_mojo_host.h"
143 #include "media/base/media_switches.h"
144 #include "net/url_request/url_request_context_getter.h"
145 #include "ppapi/shared_impl/ppapi_switches.h"
146 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
147 #include "third_party/skia/include/core/SkBitmap.h"
148 #include "ui/base/ui_base_switches.h"
149 #include "ui/events/event_switches.h"
150 #include "ui/gfx/switches.h"
151 #include "ui/gl/gl_switches.h"
152 #include "ui/native_theme/native_theme_switches.h"
154 #if defined(OS_ANDROID)
155 #include "content/browser/media/android/browser_demuxer_android.h"
156 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
157 #endif
159 #if defined(OS_WIN)
160 #include "base/win/scoped_com_initializer.h"
161 #include "content/common/font_cache_dispatcher_win.h"
162 #include "content/common/sandbox_win.h"
163 #include "ui/gfx/win/dpi.h"
164 #endif
166 #if defined(ENABLE_BROWSER_CDMS)
167 #include "content/browser/media/cdm/browser_cdm_manager.h"
168 #endif
170 #if defined(ENABLE_PLUGINS)
171 #include "content/browser/plugin_service_impl.h"
172 #endif
174 #if defined(ENABLE_WEBRTC)
175 #include "content/browser/media/webrtc_internals.h"
176 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
177 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
178 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
179 #include "content/common/media/aec_dump_messages.h"
180 #include "content/common/media/media_stream_messages.h"
181 #endif
183 extern bool g_exited_main_message_loop;
185 namespace content {
186 namespace {
188 const char kSiteProcessMapKeyName[] = "content_site_process_map";
190 void CacheShaderInfo(int32 id, base::FilePath path) {
191 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
194 void RemoveShaderInfo(int32 id) {
195 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
198 net::URLRequestContext* GetRequestContext(
199 scoped_refptr<net::URLRequestContextGetter> request_context,
200 scoped_refptr<net::URLRequestContextGetter> media_request_context,
201 ResourceType resource_type) {
202 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
203 // context specific to media for handling it because these resources have
204 // specific needs for caching.
205 if (resource_type == RESOURCE_TYPE_MEDIA)
206 return media_request_context->GetURLRequestContext();
207 return request_context->GetURLRequestContext();
210 void GetContexts(
211 ResourceContext* resource_context,
212 scoped_refptr<net::URLRequestContextGetter> request_context,
213 scoped_refptr<net::URLRequestContextGetter> media_request_context,
214 const ResourceHostMsg_Request& request,
215 ResourceContext** resource_context_out,
216 net::URLRequestContext** request_context_out) {
217 *resource_context_out = resource_context;
218 *request_context_out =
219 GetRequestContext(request_context, media_request_context,
220 request.resource_type);
223 #if defined(ENABLE_WEBRTC)
224 // Creates a file used for diagnostic echo canceller recordings for handing
225 // over to the renderer.
226 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
227 base::FilePath file_path,
228 base::ProcessHandle process) {
229 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
230 base::File dump_file(file_path,
231 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
232 if (!dump_file.IsValid()) {
233 VLOG(1) << "Could not open AEC dump file, error=" <<
234 dump_file.error_details();
235 return IPC::InvalidPlatformFileForTransit();
237 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
240 // Does nothing. Just to avoid races between enable and disable.
241 void DisableAecDumpOnFileThread() {
242 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
244 #endif
246 // the global list of all renderer processes
247 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
248 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
250 // Map of site to process, to ensure we only have one RenderProcessHost per
251 // site in process-per-site mode. Each map is specific to a BrowserContext.
252 class SiteProcessMap : public base::SupportsUserData::Data {
253 public:
254 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
255 SiteProcessMap() {}
257 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
258 map_[site] = process;
261 RenderProcessHost* FindProcess(const std::string& site) {
262 SiteToProcessMap::iterator i = map_.find(site);
263 if (i != map_.end())
264 return i->second;
265 return NULL;
268 void RemoveProcess(RenderProcessHost* host) {
269 // Find all instances of this process in the map, then separately remove
270 // them.
271 std::set<std::string> sites;
272 for (SiteToProcessMap::const_iterator i = map_.begin();
273 i != map_.end();
274 i++) {
275 if (i->second == host)
276 sites.insert(i->first);
278 for (std::set<std::string>::iterator i = sites.begin();
279 i != sites.end();
280 i++) {
281 SiteToProcessMap::iterator iter = map_.find(*i);
282 if (iter != map_.end()) {
283 DCHECK_EQ(iter->second, host);
284 map_.erase(iter);
289 private:
290 SiteToProcessMap map_;
293 // Find the SiteProcessMap specific to the given context.
294 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
295 DCHECK(context);
296 SiteProcessMap* map = static_cast<SiteProcessMap*>(
297 context->GetUserData(kSiteProcessMapKeyName));
298 if (!map) {
299 map = new SiteProcessMap();
300 context->SetUserData(kSiteProcessMapKeyName, map);
302 return map;
305 // NOTE: changes to this class need to be reviewed by the security team.
306 class RendererSandboxedProcessLauncherDelegate
307 : public SandboxedProcessLauncherDelegate {
308 public:
309 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
310 #if defined(OS_POSIX)
311 : ipc_fd_(channel->TakeClientFileDescriptor())
312 #endif // OS_POSIX
315 virtual ~RendererSandboxedProcessLauncherDelegate() {}
317 #if defined(OS_WIN)
318 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
319 bool* success) {
320 AddBaseHandleClosePolicy(policy);
321 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
324 #elif defined(OS_POSIX)
325 virtual bool ShouldUseZygote() OVERRIDE {
326 const base::CommandLine& browser_command_line =
327 *base::CommandLine::ForCurrentProcess();
328 base::CommandLine::StringType renderer_prefix =
329 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
330 return renderer_prefix.empty();
332 virtual int GetIpcFd() OVERRIDE {
333 return ipc_fd_;
335 #endif // OS_WIN
337 private:
338 #if defined(OS_POSIX)
339 int ipc_fd_;
340 #endif // OS_POSIX
343 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
345 class SessionStorageHolder : public base::SupportsUserData::Data {
346 public:
347 SessionStorageHolder() {}
348 virtual ~SessionStorageHolder() {}
350 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
351 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
354 void Release(int old_route_id) {
355 session_storage_namespaces_awaiting_close_.erase(old_route_id);
358 private:
359 std::map<int, SessionStorageNamespaceMap >
360 session_storage_namespaces_awaiting_close_;
361 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
364 } // namespace
366 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
368 base::MessageLoop* g_in_process_thread;
370 base::MessageLoop*
371 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
372 return g_in_process_thread;
375 // Stores the maximum number of renderer processes the content module can
376 // create.
377 static size_t g_max_renderer_count_override = 0;
379 // static
380 size_t RenderProcessHost::GetMaxRendererProcessCount() {
381 if (g_max_renderer_count_override)
382 return g_max_renderer_count_override;
384 #if defined(OS_ANDROID)
385 // On Android we don't maintain a limit of renderer process hosts - we are
386 // happy with keeping a lot of these, as long as the number of live renderer
387 // processes remains reasonable, and on Android the OS takes care of that.
388 return std::numeric_limits<size_t>::max();
389 #endif
391 // On other platforms, we calculate the maximum number of renderer process
392 // hosts according to the amount of installed memory as reported by the OS.
393 // The calculation assumes that you want the renderers to use half of the
394 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
395 // this assumption, you need to adjust the ThirtyFourTabs test to match the
396 // expected number of processes.
398 // With the given amounts of installed memory below on a 32-bit CPU, the
399 // maximum renderer count will roughly be as follows:
401 // 128 MB -> 3
402 // 512 MB -> 6
403 // 1024 MB -> 12
404 // 4096 MB -> 51
405 // 16384 MB -> 82 (kMaxRendererProcessCount)
407 static size_t max_count = 0;
408 if (!max_count) {
409 const size_t kEstimatedWebContentsMemoryUsage =
410 #if defined(ARCH_CPU_64_BITS)
411 60; // In MB
412 #else
413 40; // In MB
414 #endif
415 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
416 max_count /= kEstimatedWebContentsMemoryUsage;
418 const size_t kMinRendererProcessCount = 3;
419 max_count = std::max(max_count, kMinRendererProcessCount);
420 max_count = std::min(max_count, kMaxRendererProcessCount);
422 return max_count;
425 // static
426 bool g_run_renderer_in_process_ = false;
428 // static
429 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
430 g_max_renderer_count_override = count;
433 RenderProcessHostImpl::RenderProcessHostImpl(
434 BrowserContext* browser_context,
435 StoragePartitionImpl* storage_partition_impl,
436 bool is_isolated_guest)
437 : fast_shutdown_started_(false),
438 deleting_soon_(false),
439 #ifndef NDEBUG
440 is_self_deleted_(false),
441 #endif
442 pending_views_(0),
443 mojo_application_host_(new MojoApplicationHost),
444 mojo_activation_required_(false),
445 visible_widgets_(0),
446 backgrounded_(true),
447 is_initialized_(false),
448 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
449 browser_context_(browser_context),
450 storage_partition_impl_(storage_partition_impl),
451 sudden_termination_allowed_(true),
452 ignore_input_events_(false),
453 is_isolated_guest_(is_isolated_guest),
454 gpu_observer_registered_(false),
455 delayed_cleanup_needed_(false),
456 within_process_died_observer_(false),
457 power_monitor_broadcaster_(this),
458 worker_ref_count_(0),
459 weak_factory_(this) {
460 widget_helper_ = new RenderWidgetHelper();
462 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
464 CHECK(!g_exited_main_message_loop);
465 RegisterHost(GetID(), this);
466 g_all_hosts.Get().set_check_on_null_data(true);
467 // Initialize |child_process_activity_time_| to a reasonable value.
468 mark_child_process_activity_time();
470 if (!GetBrowserContext()->IsOffTheRecord() &&
471 !base::CommandLine::ForCurrentProcess()->HasSwitch(
472 switches::kDisableGpuShaderDiskCache)) {
473 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
474 base::Bind(&CacheShaderInfo, GetID(),
475 storage_partition_impl_->GetPath()));
478 // Note: When we create the RenderProcessHostImpl, it's technically
479 // backgrounded, because it has no visible listeners. But the process
480 // doesn't actually exist yet, so we'll Background it later, after
481 // creation.
484 // static
485 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
486 DCHECK(g_run_renderer_in_process_);
488 switch (g_all_hosts.Pointer()->size()) {
489 case 0:
490 return;
491 case 1: {
492 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
493 AllHostsIterator().GetCurrentValue());
494 FOR_EACH_OBSERVER(RenderProcessHostObserver,
495 host->observers_,
496 RenderProcessHostDestroyed(host));
497 #ifndef NDEBUG
498 host->is_self_deleted_ = true;
499 #endif
500 delete host;
501 return;
503 default:
504 NOTREACHED() << "There should be only one RenderProcessHost when running "
505 << "in-process.";
509 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
510 RendererMainThreadFactoryFunction create) {
511 g_renderer_main_thread_factory = create;
514 RenderProcessHostImpl::~RenderProcessHostImpl() {
515 #ifndef NDEBUG
516 DCHECK(is_self_deleted_)
517 << "RenderProcessHostImpl is destroyed by something other than itself";
518 #endif
520 // Make sure to clean up the in-process renderer before the channel, otherwise
521 // it may still run and have its IPCs fail, causing asserts.
522 in_process_renderer_.reset();
524 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
526 if (gpu_observer_registered_) {
527 GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
528 gpu_observer_registered_ = false;
531 // We may have some unsent messages at this point, but that's OK.
532 channel_.reset();
533 while (!queued_messages_.empty()) {
534 delete queued_messages_.front();
535 queued_messages_.pop();
538 UnregisterHost(GetID());
540 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
541 switches::kDisableGpuShaderDiskCache)) {
542 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
543 base::Bind(&RemoveShaderInfo, GetID()));
547 void RenderProcessHostImpl::EnableSendQueue() {
548 is_initialized_ = false;
551 bool RenderProcessHostImpl::Init() {
552 // calling Init() more than once does nothing, this makes it more convenient
553 // for the view host which may not be sure in some cases
554 if (channel_)
555 return true;
557 base::CommandLine::StringType renderer_prefix;
558 #if defined(OS_POSIX)
559 // A command prefix is something prepended to the command line of the spawned
560 // process. It is supported only on POSIX systems.
561 const base::CommandLine& browser_command_line =
562 *base::CommandLine::ForCurrentProcess();
563 renderer_prefix =
564 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
565 #endif // defined(OS_POSIX)
567 #if defined(OS_LINUX)
568 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
569 ChildProcessHost::CHILD_NORMAL;
570 #else
571 int flags = ChildProcessHost::CHILD_NORMAL;
572 #endif
574 // Find the renderer before creating the channel so if this fails early we
575 // return without creating the channel.
576 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
577 if (renderer_path.empty())
578 return false;
580 // Setup the IPC channel.
581 const std::string channel_id =
582 IPC::Channel::GenerateVerifiedChannelID(std::string());
583 channel_ = CreateChannelProxy(channel_id);
585 // Setup the Mojo channel.
586 mojo_application_host_->Init();
588 // Call the embedder first so that their IPC filters have priority.
589 GetContentClient()->browser()->RenderProcessWillLaunch(this);
591 CreateMessageFilters();
593 if (run_renderer_in_process()) {
594 DCHECK(g_renderer_main_thread_factory);
595 // Crank up a thread and run the initialization there. With the way that
596 // messages flow between the browser and renderer, this thread is required
597 // to prevent a deadlock in single-process mode. Since the primordial
598 // thread in the renderer process runs the WebKit code and can sometimes
599 // make blocking calls to the UI thread (i.e. this thread), they need to run
600 // on separate threads.
601 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
603 base::Thread::Options options;
604 #if defined(OS_WIN) && !defined(OS_MACOSX)
605 // In-process plugins require this to be a UI message loop.
606 options.message_loop_type = base::MessageLoop::TYPE_UI;
607 #else
608 // We can't have multiple UI loops on Linux and Android, so we don't support
609 // in-process plugins.
610 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
611 #endif
612 in_process_renderer_->StartWithOptions(options);
614 g_in_process_thread = in_process_renderer_->message_loop();
616 OnProcessLaunched(); // Fake a callback that the process is ready.
617 } else {
618 // Build command line for renderer. We call AppendRendererCommandLine()
619 // first so the process type argument will appear first.
620 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
621 if (!renderer_prefix.empty())
622 cmd_line->PrependWrapper(renderer_prefix);
623 AppendRendererCommandLine(cmd_line);
624 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
626 // Spawn the child process asynchronously to avoid blocking the UI thread.
627 // As long as there's no renderer prefix, we can use the zygote process
628 // at this stage.
629 child_process_launcher_.reset(new ChildProcessLauncher(
630 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
631 cmd_line,
632 GetID(),
633 this));
635 fast_shutdown_started_ = false;
638 if (!gpu_observer_registered_) {
639 gpu_observer_registered_ = true;
640 GpuDataManagerImpl::GetInstance()->AddObserver(this);
643 power_monitor_broadcaster_.Init();
645 is_initialized_ = true;
646 return true;
649 void RenderProcessHostImpl::MaybeActivateMojo() {
650 // TODO(darin): Following security review, we can unconditionally initialize
651 // Mojo in all renderers. We will then be able to directly call Activate()
652 // from OnProcessLaunched.
653 if (!mojo_activation_required_)
654 return; // Waiting on someone to require Mojo.
656 if (!GetHandle())
657 return; // Waiting on renderer startup.
659 if (!mojo_application_host_->did_activate())
660 mojo_application_host_->Activate(this, GetHandle());
663 bool RenderProcessHostImpl::ShouldUseMojoChannel() const {
664 const base::CommandLine& command_line =
665 *base::CommandLine::ForCurrentProcess();
666 return command_line.HasSwitch(switches::kEnableRendererMojoChannel);
669 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
670 const std::string& channel_id) {
671 scoped_refptr<base::SingleThreadTaskRunner> runner =
672 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
673 if (ShouldUseMojoChannel()) {
674 VLOG(1) << "Mojo Channel is enabled on host";
675 if (!channel_mojo_host_) {
676 channel_mojo_host_.reset(new IPC::ChannelMojoHost(
677 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
680 return IPC::ChannelProxy::Create(
681 IPC::ChannelMojo::CreateServerFactory(
682 channel_mojo_host_->channel_delegate(), channel_id),
683 this,
684 runner.get());
687 return IPC::ChannelProxy::Create(
688 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
691 void RenderProcessHostImpl::CreateMessageFilters() {
692 DCHECK_CURRENTLY_ON(BrowserThread::UI);
693 AddFilter(new ResourceSchedulerFilter(GetID()));
694 MediaInternals* media_internals = MediaInternals::GetInstance();
695 media::AudioManager* audio_manager =
696 BrowserMainLoop::GetInstance()->audio_manager();
697 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
698 // from guests.
699 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
700 new BrowserPluginMessageFilter(GetID()));
701 AddFilter(bp_message_filter.get());
703 scoped_refptr<RenderMessageFilter> render_message_filter(
704 new RenderMessageFilter(
705 GetID(),
706 #if defined(ENABLE_PLUGINS)
707 PluginServiceImpl::GetInstance(),
708 #else
709 NULL,
710 #endif
711 GetBrowserContext(),
712 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
713 widget_helper_.get(),
714 audio_manager,
715 media_internals,
716 storage_partition_impl_->GetDOMStorageContext()));
717 AddFilter(render_message_filter.get());
718 AddFilter(
719 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
720 BrowserContext* browser_context = GetBrowserContext();
721 ResourceContext* resource_context = browser_context->GetResourceContext();
723 scoped_refptr<net::URLRequestContextGetter> request_context(
724 browser_context->GetRequestContextForRenderProcess(GetID()));
725 scoped_refptr<net::URLRequestContextGetter> media_request_context(
726 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
728 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
729 base::Bind(&GetContexts, browser_context->GetResourceContext(),
730 request_context, media_request_context));
732 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
733 GetID(), PROCESS_TYPE_RENDERER,
734 storage_partition_impl_->GetAppCacheService(),
735 ChromeBlobStorageContext::GetFor(browser_context),
736 storage_partition_impl_->GetFileSystemContext(),
737 storage_partition_impl_->GetServiceWorkerContext(),
738 get_contexts_callback);
740 AddFilter(resource_message_filter);
741 MediaStreamManager* media_stream_manager =
742 BrowserMainLoop::GetInstance()->media_stream_manager();
743 AddFilter(new AudioInputRendererHost(
744 audio_manager,
745 media_stream_manager,
746 AudioMirroringManager::GetInstance(),
747 BrowserMainLoop::GetInstance()->user_input_monitor()));
748 // The AudioRendererHost needs to be available for lookup, so it's
749 // stashed in a member variable.
750 audio_renderer_host_ = new AudioRendererHost(
751 GetID(),
752 audio_manager,
753 AudioMirroringManager::GetInstance(),
754 media_internals,
755 media_stream_manager);
756 AddFilter(audio_renderer_host_.get());
757 AddFilter(
758 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
759 AddFilter(new VideoCaptureHost(media_stream_manager));
760 AddFilter(new AppCacheDispatcherHost(
761 storage_partition_impl_->GetAppCacheService(),
762 GetID()));
763 AddFilter(new ClipboardMessageFilter);
764 AddFilter(new DOMStorageMessageFilter(
765 GetID(),
766 storage_partition_impl_->GetDOMStorageContext()));
767 AddFilter(new IndexedDBDispatcherHost(
768 GetID(),
769 storage_partition_impl_->GetURLRequestContext(),
770 storage_partition_impl_->GetIndexedDBContext(),
771 ChromeBlobStorageContext::GetFor(browser_context)));
773 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
774 AddFilter(gpu_message_filter_);
775 #if defined(ENABLE_WEBRTC)
776 AddFilter(new WebRTCIdentityServiceHost(
777 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
778 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
779 AddFilter(peer_connection_tracker_host_.get());
780 AddFilter(new MediaStreamDispatcherHost(
781 GetID(),
782 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
783 media_stream_manager));
784 AddFilter(new DeviceRequestMessageFilter(
785 resource_context, media_stream_manager, GetID()));
786 AddFilter(new MediaStreamTrackMetricsHost());
787 #endif
788 #if defined(ENABLE_PLUGINS)
789 AddFilter(new PepperRendererConnection(GetID()));
790 #endif
791 AddFilter(new SpeechRecognitionDispatcherHost(
792 GetID(), storage_partition_impl_->GetURLRequestContext()));
793 AddFilter(new FileAPIMessageFilter(
794 GetID(),
795 storage_partition_impl_->GetURLRequestContext(),
796 storage_partition_impl_->GetFileSystemContext(),
797 ChromeBlobStorageContext::GetFor(browser_context),
798 StreamContext::GetFor(browser_context)));
799 AddFilter(new FileUtilitiesMessageFilter(GetID()));
800 AddFilter(new MimeRegistryMessageFilter());
801 AddFilter(new DatabaseMessageFilter(
802 storage_partition_impl_->GetDatabaseTracker()));
803 #if defined(OS_MACOSX)
804 AddFilter(new TextInputClientMessageFilter(GetID()));
805 #elif defined(OS_WIN)
806 // The FontCacheDispatcher is required only when we're using GDI rendering.
807 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
808 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
809 // should eventually be if (!ShouldUseDirectWrite()) guarded.
810 channel_->AddFilter(new FontCacheDispatcher());
811 #elif defined(OS_ANDROID)
812 browser_demuxer_android_ = new BrowserDemuxerAndroid();
813 AddFilter(browser_demuxer_android_);
814 #endif
815 #if defined(ENABLE_BROWSER_CDMS)
816 browser_cdm_manager_ = new BrowserCdmManager(GetID(), NULL);
817 AddFilter(browser_cdm_manager_);
818 #endif
820 SocketStreamDispatcherHost::GetRequestContextCallback
821 request_context_callback(
822 base::Bind(&GetRequestContext, request_context,
823 media_request_context));
825 SocketStreamDispatcherHost* socket_stream_dispatcher_host =
826 new SocketStreamDispatcherHost(
827 GetID(), request_context_callback, resource_context);
828 AddFilter(socket_stream_dispatcher_host);
830 WebSocketDispatcherHost::GetRequestContextCallback
831 websocket_request_context_callback(
832 base::Bind(&GetRequestContext, request_context,
833 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
835 AddFilter(
836 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
838 message_port_message_filter_ = new MessagePortMessageFilter(
839 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
840 base::Unretained(widget_helper_.get())));
841 AddFilter(message_port_message_filter_.get());
843 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
844 new ServiceWorkerDispatcherHost(GetID(),
845 message_port_message_filter_.get());
846 service_worker_filter->Init(
847 storage_partition_impl_->GetServiceWorkerContext());
848 AddFilter(service_worker_filter.get());
850 AddFilter(new SharedWorkerMessageFilter(
851 GetID(),
852 resource_context,
853 WorkerStoragePartition(
854 storage_partition_impl_->GetURLRequestContext(),
855 storage_partition_impl_->GetMediaURLRequestContext(),
856 storage_partition_impl_->GetAppCacheService(),
857 storage_partition_impl_->GetQuotaManager(),
858 storage_partition_impl_->GetFileSystemContext(),
859 storage_partition_impl_->GetDatabaseTracker(),
860 storage_partition_impl_->GetIndexedDBContext(),
861 storage_partition_impl_->GetServiceWorkerContext()),
862 message_port_message_filter_.get()));
864 #if defined(ENABLE_WEBRTC)
865 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
866 resource_context,
867 browser_context->GetRequestContextForRenderProcess(GetID()));
868 AddFilter(p2p_socket_dispatcher_host_.get());
869 #endif
871 AddFilter(new TraceMessageFilter());
872 AddFilter(new ResolveProxyMsgHelper(
873 browser_context->GetRequestContextForRenderProcess(GetID())));
874 AddFilter(new QuotaDispatcherHost(
875 GetID(),
876 storage_partition_impl_->GetQuotaManager(),
877 GetContentClient()->browser()->CreateQuotaPermissionContext()));
878 AddFilter(new GamepadBrowserMessageFilter());
879 AddFilter(new DeviceLightMessageFilter());
880 AddFilter(new DeviceMotionMessageFilter());
881 AddFilter(new DeviceOrientationMessageFilter());
882 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
883 AddFilter(new HistogramMessageFilter());
884 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
885 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
886 switches::kEnableMemoryBenchmarking))
887 AddFilter(new MemoryBenchmarkMessageFilter());
888 #endif
889 AddFilter(new VibrationMessageFilter());
890 AddFilter(new PushMessagingMessageFilter(
891 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
892 AddFilter(new BatteryStatusMessageFilter());
893 #if defined(OS_ANDROID)
894 AddFilter(new ScreenOrientationMessageFilterAndroid());
895 #endif
896 AddFilter(new GeofencingDispatcherHost());
899 int RenderProcessHostImpl::GetNextRoutingID() {
900 return widget_helper_->GetNextRoutingID();
904 void RenderProcessHostImpl::ResumeDeferredNavigation(
905 const GlobalRequestID& request_id) {
906 widget_helper_->ResumeDeferredNavigation(request_id);
909 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
910 const GlobalRequestID& request_id) {
911 widget_helper_->ResumeResponseDeferredAtStart(request_id);
914 void RenderProcessHostImpl::NotifyTimezoneChange() {
915 Send(new ViewMsg_TimezoneChange());
918 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
919 DCHECK(mojo_application_host_);
920 return mojo_application_host_->service_registry();
923 void RenderProcessHostImpl::AddRoute(
924 int32 routing_id,
925 IPC::Listener* listener) {
926 listeners_.AddWithID(listener, routing_id);
929 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
930 DCHECK(listeners_.Lookup(routing_id) != NULL);
931 listeners_.Remove(routing_id);
933 #if defined(OS_WIN)
934 // Dump the handle table if handle auditing is enabled.
935 const base::CommandLine& browser_command_line =
936 *base::CommandLine::ForCurrentProcess();
937 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
938 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
939 DumpHandles();
941 // We wait to close the channels until the child process has finished
942 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
943 return;
945 #endif
946 // Keep the one renderer thread around forever in single process mode.
947 if (!run_renderer_in_process())
948 Cleanup();
951 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
952 observers_.AddObserver(observer);
955 void RenderProcessHostImpl::RemoveObserver(
956 RenderProcessHostObserver* observer) {
957 observers_.RemoveObserver(observer);
960 void RenderProcessHostImpl::ReceivedBadMessage() {
961 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
962 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
963 return;
965 if (run_renderer_in_process()) {
966 // In single process mode it is better if we don't suicide but just
967 // crash.
968 CHECK(false);
970 // We kill the renderer but don't include a NOTREACHED, because we want the
971 // browser to try to survive when it gets illegal messages from the renderer.
972 base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
973 false);
976 void RenderProcessHostImpl::WidgetRestored() {
977 // Verify we were properly backgrounded.
978 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
979 visible_widgets_++;
980 SetBackgrounded(false);
983 void RenderProcessHostImpl::WidgetHidden() {
984 // On startup, the browser will call Hide
985 if (backgrounded_)
986 return;
988 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
989 visible_widgets_--;
990 DCHECK_GE(visible_widgets_, 0);
991 if (visible_widgets_ == 0) {
992 DCHECK(!backgrounded_);
993 SetBackgrounded(true);
997 int RenderProcessHostImpl::VisibleWidgetCount() const {
998 return visible_widgets_;
1001 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1002 return is_isolated_guest_;
1005 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1006 return storage_partition_impl_;
1009 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1010 if (IsPinchVirtualViewportEnabled())
1011 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
1013 if (IsDelegatedRendererEnabled())
1014 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1016 if (IsImplSidePaintingEnabled()) {
1017 command_line->AppendSwitch(switches::kEnableImplSidePainting);
1018 command_line->AppendSwitchASCII(
1019 switches::kNumRasterThreads,
1020 base::IntToString(NumberOfRendererRasterThreads()));
1023 if (IsGpuRasterizationEnabled())
1024 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1026 if (IsForceGpuRasterizationEnabled())
1027 command_line->AppendSwitch(switches::kForceGpuRasterization);
1029 // Appending disable-gpu-feature switches due to software rendering list.
1030 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1031 DCHECK(gpu_data_manager);
1032 gpu_data_manager->AppendRendererCommandLine(command_line);
1035 void RenderProcessHostImpl::AppendRendererCommandLine(
1036 base::CommandLine* command_line) const {
1037 // Pass the process type first, so it shows first in process listings.
1038 command_line->AppendSwitchASCII(switches::kProcessType,
1039 switches::kRendererProcess);
1041 // Now send any options from our own command line we want to propagate.
1042 const base::CommandLine& browser_command_line =
1043 *base::CommandLine::ForCurrentProcess();
1044 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1046 // Pass on the browser locale.
1047 const std::string locale =
1048 GetContentClient()->browser()->GetApplicationLocale();
1049 command_line->AppendSwitchASCII(switches::kLang, locale);
1051 // If we run base::FieldTrials, we want to pass to their state to the
1052 // renderer so that it can act in accordance with each state, or record
1053 // histograms relating to the base::FieldTrial states.
1054 std::string field_trial_states;
1055 base::FieldTrialList::StatesToString(&field_trial_states);
1056 if (!field_trial_states.empty()) {
1057 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1058 field_trial_states);
1061 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1062 command_line, GetID());
1064 if (IsPinchToZoomEnabled())
1065 command_line->AppendSwitch(switches::kEnablePinch);
1067 #if defined(OS_WIN)
1068 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1069 base::DoubleToString(gfx::GetDPIScale()));
1070 #endif
1072 AppendCompositorCommandLineFlags(command_line);
1075 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1076 const base::CommandLine& browser_cmd,
1077 base::CommandLine* renderer_cmd) const {
1078 // Propagate the following switches to the renderer command line (along
1079 // with any associated values) if present in the browser command line.
1080 static const char* const kSwitchNames[] = {
1081 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1082 switches::kAllowLoopbackInPeerConnection,
1083 switches::kAudioBufferSize,
1084 switches::kAuditAllHandles,
1085 switches::kAuditHandles,
1086 switches::kBlinkPlatformLogChannels,
1087 switches::kBlockCrossSiteDocuments,
1088 switches::kDefaultTileWidth,
1089 switches::kDefaultTileHeight,
1090 switches::kDisable3DAPIs,
1091 switches::kDisableAcceleratedVideoDecode,
1092 switches::kDisableApplicationCache,
1093 switches::kDisableBlinkScheduler,
1094 switches::kDisableBreakpad,
1095 switches::kDisablePreferCompositingToLCDText,
1096 switches::kDisableCompositingForTransition,
1097 switches::kDisableDatabases,
1098 switches::kDisableDesktopNotifications,
1099 switches::kDisableDirectNPAPIRequests,
1100 switches::kDisableDisplayList2dCanvas,
1101 switches::kDisableDistanceFieldText,
1102 switches::kDisableFileSystem,
1103 switches::kDisableGpuCompositing,
1104 switches::kDisableGpuVsync,
1105 switches::kDisableLowResTiling,
1106 switches::kDisableHistogramCustomizer,
1107 switches::kDisableLCDText,
1108 switches::kDisableLayerSquashing,
1109 switches::kDisableLocalStorage,
1110 switches::kDisableLogging,
1111 switches::kDisableMediaSource,
1112 switches::kDisableOverlayScrollbar,
1113 switches::kDisablePinch,
1114 switches::kDisablePrefixedEncryptedMedia,
1115 switches::kDisableSeccompFilterSandbox,
1116 switches::kDisableSessionStorage,
1117 switches::kDisableSharedWorkers,
1118 switches::kDisableThreadedCompositing,
1119 switches::kDisableThreadedScrolling,
1120 switches::kDisableTouchAdjustment,
1121 switches::kDisableTouchDragDrop,
1122 switches::kDisableTouchEditing,
1123 switches::kDisableV8IdleNotificationAfterCommit,
1124 switches::kDisableZeroCopy,
1125 switches::kDomAutomationController,
1126 switches::kEnableBeginFrameScheduling,
1127 switches::kEnableBleedingEdgeRenderingFastPaths,
1128 switches::kEnablePreferCompositingToLCDText,
1129 switches::kEnableCompositingForTransition,
1130 switches::kEnableCredentialManagerAPI,
1131 switches::kEnableDeferredImageDecoding,
1132 switches::kEnableDisplayList2dCanvas,
1133 switches::kEnableDistanceFieldText,
1134 switches::kEnableEncryptedMedia,
1135 switches::kEnableExperimentalCanvasFeatures,
1136 switches::kEnableExperimentalWebPlatformFeatures,
1137 switches::kEnableGPUClientLogging,
1138 switches::kEnableGpuClientTracing,
1139 switches::kEnableGPUServiceLogging,
1140 switches::kEnableLowResTiling,
1141 switches::kEnableInbandTextTracks,
1142 switches::kEnableLCDText,
1143 switches::kEnableLayerSquashing,
1144 switches::kEnableLogging,
1145 switches::kEnableMemoryBenchmarking,
1146 switches::kEnableNetworkInformation,
1147 switches::kEnableOneCopy,
1148 switches::kEnableOverlayFullscreenVideo,
1149 switches::kEnableOverlayScrollbar,
1150 switches::kEnableOverscrollNotifications,
1151 switches::kEnablePinch,
1152 switches::kEnablePluginPowerSaver,
1153 switches::kEnablePreciseMemoryInfo,
1154 switches::kEnableRendererMojoChannel,
1155 switches::kEnableSeccompFilterSandbox,
1156 switches::kEnableSkiaBenchmarking,
1157 switches::kEnableSmoothScrolling,
1158 switches::kEnableStatsTable,
1159 switches::kEnableStrictSiteIsolation,
1160 switches::kEnableThreadedCompositing,
1161 switches::kEnableTouchDragDrop,
1162 switches::kEnableTouchEditing,
1163 switches::kEnableV8IdleNotificationAfterCommit,
1164 switches::kEnableViewport,
1165 switches::kEnableViewportMeta,
1166 switches::kEnableVtune,
1167 switches::kEnableWebGLDraftExtensions,
1168 switches::kEnableWebGLImageChromium,
1169 switches::kEnableWebMIDI,
1170 switches::kEnableZeroCopy,
1171 switches::kForceDeviceScaleFactor,
1172 switches::kFullMemoryCrashReport,
1173 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
1174 switches::kIPCConnectionTimeout,
1175 switches::kJavaScriptFlags,
1176 switches::kLoggingLevel,
1177 switches::kMainFrameResizesAreOrientationChanges,
1178 switches::kMaxUntiledLayerWidth,
1179 switches::kMaxUntiledLayerHeight,
1180 switches::kMemoryMetrics,
1181 switches::kNoReferrers,
1182 switches::kNoSandbox,
1183 switches::kPpapiInProcess,
1184 switches::kProfilerTiming,
1185 switches::kReduceSecurityForTesting,
1186 switches::kRegisterPepperPlugins,
1187 switches::kRendererAssertTest,
1188 switches::kRendererStartupDialog,
1189 switches::kShowPaintRects,
1190 switches::kSitePerProcess,
1191 switches::kStatsCollectionController,
1192 switches::kTestType,
1193 switches::kTouchEvents,
1194 switches::kTraceToConsole,
1195 switches::kUseDiscardableMemory,
1196 // This flag needs to be propagated to the renderer process for
1197 // --in-process-webgl.
1198 switches::kUseGL,
1199 switches::kUseMobileUserAgent,
1200 switches::kV,
1201 switches::kVideoThreads,
1202 switches::kVModule,
1203 // Please keep these in alphabetical order. Compositor switches here should
1204 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1205 cc::switches::kCompositeToMailbox,
1206 cc::switches::kDisableCompositedAntialiasing,
1207 cc::switches::kDisableMainFrameBeforeActivation,
1208 cc::switches::kDisableThreadedAnimation,
1209 cc::switches::kEnableGpuBenchmarking,
1210 cc::switches::kEnableMainFrameBeforeActivation,
1211 cc::switches::kEnableTopControlsPositionCalculation,
1212 cc::switches::kMaxTilesForInterestArea,
1213 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1214 cc::switches::kShowCompositedLayerBorders,
1215 cc::switches::kShowFPSCounter,
1216 cc::switches::kShowLayerAnimationBounds,
1217 cc::switches::kShowNonOccludingRects,
1218 cc::switches::kShowOccludingRects,
1219 cc::switches::kShowPropertyChangedRects,
1220 cc::switches::kShowReplicaScreenSpaceRects,
1221 cc::switches::kShowScreenSpaceRects,
1222 cc::switches::kShowSurfaceDamageRects,
1223 cc::switches::kSlowDownRasterScaleFactor,
1224 cc::switches::kStrictLayerPropertyChangeChecking,
1225 cc::switches::kTopControlsHeight,
1226 cc::switches::kTopControlsHideThreshold,
1227 cc::switches::kTopControlsShowThreshold,
1228 #if defined(ENABLE_PLUGINS)
1229 switches::kEnablePepperTesting,
1230 #endif
1231 #if defined(ENABLE_WEBRTC)
1232 switches::kDisableAudioTrackProcessing,
1233 switches::kDisableWebRtcHWDecoding,
1234 switches::kDisableWebRtcHWEncoding,
1235 switches::kEnableWebRtcHWVp8Encoding,
1236 switches::kEnableWebRtcHWH264Encoding,
1237 #endif
1238 switches::kLowEndDeviceMode,
1239 #if defined(OS_ANDROID)
1240 switches::kDisableGestureRequirementForMediaPlayback,
1241 switches::kDisableWebRTC,
1242 switches::kEnableSpeechRecognition,
1243 switches::kMediaDrmEnableNonCompositing,
1244 switches::kNetworkCountryIso,
1245 switches::kDisableWebAudio,
1246 switches::kRendererWaitForJavaDebugger,
1247 #endif
1248 #if defined(OS_MACOSX)
1249 // Allow this to be set when invoking the browser and relayed along.
1250 switches::kEnableSandboxLogging,
1251 #endif
1252 #if defined(OS_WIN)
1253 switches::kDisableDirectWrite,
1254 #endif
1255 #if defined(OS_CHROMEOS)
1256 switches::kDisableVaapiAcceleratedVideoEncode,
1257 #endif
1259 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1260 arraysize(kSwitchNames));
1262 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1263 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1264 // Pass kTraceStartup switch to renderer only if startup tracing has not
1265 // finished.
1266 renderer_cmd->AppendSwitchASCII(
1267 switches::kTraceStartup,
1268 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1271 // Disable databases in incognito mode.
1272 if (GetBrowserContext()->IsOffTheRecord() &&
1273 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1274 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1277 // Enforce the extra command line flags for impl-side painting.
1278 if (IsImplSidePaintingEnabled() &&
1279 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1280 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1282 // Add kWaitForDebugger to let renderer process wait for a debugger.
1283 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1284 // Look to pass-on the kWaitForDebugger flag.
1285 std::string value =
1286 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1287 if (value.empty() || value == switches::kRendererProcess) {
1288 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1293 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1294 if (run_renderer_in_process())
1295 return base::Process::Current().handle();
1297 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1298 return base::kNullProcessHandle;
1300 return child_process_launcher_->GetHandle();
1303 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1304 if (run_renderer_in_process())
1305 return false; // Single process mode never shutdown the renderer.
1307 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1308 return false;
1310 if (!child_process_launcher_.get() ||
1311 child_process_launcher_->IsStarting() ||
1312 !GetHandle())
1313 return false; // Render process hasn't started or is probably crashed.
1315 // Test if there's an unload listener.
1316 // NOTE: It's possible that an onunload listener may be installed
1317 // while we're shutting down, so there's a small race here. Given that
1318 // the window is small, it's unlikely that the web page has much
1319 // state that will be lost by not calling its unload handlers properly.
1320 if (!SuddenTerminationAllowed())
1321 return false;
1323 if (worker_ref_count_ != 0) {
1324 if (survive_for_worker_start_time_.is_null())
1325 survive_for_worker_start_time_ = base::TimeTicks::Now();
1326 return false;
1329 // Set this before ProcessDied() so observers can tell if the render process
1330 // died due to fast shutdown versus another cause.
1331 fast_shutdown_started_ = true;
1333 ProcessDied(false /* already_dead */);
1334 return true;
1337 void RenderProcessHostImpl::DumpHandles() {
1338 #if defined(OS_WIN)
1339 Send(new ChildProcessMsg_DumpHandles());
1340 #else
1341 NOTIMPLEMENTED();
1342 #endif
1345 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1346 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1347 if (!channel_) {
1348 if (!is_initialized_) {
1349 queued_messages_.push(msg);
1350 return true;
1351 } else {
1352 delete msg;
1353 return false;
1357 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1358 queued_messages_.push(msg);
1359 return true;
1362 return channel_->Send(msg);
1365 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1366 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1367 // we ignore incoming messages.
1369 if (deleting_soon_ || fast_shutdown_started_)
1370 return false;
1372 mark_child_process_activity_time();
1373 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1374 // Dispatch control messages.
1375 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1376 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1377 OnShutdownRequest)
1378 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1379 OnDumpHandlesDone)
1380 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1381 SuddenTerminationChanged)
1382 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1383 OnUserMetricsRecordAction)
1384 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1385 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1386 #if defined(ENABLE_WEBRTC)
1387 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1388 OnRegisterAecDumpConsumer)
1389 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1390 OnUnregisterAecDumpConsumer)
1391 #endif
1392 // Adding single handlers for your service here is fine, but once your
1393 // service needs more than one handler, please extract them into a new
1394 // message filter and add that filter to CreateMessageFilters().
1395 IPC_END_MESSAGE_MAP()
1397 return true;
1400 // Dispatch incoming messages to the appropriate IPC::Listener.
1401 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1402 if (!listener) {
1403 if (msg.is_sync()) {
1404 // The listener has gone away, so we must respond or else the caller will
1405 // hang waiting for a reply.
1406 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1407 reply->set_reply_error();
1408 Send(reply);
1410 return true;
1412 return listener->OnMessageReceived(msg);
1415 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1416 #if defined(IPC_MESSAGE_LOG_ENABLED)
1417 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1418 IPC::Logging::GetInstance()->Enabled()));
1419 #endif
1421 tracked_objects::ThreadData::Status status =
1422 tracked_objects::ThreadData::status();
1423 Send(new ChildProcessMsg_SetProfilerStatus(status));
1426 void RenderProcessHostImpl::OnChannelError() {
1427 ProcessDied(true /* already_dead */);
1430 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1431 // Message de-serialization failed. We consider this a capital crime. Kill the
1432 // renderer if we have one.
1433 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1434 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1435 PROCESS_TYPE_RENDERER);
1436 ReceivedBadMessage();
1439 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1440 return browser_context_;
1443 bool RenderProcessHostImpl::InSameStoragePartition(
1444 StoragePartition* partition) const {
1445 return storage_partition_impl_ == partition;
1448 int RenderProcessHostImpl::GetID() const {
1449 return id_;
1452 bool RenderProcessHostImpl::HasConnection() const {
1453 return channel_.get() != NULL;
1456 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1457 ignore_input_events_ = ignore_input_events;
1460 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1461 return ignore_input_events_;
1464 void RenderProcessHostImpl::Cleanup() {
1465 // If within_process_died_observer_ is true, one of our observers performed an
1466 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1467 // delay the destruction until all of the observer callbacks have been made,
1468 // and guarantee that the RenderProcessHostDestroyed observer callback is
1469 // always the last callback fired.
1470 if (within_process_died_observer_) {
1471 delayed_cleanup_needed_ = true;
1472 return;
1474 delayed_cleanup_needed_ = false;
1476 // Records the time when the process starts surviving for workers for UMA.
1477 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1478 survive_for_worker_start_time_.is_null()) {
1479 survive_for_worker_start_time_ = base::TimeTicks::Now();
1482 // When there are no other owners of this object, we can delete ourselves.
1483 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1484 if (!survive_for_worker_start_time_.is_null()) {
1485 UMA_HISTOGRAM_LONG_TIMES(
1486 "SharedWorker.RendererSurviveForWorkerTime",
1487 base::TimeTicks::Now() - survive_for_worker_start_time_);
1489 // We cannot clean up twice; if this fails, there is an issue with our
1490 // control flow.
1491 DCHECK(!deleting_soon_);
1493 DCHECK_EQ(0, pending_views_);
1494 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1495 observers_,
1496 RenderProcessHostDestroyed(this));
1497 NotificationService::current()->Notify(
1498 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1499 Source<RenderProcessHost>(this),
1500 NotificationService::NoDetails());
1502 #ifndef NDEBUG
1503 is_self_deleted_ = true;
1504 #endif
1505 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1506 deleting_soon_ = true;
1507 // It's important not to wait for the DeleteTask to delete the channel
1508 // proxy. Kill it off now. That way, in case the profile is going away, the
1509 // rest of the objects attached to this RenderProcessHost start going
1510 // away first, since deleting the channel proxy will post a
1511 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1512 channel_.reset();
1513 gpu_message_filter_ = NULL;
1514 message_port_message_filter_ = NULL;
1515 RemoveUserData(kSessionStorageHolderKey);
1517 // Remove ourself from the list of renderer processes so that we can't be
1518 // reused in between now and when the Delete task runs.
1519 UnregisterHost(GetID());
1523 void RenderProcessHostImpl::AddPendingView() {
1524 pending_views_++;
1527 void RenderProcessHostImpl::RemovePendingView() {
1528 DCHECK(pending_views_);
1529 pending_views_--;
1532 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1533 sudden_termination_allowed_ = enabled;
1536 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1537 return sudden_termination_allowed_;
1540 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1541 return base::TimeTicks::Now() - child_process_activity_time_;
1544 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1545 widget_helper_->ResumeRequestsForView(route_id);
1548 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1549 FilterURL(this, empty_allowed, url);
1552 #if defined(ENABLE_WEBRTC)
1553 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1554 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1555 // Enable AEC dump for each registered consumer.
1556 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1557 it != aec_dump_consumers_.end(); ++it) {
1558 EnableAecDumpForId(file, *it);
1562 void RenderProcessHostImpl::DisableAecDump() {
1563 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1564 // Posting on the FILE thread and then replying back on the UI thread is only
1565 // for avoiding races between enable and disable. Nothing is done on the FILE
1566 // thread.
1567 BrowserThread::PostTaskAndReply(
1568 BrowserThread::FILE, FROM_HERE,
1569 base::Bind(&DisableAecDumpOnFileThread),
1570 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1571 weak_factory_.GetWeakPtr()));
1574 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1575 base::Callback<void(const std::string&)> callback) {
1576 webrtc_log_message_callback_ = callback;
1579 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1580 RenderProcessHostImpl::StartRtpDump(
1581 bool incoming,
1582 bool outgoing,
1583 const WebRtcRtpPacketCallback& packet_callback) {
1584 if (!p2p_socket_dispatcher_host_.get())
1585 return WebRtcStopRtpDumpCallback();
1587 BrowserThread::PostTask(BrowserThread::IO,
1588 FROM_HERE,
1589 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1590 p2p_socket_dispatcher_host_,
1591 incoming,
1592 outgoing,
1593 packet_callback));
1595 if (stop_rtp_dump_callback_.is_null()) {
1596 stop_rtp_dump_callback_ =
1597 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1598 p2p_socket_dispatcher_host_);
1600 return stop_rtp_dump_callback_;
1602 #endif
1604 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1605 return channel_.get();
1608 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1609 channel_->AddFilter(filter->GetFilter());
1612 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1613 if (static_cast<size_t>(GetActiveViewCount()) == count)
1614 return FastShutdownIfPossible();
1615 return false;
1618 bool RenderProcessHostImpl::FastShutdownStarted() const {
1619 return fast_shutdown_started_;
1622 // static
1623 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1624 g_all_hosts.Get().AddWithID(host, host_id);
1627 // static
1628 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1629 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1630 if (!host)
1631 return;
1633 g_all_hosts.Get().Remove(host_id);
1635 // Look up the map of site to process for the given browser_context,
1636 // in case we need to remove this process from it. It will be registered
1637 // under any sites it rendered that use process-per-site mode.
1638 SiteProcessMap* map =
1639 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1640 map->RemoveProcess(host);
1643 // static
1644 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1645 bool empty_allowed,
1646 GURL* url) {
1647 ChildProcessSecurityPolicyImpl* policy =
1648 ChildProcessSecurityPolicyImpl::GetInstance();
1650 if (empty_allowed && url->is_empty())
1651 return;
1653 // The browser process should never hear the swappedout:// URL from any
1654 // of the renderer's messages. Check for this in debug builds, but don't
1655 // let it crash a release browser.
1656 DCHECK(GURL(kSwappedOutURL) != *url);
1658 if (!url->is_valid()) {
1659 // Have to use about:blank for the denied case, instead of an empty GURL.
1660 // This is because the browser treats navigation to an empty GURL as a
1661 // navigation to the home page. This is often a privileged page
1662 // (chrome://newtab/) which is exactly what we don't want.
1663 *url = GURL(url::kAboutBlankURL);
1664 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1665 return;
1668 if (url->SchemeIs(url::kAboutScheme)) {
1669 // The renderer treats all URLs in the about: scheme as being about:blank.
1670 // Canonicalize about: URLs to about:blank.
1671 *url = GURL(url::kAboutBlankURL);
1672 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1675 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1676 // cannot swap processes or grant bindings.
1677 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1678 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1680 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1681 // If this renderer is not permitted to request this URL, we invalidate the
1682 // URL. This prevents us from storing the blocked URL and becoming confused
1683 // later.
1684 VLOG(1) << "Blocked URL " << url->spec();
1685 *url = GURL(url::kAboutBlankURL);
1686 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1690 // static
1691 bool RenderProcessHostImpl::IsSuitableHost(
1692 RenderProcessHost* host,
1693 BrowserContext* browser_context,
1694 const GURL& site_url) {
1695 if (run_renderer_in_process())
1696 return true;
1698 if (host->GetBrowserContext() != browser_context)
1699 return false;
1701 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1702 // and non-guest storage gets mixed. In the future, we might consider enabling
1703 // the sharing of guests, in this case this check should be removed and
1704 // InSameStoragePartition should handle the possible sharing.
1705 if (host->IsIsolatedGuest())
1706 return false;
1708 // Check whether the given host and the intended site_url will be using the
1709 // same StoragePartition, since a RenderProcessHost can only support a single
1710 // StoragePartition. This is relevant for packaged apps and isolated sites.
1711 StoragePartition* dest_partition =
1712 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1713 if (!host->InSameStoragePartition(dest_partition))
1714 return false;
1716 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1717 host->GetID()) !=
1718 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1719 browser_context, site_url)) {
1720 return false;
1723 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1726 // static
1727 bool RenderProcessHost::run_renderer_in_process() {
1728 return g_run_renderer_in_process_;
1731 // static
1732 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1733 g_run_renderer_in_process_ = value;
1735 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1736 if (value) {
1737 if (!command_line->HasSwitch(switches::kLang)) {
1738 // Modify the current process' command line to include the browser locale,
1739 // as the renderer expects this flag to be set.
1740 const std::string locale =
1741 GetContentClient()->browser()->GetApplicationLocale();
1742 command_line->AppendSwitchASCII(switches::kLang, locale);
1744 // TODO(piman): we should really send configuration through bools rather
1745 // than by parsing strings, i.e. sending an IPC rather than command line
1746 // args. crbug.com/314909
1747 AppendCompositorCommandLineFlags(command_line);
1751 // static
1752 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1753 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1754 return iterator(g_all_hosts.Pointer());
1757 // static
1758 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1759 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1760 return g_all_hosts.Get().Lookup(render_process_id);
1763 // static
1764 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1765 BrowserContext* browser_context, const GURL& url) {
1766 // Experimental:
1767 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1768 // try to reuse renderer processes when over the limit. (We could allow pages
1769 // from the same site to share, if we knew what the given process was
1770 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1771 // resource exhaustion issues if too many sites are open at once.
1772 const base::CommandLine& command_line =
1773 *base::CommandLine::ForCurrentProcess();
1774 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1775 command_line.HasSwitch(switches::kSitePerProcess))
1776 return false;
1778 if (run_renderer_in_process())
1779 return true;
1781 // NOTE: Sometimes it's necessary to create more render processes than
1782 // GetMaxRendererProcessCount(), for instance when we want to create
1783 // a renderer process for a browser context that has no existing
1784 // renderers. This is OK in moderation, since the
1785 // GetMaxRendererProcessCount() is conservative.
1786 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1787 return true;
1789 return GetContentClient()->browser()->
1790 ShouldTryToUseExistingProcessHost(browser_context, url);
1793 // static
1794 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1795 BrowserContext* browser_context,
1796 const GURL& site_url) {
1797 // First figure out which existing renderers we can use.
1798 std::vector<RenderProcessHost*> suitable_renderers;
1799 suitable_renderers.reserve(g_all_hosts.Get().size());
1801 iterator iter(AllHostsIterator());
1802 while (!iter.IsAtEnd()) {
1803 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1804 RenderProcessHostImpl::IsSuitableHost(
1805 iter.GetCurrentValue(),
1806 browser_context, site_url)) {
1807 suitable_renderers.push_back(iter.GetCurrentValue());
1809 iter.Advance();
1812 // Now pick a random suitable renderer, if we have any.
1813 if (!suitable_renderers.empty()) {
1814 int suitable_count = static_cast<int>(suitable_renderers.size());
1815 int random_index = base::RandInt(0, suitable_count - 1);
1816 return suitable_renderers[random_index];
1819 return NULL;
1822 // static
1823 bool RenderProcessHost::ShouldUseProcessPerSite(
1824 BrowserContext* browser_context,
1825 const GURL& url) {
1826 // Returns true if we should use the process-per-site model. This will be
1827 // the case if the --process-per-site switch is specified, or in
1828 // process-per-site-instance for particular sites (e.g., WebUI).
1829 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1830 const base::CommandLine& command_line =
1831 *base::CommandLine::ForCurrentProcess();
1832 if (command_line.HasSwitch(switches::kProcessPerSite))
1833 return true;
1835 // We want to consolidate particular sites like WebUI even when we are using
1836 // the process-per-tab or process-per-site-instance models.
1837 // Note: DevTools pages have WebUI type but should not reuse the same host.
1838 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1839 browser_context, url) &&
1840 !url.SchemeIs(kChromeDevToolsScheme)) {
1841 return true;
1844 // Otherwise let the content client decide, defaulting to false.
1845 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1846 url);
1849 // static
1850 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1851 BrowserContext* browser_context,
1852 const GURL& url) {
1853 // Look up the map of site to process for the given browser_context.
1854 SiteProcessMap* map =
1855 GetSiteProcessMapForBrowserContext(browser_context);
1857 // See if we have an existing process with appropriate bindings for this site.
1858 // If not, the caller should create a new process and register it.
1859 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1860 .possibly_invalid_spec();
1861 RenderProcessHost* host = map->FindProcess(site);
1862 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
1863 !IsSuitableHost(host, browser_context, url))) {
1864 // The registered process does not have an appropriate set of bindings for
1865 // the url. Remove it from the map so we can register a better one.
1866 RecordAction(
1867 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1868 map->RemoveProcess(host);
1869 host = NULL;
1872 return host;
1875 void RenderProcessHostImpl::RegisterProcessHostForSite(
1876 BrowserContext* browser_context,
1877 RenderProcessHost* process,
1878 const GURL& url) {
1879 // Look up the map of site to process for the given browser_context.
1880 SiteProcessMap* map =
1881 GetSiteProcessMapForBrowserContext(browser_context);
1883 // Only register valid, non-empty sites. Empty or invalid sites will not
1884 // use process-per-site mode. We cannot check whether the process has
1885 // appropriate bindings here, because the bindings have not yet been granted.
1886 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1887 .possibly_invalid_spec();
1888 if (!site.empty())
1889 map->RegisterProcess(site, process);
1892 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1893 // Our child process has died. If we didn't expect it, it's a crash.
1894 // In any case, we need to let everyone know it's gone.
1895 // The OnChannelError notification can fire multiple times due to nested sync
1896 // calls to a renderer. If we don't have a valid channel here it means we
1897 // already handled the error.
1899 // It should not be possible for us to be called re-entrantly.
1900 DCHECK(!within_process_died_observer_);
1902 // It should not be possible for a process death notification to come in while
1903 // we are dying.
1904 DCHECK(!deleting_soon_);
1906 // child_process_launcher_ can be NULL in single process mode or if fast
1907 // termination happened.
1908 int exit_code = 0;
1909 base::TerminationStatus status =
1910 child_process_launcher_.get() ?
1911 child_process_launcher_->GetChildTerminationStatus(already_dead,
1912 &exit_code) :
1913 base::TERMINATION_STATUS_NORMAL_TERMINATION;
1915 RendererClosedDetails details(GetHandle(), status, exit_code);
1916 mojo_application_host_->WillDestroySoon();
1918 child_process_launcher_.reset();
1919 channel_.reset();
1921 within_process_died_observer_ = true;
1922 NotificationService::current()->Notify(
1923 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1924 Source<RenderProcessHost>(this),
1925 Details<RendererClosedDetails>(&details));
1926 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1927 observers_,
1928 RenderProcessExited(this, GetHandle(), status, exit_code));
1929 within_process_died_observer_ = false;
1931 gpu_message_filter_ = NULL;
1932 message_port_message_filter_ = NULL;
1933 RemoveUserData(kSessionStorageHolderKey);
1935 IDMap<IPC::Listener>::iterator iter(&listeners_);
1936 while (!iter.IsAtEnd()) {
1937 iter.GetCurrentValue()->OnMessageReceived(
1938 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1939 static_cast<int>(status),
1940 exit_code));
1941 iter.Advance();
1944 mojo_application_host_.reset(new MojoApplicationHost);
1945 mojo_activation_required_ = false;
1947 // It's possible that one of the calls out to the observers might have caused
1948 // this object to be no longer needed.
1949 if (delayed_cleanup_needed_)
1950 Cleanup();
1952 // This object is not deleted at this point and might be reused later.
1953 // TODO(darin): clean this up
1956 int RenderProcessHostImpl::GetActiveViewCount() {
1957 int num_active_views = 0;
1958 scoped_ptr<RenderWidgetHostIterator> widgets(
1959 RenderWidgetHost::GetRenderWidgetHosts());
1960 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1961 // Count only RenderWidgetHosts in this process.
1962 if (widget->GetProcess()->GetID() == GetID())
1963 num_active_views++;
1965 return num_active_views;
1968 // Frame subscription API for this class is for accelerated composited path
1969 // only. These calls are redirected to GpuMessageFilter.
1970 void RenderProcessHostImpl::BeginFrameSubscription(
1971 int route_id,
1972 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1973 if (!gpu_message_filter_)
1974 return;
1975 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1976 &GpuMessageFilter::BeginFrameSubscription,
1977 gpu_message_filter_,
1978 route_id, base::Passed(&subscriber)));
1981 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1982 if (!gpu_message_filter_)
1983 return;
1984 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1985 &GpuMessageFilter::EndFrameSubscription,
1986 gpu_message_filter_,
1987 route_id));
1990 #if defined(ENABLE_WEBRTC)
1991 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
1992 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1993 if (!webrtc_log_message_callback_.is_null())
1994 webrtc_log_message_callback_.Run(message);
1996 #endif
1998 void RenderProcessHostImpl::ReleaseOnCloseACK(
1999 RenderProcessHost* host,
2000 const SessionStorageNamespaceMap& sessions,
2001 int view_route_id) {
2002 DCHECK(host);
2003 if (sessions.empty())
2004 return;
2005 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2006 (host->GetUserData(kSessionStorageHolderKey));
2007 if (!holder) {
2008 holder = new SessionStorageHolder();
2009 host->SetUserData(
2010 kSessionStorageHolderKey,
2011 holder);
2013 holder->Hold(sessions, view_route_id);
2016 void RenderProcessHostImpl::OnShutdownRequest() {
2017 // Don't shut down if there are active RenderViews, or if there are pending
2018 // RenderViews being swapped back in.
2019 // In single process mode, we never shutdown the renderer.
2020 int num_active_views = GetActiveViewCount();
2021 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2022 return;
2024 // Notify any contents that might have swapped out renderers from this
2025 // process. They should not attempt to swap them back in.
2026 NotificationService::current()->Notify(
2027 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2028 Source<RenderProcessHost>(this),
2029 NotificationService::NoDetails());
2031 mojo_application_host_->WillDestroySoon();
2033 Send(new ChildProcessMsg_Shutdown());
2036 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2037 SetSuddenTerminationAllowed(enabled);
2040 void RenderProcessHostImpl::OnDumpHandlesDone() {
2041 Cleanup();
2044 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2045 // Note: we always set the backgrounded_ value. If the process is NULL
2046 // (and hence hasn't been created yet), we will set the process priority
2047 // later when we create the process.
2048 backgrounded_ = backgrounded;
2049 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2050 return;
2052 // Don't background processes which have active audio streams.
2053 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2054 return;
2056 #if defined(OS_WIN)
2057 // The cbstext.dll loads as a global GetMessage hook in the browser process
2058 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2059 // background thread. If the UI thread invokes this API just when it is
2060 // intercepted the stack is messed up on return from the interceptor
2061 // which causes random crashes in the browser process. Our hack for now
2062 // is to not invoke the SetPriorityClass API if the dll is loaded.
2063 if (GetModuleHandle(L"cbstext.dll"))
2064 return;
2065 #endif // OS_WIN
2067 // Notify the child process of background state.
2068 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2070 #if !defined(OS_WIN)
2071 // Backgrounding may require elevated privileges not available to renderer
2072 // processes, so control backgrounding from the process host.
2074 // Windows Vista+ has a fancy process backgrounding mode that can only be set
2075 // from within the process.
2076 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2077 #endif // !OS_WIN
2080 void RenderProcessHostImpl::OnProcessLaunched() {
2081 // No point doing anything, since this object will be destructed soon. We
2082 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2083 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2084 // properly cleanup.
2085 if (deleting_soon_)
2086 return;
2088 if (child_process_launcher_) {
2089 if (!child_process_launcher_->GetHandle()) {
2090 OnChannelError();
2091 return;
2094 SetBackgrounded(backgrounded_);
2097 // NOTE: This needs to be before sending queued messages because
2098 // ExtensionService uses this notification to initialize the renderer process
2099 // with state that must be there before any JavaScript executes.
2101 // The queued messages contain such things as "navigate". If this notification
2102 // was after, we can end up executing JavaScript before the initialization
2103 // happens.
2104 NotificationService::current()->Notify(
2105 NOTIFICATION_RENDERER_PROCESS_CREATED,
2106 Source<RenderProcessHost>(this),
2107 NotificationService::NoDetails());
2109 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2110 // This way, Mojo can be safely used from the renderer in response to any
2111 // Chrome IPC message.
2112 MaybeActivateMojo();
2114 if (channel_mojo_host_)
2115 channel_mojo_host_->OnClientLaunched(GetHandle());
2117 while (!queued_messages_.empty()) {
2118 Send(queued_messages_.front());
2119 queued_messages_.pop();
2122 #if defined(ENABLE_WEBRTC)
2123 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2124 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2125 #endif
2128 scoped_refptr<AudioRendererHost>
2129 RenderProcessHostImpl::audio_renderer_host() const {
2130 return audio_renderer_host_;
2133 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2134 const std::string& action) {
2135 RecordComputedAction(action);
2138 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2139 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2140 (GetUserData(kSessionStorageHolderKey));
2141 if (!holder)
2142 return;
2143 holder->Release(old_route_id);
2146 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2147 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2150 void RenderProcessHostImpl::OnGpuSwitching() {
2151 // We are updating all widgets including swapped out ones.
2152 scoped_ptr<RenderWidgetHostIterator> widgets(
2153 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2154 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2155 if (!widget->IsRenderView())
2156 continue;
2158 // Skip widgets in other processes.
2159 if (widget->GetProcess()->GetID() != GetID())
2160 continue;
2162 RenderViewHost* rvh = RenderViewHost::From(widget);
2163 rvh->OnWebkitPreferencesChanged();
2167 #if defined(ENABLE_WEBRTC)
2168 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2169 BrowserThread::PostTask(
2170 BrowserThread::UI,
2171 FROM_HERE,
2172 base::Bind(
2173 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2174 weak_factory_.GetWeakPtr(),
2175 id));
2178 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2179 BrowserThread::PostTask(
2180 BrowserThread::UI,
2181 FROM_HERE,
2182 base::Bind(
2183 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2184 weak_factory_.GetWeakPtr(),
2185 id));
2188 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2189 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2190 aec_dump_consumers_.push_back(id);
2191 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2192 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2193 id);
2197 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2198 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2199 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2200 it != aec_dump_consumers_.end(); ++it) {
2201 if (*it == id) {
2202 aec_dump_consumers_.erase(it);
2203 break;
2208 #if defined(OS_WIN)
2209 #define IntToStringType base::IntToString16
2210 #else
2211 #define IntToStringType base::IntToString
2212 #endif
2214 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2215 int id) {
2216 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2217 base::FilePath unique_file =
2218 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2219 .AddExtension(IntToStringType(id));
2220 BrowserThread::PostTaskAndReplyWithResult(
2221 BrowserThread::FILE, FROM_HERE,
2222 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2223 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2224 weak_factory_.GetWeakPtr(),
2225 id));
2228 #undef IntToStringType
2230 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2231 int id,
2232 IPC::PlatformFileForTransit file_for_transit) {
2233 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2234 return;
2235 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2238 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2239 Send(new AecDumpMsg_DisableAecDump());
2241 #endif
2243 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2244 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2245 ++worker_ref_count_;
2248 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2249 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2250 DCHECK_GT(worker_ref_count_, 0);
2251 --worker_ref_count_;
2252 if (worker_ref_count_ == 0)
2253 Cleanup();
2256 void RenderProcessHostImpl::EnsureMojoActivated() {
2257 mojo_activation_required_ = true;
2258 MaybeActivateMojo();
2261 } // namespace content