Battery Status API: add UMA logging for Linux.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blob0b95dda213f4478e756b8df802d049288b5f7398
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/numerics/safe_math.h"
30 #include "base/path_service.h"
31 #include "base/process/process_handle.h"
32 #include "base/rand_util.h"
33 #include "base/stl_util.h"
34 #include "base/strings/string_number_conversions.h"
35 #include "base/strings/string_util.h"
36 #include "base/supports_user_data.h"
37 #include "base/sys_info.h"
38 #include "base/threading/thread.h"
39 #include "base/threading/thread_restrictions.h"
40 #include "base/tracked_objects.h"
41 #include "cc/base/switches.h"
42 #include "content/browser/appcache/appcache_dispatcher_host.h"
43 #include "content/browser/appcache/chrome_appcache_service.h"
44 #include "content/browser/battery_status/battery_status_message_filter.h"
45 #include "content/browser/browser_child_process_host_impl.h"
46 #include "content/browser/browser_main.h"
47 #include "content/browser/browser_main_loop.h"
48 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
49 #include "content/browser/child_process_security_policy_impl.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/gpu/compositor_util.h"
59 #include "content/browser/gpu/gpu_data_manager_impl.h"
60 #include "content/browser/gpu/gpu_process_host.h"
61 #include "content/browser/gpu/shader_disk_cache.h"
62 #include "content/browser/histogram_message_filter.h"
63 #include "content/browser/indexed_db/indexed_db_context_impl.h"
64 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
65 #include "content/browser/loader/resource_message_filter.h"
66 #include "content/browser/loader/resource_scheduler_filter.h"
67 #include "content/browser/media/capture/audio_mirroring_manager.h"
68 #include "content/browser/media/media_internals.h"
69 #include "content/browser/media/midi_host.h"
70 #include "content/browser/message_port_message_filter.h"
71 #include "content/browser/mime_registry_message_filter.h"
72 #include "content/browser/mojo/mojo_application_host.h"
73 #include "content/browser/plugin_service_impl.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/client/gpu_memory_buffer_impl.h"
114 #include "content/common/gpu/gpu_messages.h"
115 #include "content/common/mojo/mojo_messages.h"
116 #include "content/common/resource_messages.h"
117 #include "content/common/view_messages.h"
118 #include "content/public/browser/browser_context.h"
119 #include "content/public/browser/content_browser_client.h"
120 #include "content/public/browser/notification_service.h"
121 #include "content/public/browser/notification_types.h"
122 #include "content/public/browser/render_process_host_factory.h"
123 #include "content/public/browser/render_process_host_observer.h"
124 #include "content/public/browser/render_widget_host.h"
125 #include "content/public/browser/render_widget_host_iterator.h"
126 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
127 #include "content/public/browser/resource_context.h"
128 #include "content/public/browser/user_metrics.h"
129 #include "content/public/browser/worker_service.h"
130 #include "content/public/common/content_constants.h"
131 #include "content/public/common/content_switches.h"
132 #include "content/public/common/process_type.h"
133 #include "content/public/common/resource_type.h"
134 #include "content/public/common/result_codes.h"
135 #include "content/public/common/sandboxed_process_launcher_delegate.h"
136 #include "content/public/common/url_constants.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 "media/base/media_switches.h"
143 #include "net/url_request/url_request_context_getter.h"
144 #include "ppapi/shared_impl/ppapi_switches.h"
145 #include "third_party/skia/include/core/SkBitmap.h"
146 #include "ui/base/ui_base_switches.h"
147 #include "ui/events/event_switches.h"
148 #include "ui/gfx/switches.h"
149 #include "ui/gl/gl_switches.h"
150 #include "ui/native_theme/native_theme_switches.h"
151 #include "webkit/browser/fileapi/sandbox_file_system_backend.h"
153 #if defined(OS_ANDROID)
154 #include "content/browser/media/android/browser_demuxer_android.h"
155 #include "content/browser/renderer_host/compositor_impl_android.h"
156 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
157 #include "content/common/gpu/client/gpu_memory_buffer_impl_surface_texture.h"
158 #endif
160 #if defined(OS_MACOSX)
161 #include "content/common/gpu/client/gpu_memory_buffer_impl_io_surface.h"
162 #endif
164 #if defined(OS_WIN)
165 #include "base/win/scoped_com_initializer.h"
166 #include "content/common/font_cache_dispatcher_win.h"
167 #include "content/common/sandbox_win.h"
168 #include "ui/gfx/win/dpi.h"
169 #endif
171 #if defined(ENABLE_WEBRTC)
172 #include "content/browser/media/webrtc_internals.h"
173 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
174 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
175 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
176 #include "content/common/media/aec_dump_messages.h"
177 #include "content/common/media/media_stream_messages.h"
178 #endif
180 extern bool g_exited_main_message_loop;
182 namespace content {
183 namespace {
185 const char kSiteProcessMapKeyName[] = "content_site_process_map";
187 void CacheShaderInfo(int32 id, base::FilePath path) {
188 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
191 void RemoveShaderInfo(int32 id) {
192 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
195 net::URLRequestContext* GetRequestContext(
196 scoped_refptr<net::URLRequestContextGetter> request_context,
197 scoped_refptr<net::URLRequestContextGetter> media_request_context,
198 ResourceType resource_type) {
199 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
200 // context specific to media for handling it because these resources have
201 // specific needs for caching.
202 if (resource_type == RESOURCE_TYPE_MEDIA)
203 return media_request_context->GetURLRequestContext();
204 return request_context->GetURLRequestContext();
207 void GetContexts(
208 ResourceContext* resource_context,
209 scoped_refptr<net::URLRequestContextGetter> request_context,
210 scoped_refptr<net::URLRequestContextGetter> media_request_context,
211 const ResourceHostMsg_Request& request,
212 ResourceContext** resource_context_out,
213 net::URLRequestContext** request_context_out) {
214 *resource_context_out = resource_context;
215 *request_context_out =
216 GetRequestContext(request_context, media_request_context,
217 request.resource_type);
220 #if defined(ENABLE_WEBRTC)
221 // Creates a file used for diagnostic echo canceller recordings for handing
222 // over to the renderer.
223 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
224 base::FilePath file_path,
225 base::ProcessHandle process) {
226 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
227 base::File dump_file(file_path,
228 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
229 if (!dump_file.IsValid()) {
230 VLOG(1) << "Could not open AEC dump file, error=" <<
231 dump_file.error_details();
232 return IPC::InvalidPlatformFileForTransit();
234 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
237 // Does nothing. Just to avoid races between enable and disable.
238 void DisableAecDumpOnFileThread() {
239 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
241 #endif
243 // the global list of all renderer processes
244 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
245 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
247 // Map of site to process, to ensure we only have one RenderProcessHost per
248 // site in process-per-site mode. Each map is specific to a BrowserContext.
249 class SiteProcessMap : public base::SupportsUserData::Data {
250 public:
251 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
252 SiteProcessMap() {}
254 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
255 map_[site] = process;
258 RenderProcessHost* FindProcess(const std::string& site) {
259 SiteToProcessMap::iterator i = map_.find(site);
260 if (i != map_.end())
261 return i->second;
262 return NULL;
265 void RemoveProcess(RenderProcessHost* host) {
266 // Find all instances of this process in the map, then separately remove
267 // them.
268 std::set<std::string> sites;
269 for (SiteToProcessMap::const_iterator i = map_.begin();
270 i != map_.end();
271 i++) {
272 if (i->second == host)
273 sites.insert(i->first);
275 for (std::set<std::string>::iterator i = sites.begin();
276 i != sites.end();
277 i++) {
278 SiteToProcessMap::iterator iter = map_.find(*i);
279 if (iter != map_.end()) {
280 DCHECK_EQ(iter->second, host);
281 map_.erase(iter);
286 private:
287 SiteToProcessMap map_;
290 // Find the SiteProcessMap specific to the given context.
291 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
292 DCHECK(context);
293 SiteProcessMap* map = static_cast<SiteProcessMap*>(
294 context->GetUserData(kSiteProcessMapKeyName));
295 if (!map) {
296 map = new SiteProcessMap();
297 context->SetUserData(kSiteProcessMapKeyName, map);
299 return map;
302 // NOTE: changes to this class need to be reviewed by the security team.
303 class RendererSandboxedProcessLauncherDelegate
304 : public content::SandboxedProcessLauncherDelegate {
305 public:
306 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
307 #if defined(OS_POSIX)
308 : ipc_fd_(channel->TakeClientFileDescriptor())
309 #endif // OS_POSIX
312 virtual ~RendererSandboxedProcessLauncherDelegate() {}
314 #if defined(OS_WIN)
315 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
316 bool* success) {
317 AddBaseHandleClosePolicy(policy);
318 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
321 #elif defined(OS_POSIX)
322 virtual bool ShouldUseZygote() OVERRIDE {
323 const base::CommandLine& browser_command_line =
324 *base::CommandLine::ForCurrentProcess();
325 base::CommandLine::StringType renderer_prefix =
326 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
327 return renderer_prefix.empty();
329 virtual int GetIpcFd() OVERRIDE {
330 return ipc_fd_;
332 #endif // OS_WIN
334 private:
335 #if defined(OS_POSIX)
336 int ipc_fd_;
337 #endif // OS_POSIX
340 #if defined(OS_MACOSX)
341 void AddBooleanValue(CFMutableDictionaryRef dictionary,
342 const CFStringRef key,
343 bool value) {
344 CFDictionaryAddValue(
345 dictionary, key, value ? kCFBooleanTrue : kCFBooleanFalse);
348 void AddIntegerValue(CFMutableDictionaryRef dictionary,
349 const CFStringRef key,
350 int32 value) {
351 base::ScopedCFTypeRef<CFNumberRef> number(
352 CFNumberCreate(NULL, kCFNumberSInt32Type, &value));
353 CFDictionaryAddValue(dictionary, key, number.get());
355 #endif
357 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
359 class SessionStorageHolder : public base::SupportsUserData::Data {
360 public:
361 SessionStorageHolder() {}
362 virtual ~SessionStorageHolder() {}
364 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
365 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
368 void Release(int old_route_id) {
369 session_storage_namespaces_awaiting_close_.erase(old_route_id);
372 private:
373 std::map<int, SessionStorageNamespaceMap >
374 session_storage_namespaces_awaiting_close_;
375 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
378 } // namespace
380 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
382 base::MessageLoop* g_in_process_thread;
384 base::MessageLoop*
385 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
386 return g_in_process_thread;
389 // Stores the maximum number of renderer processes the content module can
390 // create.
391 static size_t g_max_renderer_count_override = 0;
393 // static
394 size_t RenderProcessHost::GetMaxRendererProcessCount() {
395 if (g_max_renderer_count_override)
396 return g_max_renderer_count_override;
398 #if defined(OS_ANDROID)
399 // On Android we don't maintain a limit of renderer process hosts - we are
400 // happy with keeping a lot of these, as long as the number of live renderer
401 // processes remains reasonable, and on Android the OS takes care of that.
402 return std::numeric_limits<size_t>::max();
403 #endif
405 // On other platforms, we calculate the maximum number of renderer process
406 // hosts according to the amount of installed memory as reported by the OS.
407 // The calculation assumes that you want the renderers to use half of the
408 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
409 // this assumption, you need to adjust the ThirtyFourTabs test to match the
410 // expected number of processes.
412 // With the given amounts of installed memory below on a 32-bit CPU, the
413 // maximum renderer count will roughly be as follows:
415 // 128 MB -> 3
416 // 512 MB -> 6
417 // 1024 MB -> 12
418 // 4096 MB -> 51
419 // 16384 MB -> 82 (kMaxRendererProcessCount)
421 static size_t max_count = 0;
422 if (!max_count) {
423 const size_t kEstimatedWebContentsMemoryUsage =
424 #if defined(ARCH_CPU_64_BITS)
425 60; // In MB
426 #else
427 40; // In MB
428 #endif
429 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
430 max_count /= kEstimatedWebContentsMemoryUsage;
432 const size_t kMinRendererProcessCount = 3;
433 max_count = std::max(max_count, kMinRendererProcessCount);
434 max_count = std::min(max_count, kMaxRendererProcessCount);
436 return max_count;
439 // static
440 bool g_run_renderer_in_process_ = false;
442 // static
443 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
444 g_max_renderer_count_override = count;
447 RenderProcessHostImpl::RenderProcessHostImpl(
448 BrowserContext* browser_context,
449 StoragePartitionImpl* storage_partition_impl,
450 bool is_isolated_guest)
451 : fast_shutdown_started_(false),
452 deleting_soon_(false),
453 #ifndef NDEBUG
454 is_self_deleted_(false),
455 #endif
456 pending_views_(0),
457 mojo_application_host_(new MojoApplicationHost),
458 mojo_activation_required_(false),
459 visible_widgets_(0),
460 backgrounded_(true),
461 is_initialized_(false),
462 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
463 browser_context_(browser_context),
464 storage_partition_impl_(storage_partition_impl),
465 sudden_termination_allowed_(true),
466 ignore_input_events_(false),
467 is_isolated_guest_(is_isolated_guest),
468 gpu_observer_registered_(false),
469 delayed_cleanup_needed_(false),
470 within_process_died_observer_(false),
471 power_monitor_broadcaster_(this),
472 worker_ref_count_(0),
473 weak_factory_(this) {
474 widget_helper_ = new RenderWidgetHelper();
476 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
478 CHECK(!g_exited_main_message_loop);
479 RegisterHost(GetID(), this);
480 g_all_hosts.Get().set_check_on_null_data(true);
481 // Initialize |child_process_activity_time_| to a reasonable value.
482 mark_child_process_activity_time();
484 if (!GetBrowserContext()->IsOffTheRecord() &&
485 !base::CommandLine::ForCurrentProcess()->HasSwitch(
486 switches::kDisableGpuShaderDiskCache)) {
487 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
488 base::Bind(&CacheShaderInfo, GetID(),
489 storage_partition_impl_->GetPath()));
492 // Note: When we create the RenderProcessHostImpl, it's technically
493 // backgrounded, because it has no visible listeners. But the process
494 // doesn't actually exist yet, so we'll Background it later, after
495 // creation.
498 // static
499 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
500 DCHECK(g_run_renderer_in_process_);
502 switch (g_all_hosts.Pointer()->size()) {
503 case 0:
504 return;
505 case 1: {
506 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
507 AllHostsIterator().GetCurrentValue());
508 FOR_EACH_OBSERVER(RenderProcessHostObserver,
509 host->observers_,
510 RenderProcessHostDestroyed(host));
511 #ifndef NDEBUG
512 host->is_self_deleted_ = true;
513 #endif
514 delete host;
515 return;
517 default:
518 NOTREACHED() << "There should be only one RenderProcessHost when running "
519 << "in-process.";
523 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
524 RendererMainThreadFactoryFunction create) {
525 g_renderer_main_thread_factory = create;
528 RenderProcessHostImpl::~RenderProcessHostImpl() {
529 #ifndef NDEBUG
530 DCHECK(is_self_deleted_)
531 << "RenderProcessHostImpl is destroyed by something other than itself";
532 #endif
534 // Make sure to clean up the in-process renderer before the channel, otherwise
535 // it may still run and have its IPCs fail, causing asserts.
536 in_process_renderer_.reset();
538 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
540 if (gpu_observer_registered_) {
541 GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
542 gpu_observer_registered_ = false;
545 // We may have some unsent messages at this point, but that's OK.
546 channel_.reset();
547 while (!queued_messages_.empty()) {
548 delete queued_messages_.front();
549 queued_messages_.pop();
552 UnregisterHost(GetID());
554 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
555 switches::kDisableGpuShaderDiskCache)) {
556 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
557 base::Bind(&RemoveShaderInfo, GetID()));
560 #if defined(OS_ANDROID)
561 CompositorImpl::DestroyAllSurfaceTextures(GetID());
562 #endif
565 void RenderProcessHostImpl::EnableSendQueue() {
566 is_initialized_ = false;
569 bool RenderProcessHostImpl::Init() {
570 // calling Init() more than once does nothing, this makes it more convenient
571 // for the view host which may not be sure in some cases
572 if (channel_)
573 return true;
575 base::CommandLine::StringType renderer_prefix;
576 #if defined(OS_POSIX)
577 // A command prefix is something prepended to the command line of the spawned
578 // process. It is supported only on POSIX systems.
579 const base::CommandLine& browser_command_line =
580 *base::CommandLine::ForCurrentProcess();
581 renderer_prefix =
582 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
583 #endif // defined(OS_POSIX)
585 #if defined(OS_LINUX)
586 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
587 ChildProcessHost::CHILD_NORMAL;
588 #else
589 int flags = ChildProcessHost::CHILD_NORMAL;
590 #endif
592 // Find the renderer before creating the channel so if this fails early we
593 // return without creating the channel.
594 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
595 if (renderer_path.empty())
596 return false;
598 // Setup the IPC channel.
599 const std::string channel_id =
600 IPC::Channel::GenerateVerifiedChannelID(std::string());
601 channel_ = CreateChannelProxy(channel_id);
603 // Setup the Mojo channel.
604 mojo_application_host_->Init();
606 // Call the embedder first so that their IPC filters have priority.
607 GetContentClient()->browser()->RenderProcessWillLaunch(this);
609 CreateMessageFilters();
611 if (run_renderer_in_process()) {
612 DCHECK(g_renderer_main_thread_factory);
613 // Crank up a thread and run the initialization there. With the way that
614 // messages flow between the browser and renderer, this thread is required
615 // to prevent a deadlock in single-process mode. Since the primordial
616 // thread in the renderer process runs the WebKit code and can sometimes
617 // make blocking calls to the UI thread (i.e. this thread), they need to run
618 // on separate threads.
619 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
621 base::Thread::Options options;
622 #if defined(OS_WIN) && !defined(OS_MACOSX)
623 // In-process plugins require this to be a UI message loop.
624 options.message_loop_type = base::MessageLoop::TYPE_UI;
625 #else
626 // We can't have multiple UI loops on Linux and Android, so we don't support
627 // in-process plugins.
628 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
629 #endif
630 in_process_renderer_->StartWithOptions(options);
632 g_in_process_thread = in_process_renderer_->message_loop();
634 OnProcessLaunched(); // Fake a callback that the process is ready.
635 } else {
636 // Build command line for renderer. We call AppendRendererCommandLine()
637 // first so the process type argument will appear first.
638 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
639 if (!renderer_prefix.empty())
640 cmd_line->PrependWrapper(renderer_prefix);
641 AppendRendererCommandLine(cmd_line);
642 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
644 // Spawn the child process asynchronously to avoid blocking the UI thread.
645 // As long as there's no renderer prefix, we can use the zygote process
646 // at this stage.
647 child_process_launcher_.reset(new ChildProcessLauncher(
648 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
649 cmd_line,
650 GetID(),
651 this));
653 fast_shutdown_started_ = false;
656 if (!gpu_observer_registered_) {
657 gpu_observer_registered_ = true;
658 GpuDataManagerImpl::GetInstance()->AddObserver(this);
661 power_monitor_broadcaster_.Init();
663 is_initialized_ = true;
664 return true;
667 void RenderProcessHostImpl::MaybeActivateMojo() {
668 // TODO(darin): Following security review, we can unconditionally initialize
669 // Mojo in all renderers. We will then be able to directly call Activate()
670 // from OnProcessLaunched.
671 if (!mojo_activation_required_)
672 return; // Waiting on someone to require Mojo.
674 if (!GetHandle())
675 return; // Waiting on renderer startup.
677 if (!mojo_application_host_->did_activate())
678 mojo_application_host_->Activate(this, GetHandle());
681 bool RenderProcessHostImpl::ShouldUseMojoChannel() const {
682 const base::CommandLine& command_line =
683 *base::CommandLine::ForCurrentProcess();
684 return command_line.HasSwitch(switches::kEnableRendererMojoChannel);
687 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
688 const std::string& channel_id) {
689 scoped_refptr<base::SingleThreadTaskRunner> runner =
690 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
691 if (ShouldUseMojoChannel()) {
692 VLOG(1) << "Mojo Channel is enabled on host";
693 return IPC::ChannelProxy::Create(
694 IPC::ChannelMojo::CreateFactory(
695 channel_id, IPC::Channel::MODE_SERVER, runner),
696 this, runner.get());
699 return IPC::ChannelProxy::Create(
700 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
703 void RenderProcessHostImpl::CreateMessageFilters() {
704 DCHECK_CURRENTLY_ON(BrowserThread::UI);
705 AddFilter(new ResourceSchedulerFilter(GetID()));
706 MediaInternals* media_internals = MediaInternals::GetInstance();
707 media::AudioManager* audio_manager =
708 BrowserMainLoop::GetInstance()->audio_manager();
709 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
710 // from guests.
711 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
712 new BrowserPluginMessageFilter(GetID()));
713 AddFilter(bp_message_filter.get());
715 scoped_refptr<RenderMessageFilter> render_message_filter(
716 new RenderMessageFilter(
717 GetID(),
718 #if defined(ENABLE_PLUGINS)
719 PluginServiceImpl::GetInstance(),
720 #else
721 NULL,
722 #endif
723 GetBrowserContext(),
724 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
725 widget_helper_.get(),
726 audio_manager,
727 media_internals,
728 storage_partition_impl_->GetDOMStorageContext()));
729 AddFilter(render_message_filter.get());
730 AddFilter(
731 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
732 BrowserContext* browser_context = GetBrowserContext();
733 ResourceContext* resource_context = browser_context->GetResourceContext();
735 scoped_refptr<net::URLRequestContextGetter> request_context(
736 browser_context->GetRequestContextForRenderProcess(GetID()));
737 scoped_refptr<net::URLRequestContextGetter> media_request_context(
738 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
740 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
741 base::Bind(&GetContexts, browser_context->GetResourceContext(),
742 request_context, media_request_context));
744 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
745 GetID(), PROCESS_TYPE_RENDERER,
746 storage_partition_impl_->GetAppCacheService(),
747 ChromeBlobStorageContext::GetFor(browser_context),
748 storage_partition_impl_->GetFileSystemContext(),
749 storage_partition_impl_->GetServiceWorkerContext(),
750 get_contexts_callback);
752 AddFilter(resource_message_filter);
753 MediaStreamManager* media_stream_manager =
754 BrowserMainLoop::GetInstance()->media_stream_manager();
755 AddFilter(new AudioInputRendererHost(
756 audio_manager,
757 media_stream_manager,
758 AudioMirroringManager::GetInstance(),
759 BrowserMainLoop::GetInstance()->user_input_monitor()));
760 // The AudioRendererHost needs to be available for lookup, so it's
761 // stashed in a member variable.
762 audio_renderer_host_ = new AudioRendererHost(
763 GetID(),
764 audio_manager,
765 AudioMirroringManager::GetInstance(),
766 media_internals,
767 media_stream_manager);
768 AddFilter(audio_renderer_host_.get());
769 AddFilter(
770 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
771 AddFilter(new VideoCaptureHost(media_stream_manager));
772 AddFilter(new AppCacheDispatcherHost(
773 storage_partition_impl_->GetAppCacheService(),
774 GetID()));
775 AddFilter(new ClipboardMessageFilter);
776 AddFilter(new DOMStorageMessageFilter(
777 GetID(),
778 storage_partition_impl_->GetDOMStorageContext()));
779 AddFilter(new IndexedDBDispatcherHost(
780 GetID(),
781 storage_partition_impl_->GetURLRequestContext(),
782 storage_partition_impl_->GetIndexedDBContext(),
783 ChromeBlobStorageContext::GetFor(browser_context)));
785 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
786 AddFilter(gpu_message_filter_);
787 #if defined(ENABLE_WEBRTC)
788 AddFilter(new WebRTCIdentityServiceHost(
789 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
790 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
791 AddFilter(peer_connection_tracker_host_.get());
792 AddFilter(new MediaStreamDispatcherHost(
793 GetID(),
794 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
795 media_stream_manager,
796 resource_context));
797 AddFilter(new DeviceRequestMessageFilter(
798 resource_context, media_stream_manager, GetID()));
799 AddFilter(new MediaStreamTrackMetricsHost());
800 #endif
801 #if defined(ENABLE_PLUGINS)
802 AddFilter(new PepperRendererConnection(GetID()));
803 #endif
804 AddFilter(new SpeechRecognitionDispatcherHost(
805 GetID(), storage_partition_impl_->GetURLRequestContext()));
806 AddFilter(new FileAPIMessageFilter(
807 GetID(),
808 storage_partition_impl_->GetURLRequestContext(),
809 storage_partition_impl_->GetFileSystemContext(),
810 ChromeBlobStorageContext::GetFor(browser_context),
811 StreamContext::GetFor(browser_context)));
812 AddFilter(new FileUtilitiesMessageFilter(GetID()));
813 AddFilter(new MimeRegistryMessageFilter());
814 AddFilter(new DatabaseMessageFilter(
815 storage_partition_impl_->GetDatabaseTracker()));
816 #if defined(OS_MACOSX)
817 AddFilter(new TextInputClientMessageFilter(GetID()));
818 #elif defined(OS_WIN)
819 // The FontCacheDispatcher is required only when we're using GDI rendering.
820 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
821 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
822 // should eventually be if (!ShouldUseDirectWrite()) guarded.
823 channel_->AddFilter(new FontCacheDispatcher());
824 #elif defined(OS_ANDROID)
825 browser_demuxer_android_ = new BrowserDemuxerAndroid();
826 AddFilter(browser_demuxer_android_);
827 #endif
829 SocketStreamDispatcherHost::GetRequestContextCallback
830 request_context_callback(
831 base::Bind(&GetRequestContext, request_context,
832 media_request_context));
834 SocketStreamDispatcherHost* socket_stream_dispatcher_host =
835 new SocketStreamDispatcherHost(
836 GetID(), request_context_callback, resource_context);
837 AddFilter(socket_stream_dispatcher_host);
839 WebSocketDispatcherHost::GetRequestContextCallback
840 websocket_request_context_callback(
841 base::Bind(&GetRequestContext, request_context,
842 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
844 AddFilter(
845 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
847 message_port_message_filter_ = new MessagePortMessageFilter(
848 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
849 base::Unretained(widget_helper_.get())));
850 AddFilter(message_port_message_filter_.get());
852 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
853 new ServiceWorkerDispatcherHost(GetID(),
854 message_port_message_filter_.get());
855 service_worker_filter->Init(
856 storage_partition_impl_->GetServiceWorkerContext());
857 AddFilter(service_worker_filter.get());
859 AddFilter(new SharedWorkerMessageFilter(
860 GetID(),
861 resource_context,
862 WorkerStoragePartition(
863 storage_partition_impl_->GetURLRequestContext(),
864 storage_partition_impl_->GetMediaURLRequestContext(),
865 storage_partition_impl_->GetAppCacheService(),
866 storage_partition_impl_->GetQuotaManager(),
867 storage_partition_impl_->GetFileSystemContext(),
868 storage_partition_impl_->GetDatabaseTracker(),
869 storage_partition_impl_->GetIndexedDBContext(),
870 storage_partition_impl_->GetServiceWorkerContext()),
871 message_port_message_filter_.get()));
873 #if defined(ENABLE_WEBRTC)
874 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
875 resource_context,
876 browser_context->GetRequestContextForRenderProcess(GetID()));
877 AddFilter(p2p_socket_dispatcher_host_.get());
878 #endif
880 AddFilter(new TraceMessageFilter());
881 AddFilter(new ResolveProxyMsgHelper(
882 browser_context->GetRequestContextForRenderProcess(GetID())));
883 AddFilter(new QuotaDispatcherHost(
884 GetID(),
885 storage_partition_impl_->GetQuotaManager(),
886 GetContentClient()->browser()->CreateQuotaPermissionContext()));
887 AddFilter(new GamepadBrowserMessageFilter());
888 AddFilter(new DeviceMotionMessageFilter());
889 AddFilter(new DeviceOrientationMessageFilter());
890 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
891 AddFilter(new HistogramMessageFilter());
892 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
893 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
894 switches::kEnableMemoryBenchmarking))
895 AddFilter(new MemoryBenchmarkMessageFilter());
896 #endif
897 AddFilter(new VibrationMessageFilter());
898 AddFilter(new PushMessagingMessageFilter(
899 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
900 AddFilter(new BatteryStatusMessageFilter());
901 #if defined(OS_ANDROID)
902 AddFilter(new ScreenOrientationMessageFilterAndroid());
903 #endif
906 int RenderProcessHostImpl::GetNextRoutingID() {
907 return widget_helper_->GetNextRoutingID();
911 void RenderProcessHostImpl::ResumeDeferredNavigation(
912 const GlobalRequestID& request_id) {
913 widget_helper_->ResumeDeferredNavigation(request_id);
916 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
917 const GlobalRequestID& request_id) {
918 widget_helper_->ResumeResponseDeferredAtStart(request_id);
921 void RenderProcessHostImpl::NotifyTimezoneChange() {
922 Send(new ViewMsg_TimezoneChange());
925 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
926 DCHECK(mojo_application_host_);
927 return mojo_application_host_->service_registry();
930 void RenderProcessHostImpl::AddRoute(
931 int32 routing_id,
932 IPC::Listener* listener) {
933 listeners_.AddWithID(listener, routing_id);
936 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
937 DCHECK(listeners_.Lookup(routing_id) != NULL);
938 listeners_.Remove(routing_id);
940 #if defined(OS_WIN)
941 // Dump the handle table if handle auditing is enabled.
942 const base::CommandLine& browser_command_line =
943 *base::CommandLine::ForCurrentProcess();
944 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
945 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
946 DumpHandles();
948 // We wait to close the channels until the child process has finished
949 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
950 return;
952 #endif
953 // Keep the one renderer thread around forever in single process mode.
954 if (!run_renderer_in_process())
955 Cleanup();
958 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
959 observers_.AddObserver(observer);
962 void RenderProcessHostImpl::RemoveObserver(
963 RenderProcessHostObserver* observer) {
964 observers_.RemoveObserver(observer);
967 void RenderProcessHostImpl::ReceivedBadMessage() {
968 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
969 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
970 return;
972 if (run_renderer_in_process()) {
973 // In single process mode it is better if we don't suicide but just
974 // crash.
975 CHECK(false);
977 // We kill the renderer but don't include a NOTREACHED, because we want the
978 // browser to try to survive when it gets illegal messages from the renderer.
979 base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
980 false);
983 void RenderProcessHostImpl::WidgetRestored() {
984 // Verify we were properly backgrounded.
985 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
986 visible_widgets_++;
987 SetBackgrounded(false);
990 void RenderProcessHostImpl::WidgetHidden() {
991 // On startup, the browser will call Hide
992 if (backgrounded_)
993 return;
995 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
996 visible_widgets_--;
997 DCHECK_GE(visible_widgets_, 0);
998 if (visible_widgets_ == 0) {
999 DCHECK(!backgrounded_);
1000 SetBackgrounded(true);
1004 int RenderProcessHostImpl::VisibleWidgetCount() const {
1005 return visible_widgets_;
1008 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1009 return is_isolated_guest_;
1012 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1013 return storage_partition_impl_;
1016 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1017 if (IsPinchVirtualViewportEnabled())
1018 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
1020 if (IsDelegatedRendererEnabled())
1021 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1023 if (IsImplSidePaintingEnabled())
1024 command_line->AppendSwitch(switches::kEnableImplSidePainting);
1026 if (content::IsGpuRasterizationEnabled())
1027 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1029 if (content::IsForceGpuRasterizationEnabled())
1030 command_line->AppendSwitch(switches::kForceGpuRasterization);
1032 // Appending disable-gpu-feature switches due to software rendering list.
1033 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1034 DCHECK(gpu_data_manager);
1035 gpu_data_manager->AppendRendererCommandLine(command_line);
1038 void RenderProcessHostImpl::AppendRendererCommandLine(
1039 base::CommandLine* command_line) const {
1040 // Pass the process type first, so it shows first in process listings.
1041 command_line->AppendSwitchASCII(switches::kProcessType,
1042 switches::kRendererProcess);
1044 // Now send any options from our own command line we want to propagate.
1045 const base::CommandLine& browser_command_line =
1046 *base::CommandLine::ForCurrentProcess();
1047 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1049 // Pass on the browser locale.
1050 const std::string locale =
1051 GetContentClient()->browser()->GetApplicationLocale();
1052 command_line->AppendSwitchASCII(switches::kLang, locale);
1054 // If we run base::FieldTrials, we want to pass to their state to the
1055 // renderer so that it can act in accordance with each state, or record
1056 // histograms relating to the base::FieldTrial states.
1057 std::string field_trial_states;
1058 base::FieldTrialList::StatesToString(&field_trial_states);
1059 if (!field_trial_states.empty()) {
1060 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1061 field_trial_states);
1064 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1065 command_line, GetID());
1067 if (content::IsPinchToZoomEnabled())
1068 command_line->AppendSwitch(switches::kEnablePinch);
1070 #if defined(OS_WIN)
1071 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1072 base::DoubleToString(gfx::GetDPIScale()));
1073 #endif
1075 AppendCompositorCommandLineFlags(command_line);
1078 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1079 const base::CommandLine& browser_cmd,
1080 base::CommandLine* renderer_cmd) const {
1081 // Propagate the following switches to the renderer command line (along
1082 // with any associated values) if present in the browser command line.
1083 static const char* const kSwitchNames[] = {
1084 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1085 switches::kAllowLoopbackInPeerConnection,
1086 switches::kAudioBufferSize,
1087 switches::kAuditAllHandles,
1088 switches::kAuditHandles,
1089 switches::kBlinkPlatformLogChannels,
1090 switches::kBlockCrossSiteDocuments,
1091 switches::kDefaultTileWidth,
1092 switches::kDefaultTileHeight,
1093 switches::kDisable3DAPIs,
1094 switches::kDisableAcceleratedVideoDecode,
1095 switches::kDisableApplicationCache,
1096 switches::kDisableBreakpad,
1097 switches::kDisablePreferCompositingToLCDText,
1098 switches::kDisableCompositingForTransition,
1099 switches::kDisableDatabases,
1100 switches::kDisableDesktopNotifications,
1101 switches::kDisableDirectNPAPIRequests,
1102 switches::kDisableDisplayList2dCanvas,
1103 switches::kDisableDistanceFieldText,
1104 switches::kDisableFileSystem,
1105 switches::kDisableGpuCompositing,
1106 switches::kDisableGpuVsync,
1107 switches::kDisableLowResTiling,
1108 switches::kDisableHistogramCustomizer,
1109 switches::kDisableLCDText,
1110 switches::kDisableLayerSquashing,
1111 switches::kDisableLocalStorage,
1112 switches::kDisableLogging,
1113 switches::kDisableMediaSource,
1114 switches::kDisableOverlayScrollbar,
1115 switches::kDisablePinch,
1116 switches::kDisablePrefixedEncryptedMedia,
1117 switches::kDisableSeccompFilterSandbox,
1118 switches::kDisableSessionStorage,
1119 switches::kDisableSharedWorkers,
1120 switches::kDisableThreadedCompositing,
1121 switches::kDisableTouchAdjustment,
1122 switches::kDisableTouchDragDrop,
1123 switches::kDisableTouchEditing,
1124 switches::kDisableZeroCopy,
1125 switches::kDomAutomationController,
1126 switches::kEnableBeginFrameScheduling,
1127 switches::kEnableBleedingEdgeRenderingFastPaths,
1128 switches::kEnablePreferCompositingToLCDText,
1129 switches::kEnableCompositingForTransition,
1130 switches::kEnableDeferredImageDecoding,
1131 switches::kEnableDisplayList2dCanvas,
1132 switches::kEnableDistanceFieldText,
1133 switches::kEnableEncryptedMedia,
1134 switches::kEnableExperimentalCanvasFeatures,
1135 switches::kEnableExperimentalWebPlatformFeatures,
1136 switches::kEnableGPUClientLogging,
1137 switches::kEnableGpuClientTracing,
1138 switches::kEnableGPUServiceLogging,
1139 switches::kEnableLowResTiling,
1140 switches::kEnableInbandTextTracks,
1141 switches::kEnableLCDText,
1142 switches::kEnableLayerSquashing,
1143 switches::kEnableLogging,
1144 switches::kEnableMemoryBenchmarking,
1145 switches::kEnableNetworkInformation,
1146 switches::kEnableOneCopy,
1147 switches::kEnableOverlayFullscreenVideo,
1148 switches::kEnableOverlayScrollbar,
1149 switches::kEnableOverscrollNotifications,
1150 switches::kEnablePinch,
1151 switches::kEnablePreciseMemoryInfo,
1152 switches::kEnableRendererMojoChannel,
1153 switches::kEnableSeccompFilterSandbox,
1154 switches::kEnableSkiaBenchmarking,
1155 switches::kEnableSmoothScrolling,
1156 switches::kEnableStatsTable,
1157 switches::kEnableStrictSiteIsolation,
1158 switches::kEnableTargetedStyleRecalc,
1159 switches::kEnableThreadedCompositing,
1160 switches::kEnableTouchDragDrop,
1161 switches::kEnableTouchEditing,
1162 switches::kEnableViewport,
1163 switches::kEnableViewportMeta,
1164 switches::kEnableVtune,
1165 switches::kEnableWebAnimationsSVG,
1166 switches::kEnableWebGLDraftExtensions,
1167 switches::kEnableWebGLImageChromium,
1168 switches::kEnableWebMIDI,
1169 switches::kEnableZeroCopy,
1170 switches::kForceDeviceScaleFactor,
1171 switches::kFullMemoryCrashReport,
1172 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
1173 switches::kIPCConnectionTimeout,
1174 switches::kJavaScriptFlags,
1175 switches::kLoggingLevel,
1176 switches::kMainFrameResizesAreOrientationChanges,
1177 switches::kMaxUntiledLayerWidth,
1178 switches::kMaxUntiledLayerHeight,
1179 switches::kMemoryMetrics,
1180 switches::kNoReferrers,
1181 switches::kNoSandbox,
1182 switches::kNumRasterThreads,
1183 switches::kPpapiInProcess,
1184 switches::kProfilerTiming,
1185 switches::kReduceSecurityForTesting,
1186 switches::kRegisterPepperPlugins,
1187 switches::kRendererAssertTest,
1188 switches::kRendererStartupDialog,
1189 switches::kSendV8IdleNotificationAfterCommit,
1190 switches::kShowPaintRects,
1191 switches::kSitePerProcess,
1192 switches::kStatsCollectionController,
1193 switches::kTestType,
1194 switches::kTouchEvents,
1195 switches::kTraceToConsole,
1196 switches::kUseDiscardableMemory,
1197 // This flag needs to be propagated to the renderer process for
1198 // --in-process-webgl.
1199 switches::kUseGL,
1200 switches::kUseMobileUserAgent,
1201 switches::kV,
1202 switches::kVideoThreads,
1203 switches::kVModule,
1204 // Please keep these in alphabetical order. Compositor switches here should
1205 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1206 cc::switches::kCompositeToMailbox,
1207 cc::switches::kDisableCompositedAntialiasing,
1208 cc::switches::kDisableMainFrameBeforeActivation,
1209 cc::switches::kDisableMainFrameBeforeDraw,
1210 cc::switches::kDisableThreadedAnimation,
1211 cc::switches::kEnableGpuBenchmarking,
1212 cc::switches::kEnableMainFrameBeforeActivation,
1213 cc::switches::kEnableTopControlsPositionCalculation,
1214 cc::switches::kMaxTilesForInterestArea,
1215 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1216 cc::switches::kShowCompositedLayerBorders,
1217 cc::switches::kShowFPSCounter,
1218 cc::switches::kShowLayerAnimationBounds,
1219 cc::switches::kShowNonOccludingRects,
1220 cc::switches::kShowOccludingRects,
1221 cc::switches::kShowPropertyChangedRects,
1222 cc::switches::kShowReplicaScreenSpaceRects,
1223 cc::switches::kShowScreenSpaceRects,
1224 cc::switches::kShowSurfaceDamageRects,
1225 cc::switches::kSlowDownRasterScaleFactor,
1226 cc::switches::kStrictLayerPropertyChangeChecking,
1227 cc::switches::kTopControlsHeight,
1228 cc::switches::kTopControlsHideThreshold,
1229 cc::switches::kTopControlsShowThreshold,
1230 #if defined(ENABLE_PLUGINS)
1231 switches::kEnablePepperTesting,
1232 #endif
1233 #if defined(ENABLE_WEBRTC)
1234 switches::kDisableAudioTrackProcessing,
1235 switches::kDisableWebRtcHWDecoding,
1236 switches::kDisableWebRtcHWEncoding,
1237 switches::kEnableWebRtcHWVp8Encoding,
1238 switches::kEnableWebRtcHWH264Encoding,
1239 #endif
1240 switches::kLowEndDeviceMode,
1241 #if defined(OS_ANDROID)
1242 switches::kDisableGestureRequirementForMediaPlayback,
1243 switches::kDisableWebRTC,
1244 switches::kEnableSpeechRecognition,
1245 switches::kMediaDrmEnableNonCompositing,
1246 switches::kNetworkCountryIso,
1247 switches::kDisableWebAudio,
1248 #endif
1249 #if defined(OS_MACOSX)
1250 // Allow this to be set when invoking the browser and relayed along.
1251 switches::kEnableSandboxLogging,
1252 #endif
1253 #if defined(OS_WIN)
1254 switches::kDisableDirectWrite,
1255 #endif
1256 #if defined(OS_CHROMEOS)
1257 switches::kDisableVaapiAcceleratedVideoEncode,
1258 #endif
1260 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1261 arraysize(kSwitchNames));
1263 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1264 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1265 // Pass kTraceStartup switch to renderer only if startup tracing has not
1266 // finished.
1267 renderer_cmd->AppendSwitchASCII(
1268 switches::kTraceStartup,
1269 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1272 // Disable databases in incognito mode.
1273 if (GetBrowserContext()->IsOffTheRecord() &&
1274 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1275 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1278 // Enforce the extra command line flags for impl-side painting.
1279 if (IsImplSidePaintingEnabled() &&
1280 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1281 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1284 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1285 if (run_renderer_in_process())
1286 return base::Process::Current().handle();
1288 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1289 return base::kNullProcessHandle;
1291 return child_process_launcher_->GetHandle();
1294 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1295 if (run_renderer_in_process())
1296 return false; // Single process mode never shutdown the renderer.
1298 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1299 return false;
1301 if (!child_process_launcher_.get() ||
1302 child_process_launcher_->IsStarting() ||
1303 !GetHandle())
1304 return false; // Render process hasn't started or is probably crashed.
1306 // Test if there's an unload listener.
1307 // NOTE: It's possible that an onunload listener may be installed
1308 // while we're shutting down, so there's a small race here. Given that
1309 // the window is small, it's unlikely that the web page has much
1310 // state that will be lost by not calling its unload handlers properly.
1311 if (!SuddenTerminationAllowed())
1312 return false;
1314 if (worker_ref_count_ != 0) {
1315 if (survive_for_worker_start_time_.is_null())
1316 survive_for_worker_start_time_ = base::TimeTicks::Now();
1317 return false;
1320 // Set this before ProcessDied() so observers can tell if the render process
1321 // died due to fast shutdown versus another cause.
1322 fast_shutdown_started_ = true;
1324 ProcessDied(false /* already_dead */);
1325 return true;
1328 void RenderProcessHostImpl::DumpHandles() {
1329 #if defined(OS_WIN)
1330 Send(new ChildProcessMsg_DumpHandles());
1331 #else
1332 NOTIMPLEMENTED();
1333 #endif
1336 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1337 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1338 if (!channel_) {
1339 if (!is_initialized_) {
1340 queued_messages_.push(msg);
1341 return true;
1342 } else {
1343 delete msg;
1344 return false;
1348 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1349 queued_messages_.push(msg);
1350 return true;
1353 return channel_->Send(msg);
1356 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1357 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1358 // we ignore incoming messages.
1360 if (deleting_soon_ || fast_shutdown_started_)
1361 return false;
1363 mark_child_process_activity_time();
1364 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1365 // Dispatch control messages.
1366 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1367 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1368 OnShutdownRequest)
1369 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1370 OnDumpHandlesDone)
1371 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1372 SuddenTerminationChanged)
1373 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1374 OnUserMetricsRecordAction)
1375 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1376 IPC_MESSAGE_HANDLER_DELAY_REPLY(
1377 ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
1378 OnAllocateGpuMemoryBuffer)
1379 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
1380 OnDeletedGpuMemoryBuffer)
1381 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1382 #if defined(ENABLE_WEBRTC)
1383 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1384 OnRegisterAecDumpConsumer)
1385 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1386 OnUnregisterAecDumpConsumer)
1387 #endif
1388 // Adding single handlers for your service here is fine, but once your
1389 // service needs more than one handler, please extract them into a new
1390 // message filter and add that filter to CreateMessageFilters().
1391 IPC_END_MESSAGE_MAP()
1393 return true;
1396 // Dispatch incoming messages to the appropriate IPC::Listener.
1397 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1398 if (!listener) {
1399 if (msg.is_sync()) {
1400 // The listener has gone away, so we must respond or else the caller will
1401 // hang waiting for a reply.
1402 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1403 reply->set_reply_error();
1404 Send(reply);
1406 return true;
1408 return listener->OnMessageReceived(msg);
1411 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1412 #if defined(IPC_MESSAGE_LOG_ENABLED)
1413 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1414 IPC::Logging::GetInstance()->Enabled()));
1415 #endif
1417 tracked_objects::ThreadData::Status status =
1418 tracked_objects::ThreadData::status();
1419 Send(new ChildProcessMsg_SetProfilerStatus(status));
1422 void RenderProcessHostImpl::OnChannelError() {
1423 ProcessDied(true /* already_dead */);
1426 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1427 // Message de-serialization failed. We consider this a capital crime. Kill the
1428 // renderer if we have one.
1429 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1430 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1431 PROCESS_TYPE_RENDERER);
1432 ReceivedBadMessage();
1435 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1436 return browser_context_;
1439 bool RenderProcessHostImpl::InSameStoragePartition(
1440 StoragePartition* partition) const {
1441 return storage_partition_impl_ == partition;
1444 int RenderProcessHostImpl::GetID() const {
1445 return id_;
1448 bool RenderProcessHostImpl::HasConnection() const {
1449 return channel_.get() != NULL;
1452 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1453 ignore_input_events_ = ignore_input_events;
1456 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1457 return ignore_input_events_;
1460 void RenderProcessHostImpl::Cleanup() {
1461 // If within_process_died_observer_ is true, one of our observers performed an
1462 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1463 // delay the destruction until all of the observer callbacks have been made,
1464 // and guarantee that the RenderProcessHostDestroyed observer callback is
1465 // always the last callback fired.
1466 if (within_process_died_observer_) {
1467 delayed_cleanup_needed_ = true;
1468 return;
1470 delayed_cleanup_needed_ = false;
1472 // Records the time when the process starts surviving for workers for UMA.
1473 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1474 survive_for_worker_start_time_.is_null()) {
1475 survive_for_worker_start_time_ = base::TimeTicks::Now();
1478 // When there are no other owners of this object, we can delete ourselves.
1479 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1480 if (!survive_for_worker_start_time_.is_null()) {
1481 UMA_HISTOGRAM_LONG_TIMES(
1482 "SharedWorker.RendererSurviveForWorkerTime",
1483 base::TimeTicks::Now() - survive_for_worker_start_time_);
1485 // We cannot clean up twice; if this fails, there is an issue with our
1486 // control flow.
1487 DCHECK(!deleting_soon_);
1489 DCHECK_EQ(0, pending_views_);
1490 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1491 observers_,
1492 RenderProcessHostDestroyed(this));
1493 NotificationService::current()->Notify(
1494 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1495 Source<RenderProcessHost>(this),
1496 NotificationService::NoDetails());
1498 #ifndef NDEBUG
1499 is_self_deleted_ = true;
1500 #endif
1501 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1502 deleting_soon_ = true;
1503 // It's important not to wait for the DeleteTask to delete the channel
1504 // proxy. Kill it off now. That way, in case the profile is going away, the
1505 // rest of the objects attached to this RenderProcessHost start going
1506 // away first, since deleting the channel proxy will post a
1507 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1508 channel_.reset();
1509 gpu_message_filter_ = NULL;
1510 message_port_message_filter_ = NULL;
1511 RemoveUserData(kSessionStorageHolderKey);
1513 // Remove ourself from the list of renderer processes so that we can't be
1514 // reused in between now and when the Delete task runs.
1515 UnregisterHost(GetID());
1519 void RenderProcessHostImpl::AddPendingView() {
1520 pending_views_++;
1523 void RenderProcessHostImpl::RemovePendingView() {
1524 DCHECK(pending_views_);
1525 pending_views_--;
1528 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1529 sudden_termination_allowed_ = enabled;
1532 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1533 return sudden_termination_allowed_;
1536 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1537 return base::TimeTicks::Now() - child_process_activity_time_;
1540 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1541 widget_helper_->ResumeRequestsForView(route_id);
1544 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1545 FilterURL(this, empty_allowed, url);
1548 #if defined(ENABLE_WEBRTC)
1549 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1550 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1551 // Enable AEC dump for each registered consumer.
1552 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1553 it != aec_dump_consumers_.end(); ++it) {
1554 EnableAecDumpForId(file, *it);
1558 void RenderProcessHostImpl::DisableAecDump() {
1559 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1560 // Posting on the FILE thread and then replying back on the UI thread is only
1561 // for avoiding races between enable and disable. Nothing is done on the FILE
1562 // thread.
1563 BrowserThread::PostTaskAndReply(
1564 BrowserThread::FILE, FROM_HERE,
1565 base::Bind(&DisableAecDumpOnFileThread),
1566 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1567 weak_factory_.GetWeakPtr()));
1570 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1571 base::Callback<void(const std::string&)> callback) {
1572 webrtc_log_message_callback_ = callback;
1575 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1576 RenderProcessHostImpl::StartRtpDump(
1577 bool incoming,
1578 bool outgoing,
1579 const WebRtcRtpPacketCallback& packet_callback) {
1580 if (!p2p_socket_dispatcher_host_.get())
1581 return WebRtcStopRtpDumpCallback();
1583 BrowserThread::PostTask(BrowserThread::IO,
1584 FROM_HERE,
1585 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1586 p2p_socket_dispatcher_host_,
1587 incoming,
1588 outgoing,
1589 packet_callback));
1591 if (stop_rtp_dump_callback_.is_null()) {
1592 stop_rtp_dump_callback_ =
1593 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1594 p2p_socket_dispatcher_host_);
1596 return stop_rtp_dump_callback_;
1598 #endif
1600 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1601 return channel_.get();
1604 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1605 channel_->AddFilter(filter->GetFilter());
1608 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1609 if (static_cast<size_t>(GetActiveViewCount()) == count)
1610 return FastShutdownIfPossible();
1611 return false;
1614 bool RenderProcessHostImpl::FastShutdownStarted() const {
1615 return fast_shutdown_started_;
1618 // static
1619 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1620 g_all_hosts.Get().AddWithID(host, host_id);
1623 // static
1624 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1625 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1626 if (!host)
1627 return;
1629 g_all_hosts.Get().Remove(host_id);
1631 // Look up the map of site to process for the given browser_context,
1632 // in case we need to remove this process from it. It will be registered
1633 // under any sites it rendered that use process-per-site mode.
1634 SiteProcessMap* map =
1635 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1636 map->RemoveProcess(host);
1639 // static
1640 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1641 bool empty_allowed,
1642 GURL* url) {
1643 ChildProcessSecurityPolicyImpl* policy =
1644 ChildProcessSecurityPolicyImpl::GetInstance();
1646 if (empty_allowed && url->is_empty())
1647 return;
1649 // The browser process should never hear the swappedout:// URL from any
1650 // of the renderer's messages. Check for this in debug builds, but don't
1651 // let it crash a release browser.
1652 DCHECK(GURL(kSwappedOutURL) != *url);
1654 if (!url->is_valid()) {
1655 // Have to use about:blank for the denied case, instead of an empty GURL.
1656 // This is because the browser treats navigation to an empty GURL as a
1657 // navigation to the home page. This is often a privileged page
1658 // (chrome://newtab/) which is exactly what we don't want.
1659 *url = GURL(url::kAboutBlankURL);
1660 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1661 return;
1664 if (url->SchemeIs(url::kAboutScheme)) {
1665 // The renderer treats all URLs in the about: scheme as being about:blank.
1666 // Canonicalize about: URLs to about:blank.
1667 *url = GURL(url::kAboutBlankURL);
1668 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1671 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1672 // cannot swap processes or grant bindings.
1673 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1674 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1676 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1677 // If this renderer is not permitted to request this URL, we invalidate the
1678 // URL. This prevents us from storing the blocked URL and becoming confused
1679 // later.
1680 VLOG(1) << "Blocked URL " << url->spec();
1681 *url = GURL(url::kAboutBlankURL);
1682 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1686 // static
1687 bool RenderProcessHostImpl::IsSuitableHost(
1688 RenderProcessHost* host,
1689 BrowserContext* browser_context,
1690 const GURL& site_url) {
1691 if (run_renderer_in_process())
1692 return true;
1694 if (host->GetBrowserContext() != browser_context)
1695 return false;
1697 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1698 // and non-guest storage gets mixed. In the future, we might consider enabling
1699 // the sharing of guests, in this case this check should be removed and
1700 // InSameStoragePartition should handle the possible sharing.
1701 if (host->IsIsolatedGuest())
1702 return false;
1704 // Check whether the given host and the intended site_url will be using the
1705 // same StoragePartition, since a RenderProcessHost can only support a single
1706 // StoragePartition. This is relevant for packaged apps and isolated sites.
1707 StoragePartition* dest_partition =
1708 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1709 if (!host->InSameStoragePartition(dest_partition))
1710 return false;
1712 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1713 host->GetID()) !=
1714 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1715 browser_context, site_url)) {
1716 return false;
1719 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1722 // static
1723 bool RenderProcessHost::run_renderer_in_process() {
1724 return g_run_renderer_in_process_;
1727 // static
1728 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1729 g_run_renderer_in_process_ = value;
1731 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1732 if (value) {
1733 if (!command_line->HasSwitch(switches::kLang)) {
1734 // Modify the current process' command line to include the browser locale,
1735 // as the renderer expects this flag to be set.
1736 const std::string locale =
1737 GetContentClient()->browser()->GetApplicationLocale();
1738 command_line->AppendSwitchASCII(switches::kLang, locale);
1740 // TODO(piman): we should really send configuration through bools rather
1741 // than by parsing strings, i.e. sending an IPC rather than command line
1742 // args. crbug.com/314909
1743 AppendCompositorCommandLineFlags(command_line);
1747 // static
1748 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1749 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1750 return iterator(g_all_hosts.Pointer());
1753 // static
1754 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1755 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1756 return g_all_hosts.Get().Lookup(render_process_id);
1759 // static
1760 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1761 BrowserContext* browser_context, const GURL& url) {
1762 // Experimental:
1763 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1764 // try to reuse renderer processes when over the limit. (We could allow pages
1765 // from the same site to share, if we knew what the given process was
1766 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1767 // resource exhaustion issues if too many sites are open at once.
1768 const base::CommandLine& command_line =
1769 *base::CommandLine::ForCurrentProcess();
1770 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1771 command_line.HasSwitch(switches::kSitePerProcess))
1772 return false;
1774 if (run_renderer_in_process())
1775 return true;
1777 // NOTE: Sometimes it's necessary to create more render processes than
1778 // GetMaxRendererProcessCount(), for instance when we want to create
1779 // a renderer process for a browser context that has no existing
1780 // renderers. This is OK in moderation, since the
1781 // GetMaxRendererProcessCount() is conservative.
1782 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1783 return true;
1785 return GetContentClient()->browser()->
1786 ShouldTryToUseExistingProcessHost(browser_context, url);
1789 // static
1790 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1791 BrowserContext* browser_context,
1792 const GURL& site_url) {
1793 // First figure out which existing renderers we can use.
1794 std::vector<RenderProcessHost*> suitable_renderers;
1795 suitable_renderers.reserve(g_all_hosts.Get().size());
1797 iterator iter(AllHostsIterator());
1798 while (!iter.IsAtEnd()) {
1799 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1800 RenderProcessHostImpl::IsSuitableHost(
1801 iter.GetCurrentValue(),
1802 browser_context, site_url)) {
1803 suitable_renderers.push_back(iter.GetCurrentValue());
1805 iter.Advance();
1808 // Now pick a random suitable renderer, if we have any.
1809 if (!suitable_renderers.empty()) {
1810 int suitable_count = static_cast<int>(suitable_renderers.size());
1811 int random_index = base::RandInt(0, suitable_count - 1);
1812 return suitable_renderers[random_index];
1815 return NULL;
1818 // static
1819 bool RenderProcessHost::ShouldUseProcessPerSite(
1820 BrowserContext* browser_context,
1821 const GURL& url) {
1822 // Returns true if we should use the process-per-site model. This will be
1823 // the case if the --process-per-site switch is specified, or in
1824 // process-per-site-instance for particular sites (e.g., WebUI).
1825 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1826 const base::CommandLine& command_line =
1827 *base::CommandLine::ForCurrentProcess();
1828 if (command_line.HasSwitch(switches::kProcessPerSite))
1829 return true;
1831 // We want to consolidate particular sites like WebUI even when we are using
1832 // the process-per-tab or process-per-site-instance models.
1833 // Note: DevTools pages have WebUI type but should not reuse the same host.
1834 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1835 browser_context, url) &&
1836 !url.SchemeIs(kChromeDevToolsScheme)) {
1837 return true;
1840 // Otherwise let the content client decide, defaulting to false.
1841 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1842 url);
1845 // static
1846 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1847 BrowserContext* browser_context,
1848 const GURL& url) {
1849 // Look up the map of site to process for the given browser_context.
1850 SiteProcessMap* map =
1851 GetSiteProcessMapForBrowserContext(browser_context);
1853 // See if we have an existing process with appropriate bindings for this site.
1854 // If not, the caller should create a new process and register it.
1855 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1856 .possibly_invalid_spec();
1857 RenderProcessHost* host = map->FindProcess(site);
1858 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
1859 !IsSuitableHost(host, browser_context, url))) {
1860 // The registered process does not have an appropriate set of bindings for
1861 // the url. Remove it from the map so we can register a better one.
1862 RecordAction(
1863 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1864 map->RemoveProcess(host);
1865 host = NULL;
1868 return host;
1871 void RenderProcessHostImpl::RegisterProcessHostForSite(
1872 BrowserContext* browser_context,
1873 RenderProcessHost* process,
1874 const GURL& url) {
1875 // Look up the map of site to process for the given browser_context.
1876 SiteProcessMap* map =
1877 GetSiteProcessMapForBrowserContext(browser_context);
1879 // Only register valid, non-empty sites. Empty or invalid sites will not
1880 // use process-per-site mode. We cannot check whether the process has
1881 // appropriate bindings here, because the bindings have not yet been granted.
1882 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1883 .possibly_invalid_spec();
1884 if (!site.empty())
1885 map->RegisterProcess(site, process);
1888 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1889 // Our child process has died. If we didn't expect it, it's a crash.
1890 // In any case, we need to let everyone know it's gone.
1891 // The OnChannelError notification can fire multiple times due to nested sync
1892 // calls to a renderer. If we don't have a valid channel here it means we
1893 // already handled the error.
1895 // It should not be possible for us to be called re-entrantly.
1896 DCHECK(!within_process_died_observer_);
1898 // It should not be possible for a process death notification to come in while
1899 // we are dying.
1900 DCHECK(!deleting_soon_);
1902 // child_process_launcher_ can be NULL in single process mode or if fast
1903 // termination happened.
1904 int exit_code = 0;
1905 base::TerminationStatus status =
1906 child_process_launcher_.get() ?
1907 child_process_launcher_->GetChildTerminationStatus(already_dead,
1908 &exit_code) :
1909 base::TERMINATION_STATUS_NORMAL_TERMINATION;
1911 RendererClosedDetails details(GetHandle(), status, exit_code);
1912 within_process_died_observer_ = true;
1913 NotificationService::current()->Notify(
1914 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1915 Source<RenderProcessHost>(this),
1916 Details<RendererClosedDetails>(&details));
1917 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1918 observers_,
1919 RenderProcessExited(this, GetHandle(), status, exit_code));
1920 within_process_died_observer_ = false;
1922 mojo_application_host_->WillDestroySoon();
1924 child_process_launcher_.reset();
1925 channel_.reset();
1926 gpu_message_filter_ = NULL;
1927 message_port_message_filter_ = NULL;
1928 RemoveUserData(kSessionStorageHolderKey);
1930 IDMap<IPC::Listener>::iterator iter(&listeners_);
1931 while (!iter.IsAtEnd()) {
1932 iter.GetCurrentValue()->OnMessageReceived(
1933 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1934 static_cast<int>(status),
1935 exit_code));
1936 iter.Advance();
1939 mojo_application_host_.reset(new MojoApplicationHost);
1940 mojo_activation_required_ = false;
1942 // It's possible that one of the calls out to the observers might have caused
1943 // this object to be no longer needed.
1944 if (delayed_cleanup_needed_)
1945 Cleanup();
1947 // This object is not deleted at this point and might be reused later.
1948 // TODO(darin): clean this up
1951 int RenderProcessHostImpl::GetActiveViewCount() {
1952 int num_active_views = 0;
1953 scoped_ptr<RenderWidgetHostIterator> widgets(
1954 RenderWidgetHost::GetRenderWidgetHosts());
1955 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1956 // Count only RenderWidgetHosts in this process.
1957 if (widget->GetProcess()->GetID() == GetID())
1958 num_active_views++;
1960 return num_active_views;
1963 // Frame subscription API for this class is for accelerated composited path
1964 // only. These calls are redirected to GpuMessageFilter.
1965 void RenderProcessHostImpl::BeginFrameSubscription(
1966 int route_id,
1967 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1968 if (!gpu_message_filter_)
1969 return;
1970 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1971 &GpuMessageFilter::BeginFrameSubscription,
1972 gpu_message_filter_,
1973 route_id, base::Passed(&subscriber)));
1976 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1977 if (!gpu_message_filter_)
1978 return;
1979 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1980 &GpuMessageFilter::EndFrameSubscription,
1981 gpu_message_filter_,
1982 route_id));
1985 #if defined(ENABLE_WEBRTC)
1986 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
1987 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1988 if (!webrtc_log_message_callback_.is_null())
1989 webrtc_log_message_callback_.Run(message);
1991 #endif
1993 void RenderProcessHostImpl::ReleaseOnCloseACK(
1994 RenderProcessHost* host,
1995 const SessionStorageNamespaceMap& sessions,
1996 int view_route_id) {
1997 DCHECK(host);
1998 if (sessions.empty())
1999 return;
2000 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2001 (host->GetUserData(kSessionStorageHolderKey));
2002 if (!holder) {
2003 holder = new SessionStorageHolder();
2004 host->SetUserData(
2005 kSessionStorageHolderKey,
2006 holder);
2008 holder->Hold(sessions, view_route_id);
2011 void RenderProcessHostImpl::OnShutdownRequest() {
2012 // Don't shut down if there are active RenderViews, or if there are pending
2013 // RenderViews being swapped back in.
2014 // In single process mode, we never shutdown the renderer.
2015 int num_active_views = GetActiveViewCount();
2016 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2017 return;
2019 // Notify any contents that might have swapped out renderers from this
2020 // process. They should not attempt to swap them back in.
2021 NotificationService::current()->Notify(
2022 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2023 Source<RenderProcessHost>(this),
2024 NotificationService::NoDetails());
2026 mojo_application_host_->WillDestroySoon();
2028 Send(new ChildProcessMsg_Shutdown());
2031 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2032 SetSuddenTerminationAllowed(enabled);
2035 void RenderProcessHostImpl::OnDumpHandlesDone() {
2036 Cleanup();
2039 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2040 // Note: we always set the backgrounded_ value. If the process is NULL
2041 // (and hence hasn't been created yet), we will set the process priority
2042 // later when we create the process.
2043 backgrounded_ = backgrounded;
2044 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2045 return;
2047 // Don't background processes which have active audio streams.
2048 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2049 return;
2051 #if defined(OS_WIN)
2052 // The cbstext.dll loads as a global GetMessage hook in the browser process
2053 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2054 // background thread. If the UI thread invokes this API just when it is
2055 // intercepted the stack is messed up on return from the interceptor
2056 // which causes random crashes in the browser process. Our hack for now
2057 // is to not invoke the SetPriorityClass API if the dll is loaded.
2058 if (GetModuleHandle(L"cbstext.dll"))
2059 return;
2060 #endif // OS_WIN
2062 // Notify the child process of background state.
2063 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2065 #if !defined(OS_WIN)
2066 // Backgrounding may require elevated privileges not available to renderer
2067 // processes, so control backgrounding from the process host.
2069 // Windows Vista+ has a fancy process backgrounding mode that can only be set
2070 // from within the process.
2071 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2072 #endif // !OS_WIN
2075 void RenderProcessHostImpl::OnProcessLaunched() {
2076 // No point doing anything, since this object will be destructed soon. We
2077 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2078 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2079 // properly cleanup.
2080 if (deleting_soon_)
2081 return;
2083 if (child_process_launcher_) {
2084 if (!child_process_launcher_->GetHandle()) {
2085 OnChannelError();
2086 return;
2089 SetBackgrounded(backgrounded_);
2092 // NOTE: This needs to be before sending queued messages because
2093 // ExtensionService uses this notification to initialize the renderer process
2094 // with state that must be there before any JavaScript executes.
2096 // The queued messages contain such things as "navigate". If this notification
2097 // was after, we can end up executing JavaScript before the initialization
2098 // happens.
2099 NotificationService::current()->Notify(
2100 NOTIFICATION_RENDERER_PROCESS_CREATED,
2101 Source<RenderProcessHost>(this),
2102 NotificationService::NoDetails());
2104 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2105 // This way, Mojo can be safely used from the renderer in response to any
2106 // Chrome IPC message.
2107 MaybeActivateMojo();
2109 while (!queued_messages_.empty()) {
2110 Send(queued_messages_.front());
2111 queued_messages_.pop();
2114 #if defined(ENABLE_WEBRTC)
2115 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2116 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2117 #endif
2120 scoped_refptr<AudioRendererHost>
2121 RenderProcessHostImpl::audio_renderer_host() const {
2122 return audio_renderer_host_;
2125 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2126 const std::string& action) {
2127 RecordComputedAction(action);
2130 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2131 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2132 (GetUserData(kSessionStorageHolderKey));
2133 if (!holder)
2134 return;
2135 holder->Release(old_route_id);
2138 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2139 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2142 void RenderProcessHostImpl::OnGpuSwitching() {
2143 // We are updating all widgets including swapped out ones.
2144 scoped_ptr<RenderWidgetHostIterator> widgets(
2145 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2146 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2147 if (!widget->IsRenderView())
2148 continue;
2150 // Skip widgets in other processes.
2151 if (widget->GetProcess()->GetID() != GetID())
2152 continue;
2154 RenderViewHost* rvh = RenderViewHost::From(widget);
2155 rvh->OnWebkitPreferencesChanged();
2159 #if defined(ENABLE_WEBRTC)
2160 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2161 BrowserThread::PostTask(
2162 BrowserThread::UI,
2163 FROM_HERE,
2164 base::Bind(
2165 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2166 weak_factory_.GetWeakPtr(),
2167 id));
2170 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2171 BrowserThread::PostTask(
2172 BrowserThread::UI,
2173 FROM_HERE,
2174 base::Bind(
2175 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2176 weak_factory_.GetWeakPtr(),
2177 id));
2180 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2181 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2182 aec_dump_consumers_.push_back(id);
2183 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2184 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2185 id);
2189 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2190 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2191 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2192 it != aec_dump_consumers_.end(); ++it) {
2193 if (*it == id) {
2194 aec_dump_consumers_.erase(it);
2195 break;
2200 #if defined(OS_WIN)
2201 #define IntToStringType base::IntToString16
2202 #else
2203 #define IntToStringType base::IntToString
2204 #endif
2206 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2207 int id) {
2208 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2209 base::FilePath unique_file =
2210 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2211 .AddExtension(IntToStringType(id));
2212 BrowserThread::PostTaskAndReplyWithResult(
2213 BrowserThread::FILE, FROM_HERE,
2214 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2215 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2216 weak_factory_.GetWeakPtr(),
2217 id));
2220 #undef IntToStringType
2222 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2223 int id,
2224 IPC::PlatformFileForTransit file_for_transit) {
2225 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2226 return;
2227 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2230 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2231 Send(new AecDumpMsg_DisableAecDump());
2233 #endif
2235 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2236 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2237 ++worker_ref_count_;
2240 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2241 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2242 DCHECK_GT(worker_ref_count_, 0);
2243 --worker_ref_count_;
2244 if (worker_ref_count_ == 0)
2245 Cleanup();
2248 void RenderProcessHostImpl::EnsureMojoActivated() {
2249 mojo_activation_required_ = true;
2250 MaybeActivateMojo();
2253 void RenderProcessHostImpl::OnAllocateGpuMemoryBuffer(uint32 width,
2254 uint32 height,
2255 uint32 internalformat,
2256 uint32 usage,
2257 IPC::Message* reply) {
2258 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2259 if (!GpuMemoryBufferImpl::IsFormatValid(internalformat) ||
2260 !GpuMemoryBufferImpl::IsUsageValid(usage)) {
2261 GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
2262 return;
2264 base::CheckedNumeric<int> size = width;
2265 size *= height;
2266 if (!size.IsValid()) {
2267 GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
2268 return;
2271 #if defined(OS_MACOSX)
2272 // TODO(reveman): This should be moved to
2273 // GpuMemoryBufferImpl::AllocateForChildProcess and
2274 // GpuMemoryBufferImplIOSurface. crbug.com/325045, crbug.com/323304
2275 if (GpuMemoryBufferImplIOSurface::IsConfigurationSupported(internalformat,
2276 usage)) {
2277 base::ScopedCFTypeRef<CFMutableDictionaryRef> properties;
2278 properties.reset(
2279 CFDictionaryCreateMutable(kCFAllocatorDefault,
2281 &kCFTypeDictionaryKeyCallBacks,
2282 &kCFTypeDictionaryValueCallBacks));
2283 AddIntegerValue(properties, kIOSurfaceWidth, width);
2284 AddIntegerValue(properties, kIOSurfaceHeight, height);
2285 AddIntegerValue(properties,
2286 kIOSurfaceBytesPerElement,
2287 GpuMemoryBufferImpl::BytesPerPixel(internalformat));
2288 AddIntegerValue(
2289 properties,
2290 kIOSurfacePixelFormat,
2291 GpuMemoryBufferImplIOSurface::PixelFormat(internalformat));
2292 // TODO(reveman): Remove this when using a mach_port_t to transfer
2293 // IOSurface to renderer process. crbug.com/323304
2294 AddBooleanValue(
2295 properties, kIOSurfaceIsGlobal, true);
2297 base::ScopedCFTypeRef<IOSurfaceRef> io_surface(IOSurfaceCreate(properties));
2298 if (io_surface) {
2299 gfx::GpuMemoryBufferHandle handle;
2300 handle.type = gfx::IO_SURFACE_BUFFER;
2301 handle.io_surface_id = IOSurfaceGetID(io_surface);
2303 // TODO(reveman): This makes the assumption that the renderer will
2304 // grab a reference to the surface before sending another message.
2305 // crbug.com/325045
2306 last_io_surface_ = io_surface;
2307 GpuMemoryBufferAllocated(reply, handle);
2308 return;
2311 #endif
2313 #if defined(OS_ANDROID)
2314 // TODO(reveman): This should be moved to
2315 // GpuMemoryBufferImpl::AllocateForChildProcess and
2316 // GpuMemoryBufferImplSurfaceTexture when adding support for out-of-process
2317 // GPU service. crbug.com/368716
2318 if (GpuMemoryBufferImplSurfaceTexture::IsConfigurationSupported(
2319 internalformat, usage)) {
2320 // Each surface texture is associated with a render process id. This allows
2321 // the GPU service and Java Binder IPC to verify that a renderer is not
2322 // trying to use a surface texture it doesn't own.
2323 int surface_texture_id = CompositorImpl::CreateSurfaceTexture(GetID());
2324 if (surface_texture_id != -1) {
2325 gfx::GpuMemoryBufferHandle handle;
2326 handle.type = gfx::SURFACE_TEXTURE_BUFFER;
2327 handle.surface_texture_id =
2328 gfx::SurfaceTextureId(surface_texture_id, GetID());
2329 GpuMemoryBufferAllocated(reply, handle);
2330 return;
2333 #endif
2335 GpuMemoryBufferImpl::AllocateForChildProcess(
2336 gfx::Size(width, height),
2337 internalformat,
2338 usage,
2339 GetHandle(),
2340 GetID(),
2341 base::Bind(&RenderProcessHostImpl::GpuMemoryBufferAllocated,
2342 weak_factory_.GetWeakPtr(),
2343 reply));
2346 void RenderProcessHostImpl::GpuMemoryBufferAllocated(
2347 IPC::Message* reply,
2348 const gfx::GpuMemoryBufferHandle& handle) {
2349 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2350 ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer::WriteReplyParams(reply,
2351 handle);
2352 Send(reply);
2355 void RenderProcessHostImpl::OnDeletedGpuMemoryBuffer(
2356 gfx::GpuMemoryBufferType type,
2357 const gfx::GpuMemoryBufferId& id) {
2358 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2359 GpuMemoryBufferImpl::DeletedByChildProcess(type, id, GetHandle());
2362 } // namespace content