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"
15 #include <utility> // for pair<>
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/rand_util.h"
31 #include "base/stl_util.h"
32 #include "base/strings/string_util.h"
33 #include "base/supports_user_data.h"
34 #include "base/sys_info.h"
35 #include "base/threading/thread.h"
36 #include "base/threading/thread_restrictions.h"
37 #include "base/tracked_objects.h"
38 #include "cc/base/switches.h"
39 #include "content/browser/appcache/appcache_dispatcher_host.h"
40 #include "content/browser/appcache/chrome_appcache_service.h"
41 #include "content/browser/browser_main.h"
42 #include "content/browser/browser_main_loop.h"
43 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
44 #include "content/browser/child_process_security_policy_impl.h"
45 #include "content/browser/device_sensors/device_motion_message_filter.h"
46 #include "content/browser/device_sensors/device_orientation_message_filter.h"
47 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
48 #include "content/browser/dom_storage/dom_storage_message_filter.h"
49 #include "content/browser/download/mhtml_generation_manager.h"
50 #include "content/browser/fileapi/chrome_blob_storage_context.h"
51 #include "content/browser/fileapi/fileapi_message_filter.h"
52 #include "content/browser/frame_host/render_frame_message_filter.h"
53 #include "content/browser/gpu/compositor_util.h"
54 #include "content/browser/gpu/gpu_data_manager_impl.h"
55 #include "content/browser/gpu/gpu_process_host.h"
56 #include "content/browser/gpu/shader_disk_cache.h"
57 #include "content/browser/histogram_message_filter.h"
58 #include "content/browser/indexed_db/indexed_db_context_impl.h"
59 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
60 #include "content/browser/loader/resource_message_filter.h"
61 #include "content/browser/loader/resource_scheduler_filter.h"
62 #include "content/browser/media/capture/audio_mirroring_manager.h"
63 #include "content/browser/media/media_internals.h"
64 #include "content/browser/message_port_message_filter.h"
65 #include "content/browser/mime_registry_message_filter.h"
66 #include "content/browser/mojo/mojo_application_host.h"
67 #include "content/browser/plugin_service_impl.h"
68 #include "content/browser/profiler_message_filter.h"
69 #include "content/browser/push_messaging_message_filter.h"
70 #include "content/browser/quota_dispatcher_host.h"
71 #include "content/browser/renderer_host/clipboard_message_filter.h"
72 #include "content/browser/renderer_host/database_message_filter.h"
73 #include "content/browser/renderer_host/file_utilities_message_filter.h"
74 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
75 #include "content/browser/renderer_host/gpu_message_filter.h"
76 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
77 #include "content/browser/renderer_host/media/audio_renderer_host.h"
78 #include "content/browser/renderer_host/media/device_request_message_filter.h"
79 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
80 #include "content/browser/renderer_host/media/midi_dispatcher_host.h"
81 #include "content/browser/renderer_host/media/midi_host.h"
82 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
83 #include "content/browser/renderer_host/media/video_capture_host.h"
84 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
85 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
86 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
87 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
88 #include "content/browser/renderer_host/render_message_filter.h"
89 #include "content/browser/renderer_host/render_view_host_delegate.h"
90 #include "content/browser/renderer_host/render_view_host_impl.h"
91 #include "content/browser/renderer_host/render_widget_helper.h"
92 #include "content/browser/renderer_host/render_widget_host_impl.h"
93 #include "content/browser/renderer_host/socket_stream_dispatcher_host.h"
94 #include "content/browser/renderer_host/text_input_client_message_filter.h"
95 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
96 #include "content/browser/resolve_proxy_msg_helper.h"
97 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host.h"
98 #include "content/browser/service_worker/service_worker_context_wrapper.h"
99 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
100 #include "content/browser/shared_worker/shared_worker_message_filter.h"
101 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
102 #include "content/browser/storage_partition_impl.h"
103 #include "content/browser/streams/stream_context.h"
104 #include "content/browser/tracing/trace_message_filter.h"
105 #include "content/browser/vibration/vibration_message_filter.h"
106 #include "content/browser/webui/web_ui_controller_factory_registry.h"
107 #include "content/browser/worker_host/worker_message_filter.h"
108 #include "content/browser/worker_host/worker_storage_partition.h"
109 #include "content/common/child_process_host_impl.h"
110 #include "content/common/child_process_messages.h"
111 #include "content/common/content_switches_internal.h"
112 #include "content/common/gpu/gpu_messages.h"
113 #include "content/common/mojo/mojo_messages.h"
114 #include "content/common/resource_messages.h"
115 #include "content/common/view_messages.h"
116 #include "content/public/browser/browser_context.h"
117 #include "content/public/browser/content_browser_client.h"
118 #include "content/public/browser/notification_service.h"
119 #include "content/public/browser/notification_types.h"
120 #include "content/public/browser/render_process_host_factory.h"
121 #include "content/public/browser/render_process_host_observer.h"
122 #include "content/public/browser/render_widget_host.h"
123 #include "content/public/browser/render_widget_host_iterator.h"
124 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
125 #include "content/public/browser/resource_context.h"
126 #include "content/public/browser/user_metrics.h"
127 #include "content/public/browser/worker_service.h"
128 #include "content/public/common/content_constants.h"
129 #include "content/public/common/content_switches.h"
130 #include "content/public/common/process_type.h"
131 #include "content/public/common/result_codes.h"
132 #include "content/public/common/sandboxed_process_launcher_delegate.h"
133 #include "content/public/common/url_constants.h"
134 #include "gpu/command_buffer/service/gpu_switches.h"
135 #include "ipc/ipc_channel.h"
136 #include "ipc/ipc_logging.h"
137 #include "ipc/ipc_switches.h"
138 #include "media/base/media_switches.h"
139 #include "mojo/common/common_type_converters.h"
140 #include "mojo/public/cpp/bindings/allocation_scope.h"
141 #include "net/url_request/url_request_context_getter.h"
142 #include "ppapi/shared_impl/ppapi_switches.h"
143 #include "third_party/skia/include/core/SkBitmap.h"
144 #include "ui/base/ui_base_switches.h"
145 #include "ui/events/event_switches.h"
146 #include "ui/gfx/switches.h"
147 #include "ui/gl/gl_switches.h"
148 #include "ui/native_theme/native_theme_switches.h"
149 #include "webkit/browser/fileapi/sandbox_file_system_backend.h"
150 #include "webkit/common/resource_type.h"
152 #if defined(OS_ANDROID)
153 #include "content/browser/media/android/browser_demuxer_android.h"
157 #include "base/win/scoped_com_initializer.h"
158 #include "content/common/font_cache_dispatcher_win.h"
159 #include "content/common/sandbox_win.h"
162 #if defined(ENABLE_WEBRTC)
163 #include "content/browser/media/webrtc_internals.h"
164 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
165 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
166 #include "content/common/media/media_stream_messages.h"
169 extern bool g_exited_main_message_loop;
171 static const char* kSiteProcessMapKeyName = "content_site_process_map";
176 void CacheShaderInfo(int32 id, base::FilePath path) {
177 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
180 void RemoveShaderInfo(int32 id) {
181 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
184 net::URLRequestContext* GetRequestContext(
185 scoped_refptr<net::URLRequestContextGetter> request_context,
186 scoped_refptr<net::URLRequestContextGetter> media_request_context,
187 ResourceType::Type resource_type) {
188 // If the request has resource type of ResourceType::MEDIA, we use a request
189 // context specific to media for handling it because these resources have
190 // specific needs for caching.
191 if (resource_type == ResourceType::MEDIA)
192 return media_request_context->GetURLRequestContext();
193 return request_context->GetURLRequestContext();
197 ResourceContext* resource_context,
198 scoped_refptr<net::URLRequestContextGetter> request_context,
199 scoped_refptr<net::URLRequestContextGetter> media_request_context,
200 const ResourceHostMsg_Request& request,
201 ResourceContext** resource_context_out,
202 net::URLRequestContext** request_context_out) {
203 *resource_context_out = resource_context;
204 *request_context_out =
205 GetRequestContext(request_context, media_request_context,
206 request.resource_type);
209 #if defined(ENABLE_WEBRTC)
210 // Creates a file used for diagnostic echo canceller recordings for handing
211 // over to the renderer.
212 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
213 base::FilePath file_path,
214 base::ProcessHandle process) {
215 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
216 base::File dump_file(file_path,
217 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
218 if (!dump_file.IsValid()) {
219 VLOG(1) << "Could not open AEC dump file, error=" <<
220 dump_file.error_details();
221 return IPC::InvalidPlatformFileForTransit();
223 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
226 // Does nothing. Just to avoid races between enable and disable.
227 void DisableAecDumpOnFileThread() {
228 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
232 // the global list of all renderer processes
233 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
234 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
236 // Map of site to process, to ensure we only have one RenderProcessHost per
237 // site in process-per-site mode. Each map is specific to a BrowserContext.
238 class SiteProcessMap : public base::SupportsUserData::Data {
240 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
243 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
244 map_[site] = process;
247 RenderProcessHost* FindProcess(const std::string& site) {
248 SiteToProcessMap::iterator i = map_.find(site);
254 void RemoveProcess(RenderProcessHost* host) {
255 // Find all instances of this process in the map, then separately remove
257 std::set<std::string> sites;
258 for (SiteToProcessMap::const_iterator i = map_.begin();
261 if (i->second == host)
262 sites.insert(i->first);
264 for (std::set<std::string>::iterator i = sites.begin();
267 SiteToProcessMap::iterator iter = map_.find(*i);
268 if (iter != map_.end()) {
269 DCHECK_EQ(iter->second, host);
276 SiteToProcessMap map_;
279 // Find the SiteProcessMap specific to the given context.
280 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
282 SiteProcessMap* map = static_cast<SiteProcessMap*>(
283 context->GetUserData(kSiteProcessMapKeyName));
285 map = new SiteProcessMap();
286 context->SetUserData(kSiteProcessMapKeyName, map);
291 // NOTE: changes to this class need to be reviewed by the security team.
292 class RendererSandboxedProcessLauncherDelegate
293 : public content::SandboxedProcessLauncherDelegate {
295 RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
296 #if defined(OS_POSIX)
297 : ipc_fd_(channel->TakeClientFileDescriptor())
301 virtual ~RendererSandboxedProcessLauncherDelegate() {}
304 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
306 AddBaseHandleClosePolicy(policy);
307 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
310 #elif defined(OS_POSIX)
311 virtual bool ShouldUseZygote() OVERRIDE {
312 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
313 CommandLine::StringType renderer_prefix =
314 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
315 return renderer_prefix.empty();
317 virtual int GetIpcFd() OVERRIDE {
323 #if defined(OS_POSIX)
330 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
332 base::MessageLoop* g_in_process_thread;
335 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
336 return g_in_process_thread;
339 // Stores the maximum number of renderer processes the content module can
341 static size_t g_max_renderer_count_override = 0;
344 size_t RenderProcessHost::GetMaxRendererProcessCount() {
345 if (g_max_renderer_count_override)
346 return g_max_renderer_count_override;
348 // Defines the maximum number of renderer processes according to the
349 // amount of installed memory as reported by the OS. The calculation
350 // assumes that you want the renderers to use half of the installed
351 // RAM and assuming that each WebContents uses ~40MB.
352 // If you modify this assumption, you need to adjust the
353 // ThirtyFourTabs test to match the expected number of processes.
355 // With the given amounts of installed memory below on a 32-bit CPU,
356 // the maximum renderer count will roughly be as follows:
362 // 16384 MB -> 82 (kMaxRendererProcessCount)
364 static size_t max_count = 0;
366 const size_t kEstimatedWebContentsMemoryUsage =
367 #if defined(ARCH_CPU_64_BITS)
372 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
373 max_count /= kEstimatedWebContentsMemoryUsage;
375 const size_t kMinRendererProcessCount = 3;
376 max_count = std::max(max_count, kMinRendererProcessCount);
377 max_count = std::min(max_count, kMaxRendererProcessCount);
383 bool g_run_renderer_in_process_ = false;
386 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
387 g_max_renderer_count_override = count;
390 RenderProcessHostImpl::RenderProcessHostImpl(
391 BrowserContext* browser_context,
392 StoragePartitionImpl* storage_partition_impl,
394 : fast_shutdown_started_(false),
395 deleting_soon_(false),
397 is_self_deleted_(false),
400 mojo_activation_required_(false),
403 is_initialized_(false),
404 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
405 browser_context_(browser_context),
406 storage_partition_impl_(storage_partition_impl),
407 sudden_termination_allowed_(true),
408 ignore_input_events_(false),
410 gpu_observer_registered_(false),
411 delayed_cleanup_needed_(false),
412 within_process_died_observer_(false),
413 power_monitor_broadcaster_(this),
414 geolocation_dispatcher_host_(NULL),
415 screen_orientation_dispatcher_host_(NULL),
416 worker_ref_count_(0),
417 weak_factory_(this) {
418 widget_helper_ = new RenderWidgetHelper();
420 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
422 CHECK(!g_exited_main_message_loop);
423 RegisterHost(GetID(), this);
424 g_all_hosts.Get().set_check_on_null_data(true);
425 // Initialize |child_process_activity_time_| to a reasonable value.
426 mark_child_process_activity_time();
428 if (!GetBrowserContext()->IsOffTheRecord() &&
429 !CommandLine::ForCurrentProcess()->HasSwitch(
430 switches::kDisableGpuShaderDiskCache)) {
431 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
432 base::Bind(&CacheShaderInfo, GetID(),
433 storage_partition_impl_->GetPath()));
436 // Note: When we create the RenderProcessHostImpl, it's technically
437 // backgrounded, because it has no visible listeners. But the process
438 // doesn't actually exist yet, so we'll Background it later, after
443 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
444 DCHECK(g_run_renderer_in_process_);
446 switch (g_all_hosts.Pointer()->size()) {
450 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
451 AllHostsIterator().GetCurrentValue());
452 FOR_EACH_OBSERVER(RenderProcessHostObserver,
454 RenderProcessHostDestroyed(host));
456 host->is_self_deleted_ = true;
462 NOTREACHED() << "There should be only one RenderProcessHost when running "
467 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
468 RendererMainThreadFactoryFunction create) {
469 g_renderer_main_thread_factory = create;
472 RenderProcessHostImpl::~RenderProcessHostImpl() {
474 DCHECK(is_self_deleted_)
475 << "RenderProcessHostImpl is destroyed by something other than itself";
478 // Make sure to clean up the in-process renderer before the channel, otherwise
479 // it may still run and have its IPCs fail, causing asserts.
480 in_process_renderer_.reset();
482 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
484 if (gpu_observer_registered_) {
485 GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
486 gpu_observer_registered_ = false;
489 // We may have some unsent messages at this point, but that's OK.
491 while (!queued_messages_.empty()) {
492 delete queued_messages_.front();
493 queued_messages_.pop();
496 UnregisterHost(GetID());
498 if (!CommandLine::ForCurrentProcess()->HasSwitch(
499 switches::kDisableGpuShaderDiskCache)) {
500 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
501 base::Bind(&RemoveShaderInfo, GetID()));
505 void RenderProcessHostImpl::EnableSendQueue() {
506 is_initialized_ = false;
509 bool RenderProcessHostImpl::Init() {
510 // calling Init() more than once does nothing, this makes it more convenient
511 // for the view host which may not be sure in some cases
515 CommandLine::StringType renderer_prefix;
516 #if defined(OS_POSIX)
517 // A command prefix is something prepended to the command line of the spawned
518 // process. It is supported only on POSIX systems.
519 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
521 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
522 #endif // defined(OS_POSIX)
524 #if defined(OS_LINUX)
525 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
526 ChildProcessHost::CHILD_NORMAL;
528 int flags = ChildProcessHost::CHILD_NORMAL;
531 // Find the renderer before creating the channel so if this fails early we
532 // return without creating the channel.
533 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
534 if (renderer_path.empty())
537 // Setup the IPC channel.
538 const std::string channel_id =
539 IPC::Channel::GenerateVerifiedChannelID(std::string());
541 new IPC::ChannelProxy(channel_id,
542 IPC::Channel::MODE_SERVER,
544 BrowserThread::GetMessageLoopProxyForThread(
545 BrowserThread::IO).get()));
547 // Setup the Mojo channel.
548 mojo_application_host_.reset(new MojoApplicationHost());
549 mojo_application_host_->Init();
551 // Call the embedder first so that their IPC filters have priority.
552 GetContentClient()->browser()->RenderProcessWillLaunch(this);
554 CreateMessageFilters();
556 if (run_renderer_in_process()) {
557 DCHECK(g_renderer_main_thread_factory);
558 // Crank up a thread and run the initialization there. With the way that
559 // messages flow between the browser and renderer, this thread is required
560 // to prevent a deadlock in single-process mode. Since the primordial
561 // thread in the renderer process runs the WebKit code and can sometimes
562 // make blocking calls to the UI thread (i.e. this thread), they need to run
563 // on separate threads.
564 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
566 base::Thread::Options options;
567 #if defined(OS_WIN) && !defined(OS_MACOSX)
568 // In-process plugins require this to be a UI message loop.
569 options.message_loop_type = base::MessageLoop::TYPE_UI;
571 // We can't have multiple UI loops on Linux and Android, so we don't support
572 // in-process plugins.
573 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
575 in_process_renderer_->StartWithOptions(options);
577 g_in_process_thread = in_process_renderer_->message_loop();
579 OnProcessLaunched(); // Fake a callback that the process is ready.
581 // Build command line for renderer. We call AppendRendererCommandLine()
582 // first so the process type argument will appear first.
583 CommandLine* cmd_line = new CommandLine(renderer_path);
584 if (!renderer_prefix.empty())
585 cmd_line->PrependWrapper(renderer_prefix);
586 AppendRendererCommandLine(cmd_line);
587 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
589 // Spawn the child process asynchronously to avoid blocking the UI thread.
590 // As long as there's no renderer prefix, we can use the zygote process
592 child_process_launcher_.reset(new ChildProcessLauncher(
593 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
598 fast_shutdown_started_ = false;
601 if (!gpu_observer_registered_) {
602 gpu_observer_registered_ = true;
603 GpuDataManagerImpl::GetInstance()->AddObserver(this);
606 is_initialized_ = true;
610 void RenderProcessHostImpl::MaybeActivateMojo() {
611 // TODO(darin): Following security review, we can unconditionally initialize
612 // Mojo in all renderers. We will then be able to directly call Activate()
613 // from OnProcessLaunched.
614 if (!mojo_activation_required_)
615 return; // Waiting on someone to require Mojo.
618 return; // Waiting on renderer startup.
620 if (!mojo_application_host_->did_activate())
621 mojo_application_host_->Activate(this, GetHandle());
624 void RenderProcessHostImpl::CreateMessageFilters() {
625 DCHECK_CURRENTLY_ON(BrowserThread::UI);
626 AddFilter(new ResourceSchedulerFilter(GetID()));
627 MediaInternals* media_internals = MediaInternals::GetInstance();
628 media::AudioManager* audio_manager =
629 BrowserMainLoop::GetInstance()->audio_manager();
630 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
632 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
633 new BrowserPluginMessageFilter(GetID(), IsGuest()));
634 AddFilter(bp_message_filter.get());
636 scoped_refptr<RenderMessageFilter> render_message_filter(
637 new RenderMessageFilter(
640 #if defined(ENABLE_PLUGINS)
641 PluginServiceImpl::GetInstance(),
646 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
647 widget_helper_.get(),
650 storage_partition_impl_->GetDOMStorageContext()));
651 AddFilter(render_message_filter.get());
653 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
654 BrowserContext* browser_context = GetBrowserContext();
655 ResourceContext* resource_context = browser_context->GetResourceContext();
657 scoped_refptr<net::URLRequestContextGetter> request_context(
658 browser_context->GetRequestContextForRenderProcess(GetID()));
659 scoped_refptr<net::URLRequestContextGetter> media_request_context(
660 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
662 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
663 base::Bind(&GetContexts, browser_context->GetResourceContext(),
664 request_context, media_request_context));
666 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
667 GetID(), PROCESS_TYPE_RENDERER,
668 storage_partition_impl_->GetAppCacheService(),
669 ChromeBlobStorageContext::GetFor(browser_context),
670 storage_partition_impl_->GetFileSystemContext(),
671 storage_partition_impl_->GetServiceWorkerContext(),
672 get_contexts_callback);
674 AddFilter(resource_message_filter);
675 MediaStreamManager* media_stream_manager =
676 BrowserMainLoop::GetInstance()->media_stream_manager();
677 AddFilter(new AudioInputRendererHost(
679 media_stream_manager,
680 BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
681 BrowserMainLoop::GetInstance()->user_input_monitor()));
682 // The AudioRendererHost needs to be available for lookup, so it's
683 // stashed in a member variable.
684 audio_renderer_host_ = new AudioRendererHost(
687 BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
689 media_stream_manager);
690 AddFilter(audio_renderer_host_);
692 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
693 AddFilter(new MidiDispatcherHost(GetID(), browser_context));
694 AddFilter(new VideoCaptureHost(media_stream_manager));
695 AddFilter(new AppCacheDispatcherHost(
696 storage_partition_impl_->GetAppCacheService(),
698 AddFilter(new ClipboardMessageFilter);
699 AddFilter(new DOMStorageMessageFilter(
701 storage_partition_impl_->GetDOMStorageContext()));
702 AddFilter(new IndexedDBDispatcherHost(
704 storage_partition_impl_->GetURLRequestContext(),
705 storage_partition_impl_->GetIndexedDBContext(),
706 ChromeBlobStorageContext::GetFor(browser_context)));
708 geolocation_dispatcher_host_ = new GeolocationDispatcherHost(
709 GetID(), browser_context->GetGeolocationPermissionContext());
710 AddFilter(geolocation_dispatcher_host_);
711 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
712 AddFilter(gpu_message_filter_);
713 #if defined(ENABLE_WEBRTC)
714 AddFilter(new WebRTCIdentityServiceHost(
715 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
716 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
717 AddFilter(peer_connection_tracker_host_.get());
718 AddFilter(new MediaStreamDispatcherHost(
720 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
721 media_stream_manager));
722 AddFilter(new DeviceRequestMessageFilter(
723 resource_context, media_stream_manager, GetID()));
724 AddFilter(new MediaStreamTrackMetricsHost());
726 #if defined(ENABLE_PLUGINS)
727 AddFilter(new PepperRendererConnection(GetID()));
729 AddFilter(new SpeechRecognitionDispatcherHost(
730 IsGuest(), GetID(), storage_partition_impl_->GetURLRequestContext()));
731 AddFilter(new FileAPIMessageFilter(
733 storage_partition_impl_->GetURLRequestContext(),
734 storage_partition_impl_->GetFileSystemContext(),
735 ChromeBlobStorageContext::GetFor(browser_context),
736 StreamContext::GetFor(browser_context)));
737 AddFilter(new FileUtilitiesMessageFilter(GetID()));
738 AddFilter(new MimeRegistryMessageFilter());
739 AddFilter(new DatabaseMessageFilter(
740 storage_partition_impl_->GetDatabaseTracker()));
741 #if defined(OS_MACOSX)
742 AddFilter(new TextInputClientMessageFilter(GetID()));
743 #elif defined(OS_WIN)
744 // The FontCacheDispatcher is required only when we're using GDI rendering.
745 if (!ShouldUseDirectWrite())
746 channel_->AddFilter(new FontCacheDispatcher());
747 #elif defined(OS_ANDROID)
748 browser_demuxer_android_ = new BrowserDemuxerAndroid();
749 AddFilter(browser_demuxer_android_);
752 SocketStreamDispatcherHost::GetRequestContextCallback
753 request_context_callback(
754 base::Bind(&GetRequestContext, request_context,
755 media_request_context));
757 SocketStreamDispatcherHost* socket_stream_dispatcher_host =
758 new SocketStreamDispatcherHost(
759 GetID(), request_context_callback, resource_context);
760 AddFilter(socket_stream_dispatcher_host);
762 WebSocketDispatcherHost::GetRequestContextCallback
763 websocket_request_context_callback(
764 base::Bind(&GetRequestContext, request_context,
765 media_request_context, ResourceType::SUB_RESOURCE));
768 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
770 message_port_message_filter_ = new MessagePortMessageFilter(
771 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
772 base::Unretained(widget_helper_.get())));
773 AddFilter(message_port_message_filter_);
775 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
776 new ServiceWorkerDispatcherHost(GetID(), message_port_message_filter_);
777 service_worker_filter->Init(
778 storage_partition_impl_->GetServiceWorkerContext());
779 AddFilter(service_worker_filter);
781 // If "--enable-embedded-shared-worker" is set, we use
782 // SharedWorkerMessageFilter in stead of WorkerMessageFilter.
783 if (WorkerService::EmbeddedSharedWorkerEnabled()) {
784 AddFilter(new SharedWorkerMessageFilter(
787 WorkerStoragePartition(
788 storage_partition_impl_->GetURLRequestContext(),
789 storage_partition_impl_->GetMediaURLRequestContext(),
790 storage_partition_impl_->GetAppCacheService(),
791 storage_partition_impl_->GetQuotaManager(),
792 storage_partition_impl_->GetFileSystemContext(),
793 storage_partition_impl_->GetDatabaseTracker(),
794 storage_partition_impl_->GetIndexedDBContext(),
795 storage_partition_impl_->GetServiceWorkerContext()),
796 message_port_message_filter_));
798 AddFilter(new WorkerMessageFilter(
801 WorkerStoragePartition(
802 storage_partition_impl_->GetURLRequestContext(),
803 storage_partition_impl_->GetMediaURLRequestContext(),
804 storage_partition_impl_->GetAppCacheService(),
805 storage_partition_impl_->GetQuotaManager(),
806 storage_partition_impl_->GetFileSystemContext(),
807 storage_partition_impl_->GetDatabaseTracker(),
808 storage_partition_impl_->GetIndexedDBContext(),
809 storage_partition_impl_->GetServiceWorkerContext()),
810 message_port_message_filter_));
813 #if defined(ENABLE_WEBRTC)
814 AddFilter(new P2PSocketDispatcherHost(
816 browser_context->GetRequestContextForRenderProcess(GetID())));
819 AddFilter(new TraceMessageFilter());
820 AddFilter(new ResolveProxyMsgHelper(
821 browser_context->GetRequestContextForRenderProcess(GetID())));
822 AddFilter(new QuotaDispatcherHost(
824 storage_partition_impl_->GetQuotaManager(),
825 GetContentClient()->browser()->CreateQuotaPermissionContext()));
826 AddFilter(new GamepadBrowserMessageFilter());
827 AddFilter(new DeviceMotionMessageFilter());
828 AddFilter(new DeviceOrientationMessageFilter());
829 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
830 AddFilter(new HistogramMessageFilter());
831 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
832 if (CommandLine::ForCurrentProcess()->HasSwitch(
833 switches::kEnableMemoryBenchmarking))
834 AddFilter(new MemoryBenchmarkMessageFilter());
836 AddFilter(new VibrationMessageFilter());
837 screen_orientation_dispatcher_host_ = new ScreenOrientationDispatcherHost();
838 AddFilter(screen_orientation_dispatcher_host_);
839 AddFilter(new PushMessagingMessageFilter());
842 int RenderProcessHostImpl::GetNextRoutingID() {
843 return widget_helper_->GetNextRoutingID();
847 void RenderProcessHostImpl::ResumeDeferredNavigation(
848 const GlobalRequestID& request_id) {
849 widget_helper_->ResumeDeferredNavigation(request_id);
852 void RenderProcessHostImpl::NotifyTimezoneChange() {
853 Send(new ViewMsg_TimezoneChange());
856 ScreenOrientationDispatcherHost* RenderProcessHostImpl
857 ::GetScreenOrientationDispatcherHost() {
858 return screen_orientation_dispatcher_host_;
861 void RenderProcessHostImpl::AddRoute(
863 IPC::Listener* listener) {
864 listeners_.AddWithID(listener, routing_id);
867 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
868 DCHECK(listeners_.Lookup(routing_id) != NULL);
869 listeners_.Remove(routing_id);
872 // Dump the handle table if handle auditing is enabled.
873 const CommandLine& browser_command_line =
874 *CommandLine::ForCurrentProcess();
875 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
876 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
879 // We wait to close the channels until the child process has finished
880 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
884 // Keep the one renderer thread around forever in single process mode.
885 if (!run_renderer_in_process())
889 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
890 observers_.AddObserver(observer);
893 void RenderProcessHostImpl::RemoveObserver(
894 RenderProcessHostObserver* observer) {
895 observers_.RemoveObserver(observer);
898 bool RenderProcessHostImpl::WaitForBackingStoreMsg(
899 int render_widget_id,
900 const base::TimeDelta& max_delay,
902 // The post task to this thread with the process id could be in queue, and we
903 // don't want to dispatch a message before then since it will need the handle.
904 if (child_process_launcher_.get() && child_process_launcher_->IsStarting())
907 return widget_helper_->WaitForBackingStoreMsg(render_widget_id,
911 void RenderProcessHostImpl::ReceivedBadMessage() {
912 CommandLine* command_line = CommandLine::ForCurrentProcess();
913 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
916 if (run_renderer_in_process()) {
917 // In single process mode it is better if we don't suicide but just
921 // We kill the renderer but don't include a NOTREACHED, because we want the
922 // browser to try to survive when it gets illegal messages from the renderer.
923 base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
927 void RenderProcessHostImpl::WidgetRestored() {
928 // Verify we were properly backgrounded.
929 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
931 SetBackgrounded(false);
934 void RenderProcessHostImpl::WidgetHidden() {
935 // On startup, the browser will call Hide
939 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
941 DCHECK_GE(visible_widgets_, 0);
942 if (visible_widgets_ == 0) {
943 DCHECK(!backgrounded_);
944 SetBackgrounded(true);
948 int RenderProcessHostImpl::VisibleWidgetCount() const {
949 return visible_widgets_;
952 bool RenderProcessHostImpl::IsGuest() const {
956 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
957 return storage_partition_impl_;
960 static void AppendCompositorCommandLineFlags(CommandLine* command_line) {
961 if (IsPinchVirtualViewportEnabled())
962 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
964 if (IsThreadedCompositingEnabled())
965 command_line->AppendSwitch(switches::kEnableThreadedCompositing);
967 if (IsDelegatedRendererEnabled())
968 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
970 if (IsImplSidePaintingEnabled())
971 command_line->AppendSwitch(switches::kEnableImplSidePainting);
973 if (content::IsGpuRasterizationEnabled())
974 command_line->AppendSwitch(switches::kEnableGpuRasterization);
976 if (content::IsForceGpuRasterizationEnabled())
977 command_line->AppendSwitch(switches::kForceGpuRasterization);
979 // Appending disable-gpu-feature switches due to software rendering list.
980 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
981 DCHECK(gpu_data_manager);
982 gpu_data_manager->AppendRendererCommandLine(command_line);
985 void RenderProcessHostImpl::AppendRendererCommandLine(
986 CommandLine* command_line) const {
987 // Pass the process type first, so it shows first in process listings.
988 command_line->AppendSwitchASCII(switches::kProcessType,
989 switches::kRendererProcess);
991 // Now send any options from our own command line we want to propagate.
992 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
993 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
995 // Pass on the browser locale.
996 const std::string locale =
997 GetContentClient()->browser()->GetApplicationLocale();
998 command_line->AppendSwitchASCII(switches::kLang, locale);
1000 // If we run base::FieldTrials, we want to pass to their state to the
1001 // renderer so that it can act in accordance with each state, or record
1002 // histograms relating to the base::FieldTrial states.
1003 std::string field_trial_states;
1004 base::FieldTrialList::StatesToString(&field_trial_states);
1005 if (!field_trial_states.empty()) {
1006 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1007 field_trial_states);
1010 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1011 command_line, GetID());
1013 if (content::IsPinchToZoomEnabled())
1014 command_line->AppendSwitch(switches::kEnablePinch);
1016 AppendCompositorCommandLineFlags(command_line);
1019 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1020 const CommandLine& browser_cmd,
1021 CommandLine* renderer_cmd) const {
1022 // Propagate the following switches to the renderer command line (along
1023 // with any associated values) if present in the browser command line.
1024 static const char* const kSwitchNames[] = {
1025 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1026 switches::kAllowLoopbackInPeerConnection,
1027 switches::kAudioBufferSize,
1028 switches::kAuditAllHandles,
1029 switches::kAuditHandles,
1030 switches::kBlinkPlatformLogChannels,
1031 switches::kBlockCrossSiteDocuments,
1032 switches::kDefaultTileWidth,
1033 switches::kDefaultTileHeight,
1034 switches::kDisable3DAPIs,
1035 switches::kDisableAcceleratedFixedRootBackground,
1036 switches::kDisableAcceleratedVideoDecode,
1037 switches::kDisableApplicationCache,
1038 switches::kDisableBreakpad,
1039 switches::kDisableCompositingForFixedPosition,
1040 switches::kDisableCompositingForTransition,
1041 switches::kDisableDatabases,
1042 switches::kDisableDesktopNotifications,
1043 switches::kDisableDirectNPAPIRequests,
1044 switches::kDisableDistanceFieldText,
1045 switches::kDisableFastTextAutosizing,
1046 switches::kDisableFileSystem,
1047 switches::kDisableFiltersOverIPC,
1048 switches::kDisableGpuCompositing,
1049 switches::kDisableGpuVsync,
1050 switches::kDisableLowResTiling,
1051 switches::kDisableHistogramCustomizer,
1052 switches::kDisableLCDText,
1053 switches::kDisableLayerSquashing,
1054 switches::kDisableLocalStorage,
1055 switches::kDisableLogging,
1056 switches::kDisableMediaSource,
1057 switches::kDisableOverlayScrollbar,
1058 switches::kDisablePinch,
1059 switches::kDisablePrefixedEncryptedMedia,
1060 switches::kDisableRepaintAfterLayout,
1061 switches::kDisableSeccompFilterSandbox,
1062 switches::kDisableSessionStorage,
1063 switches::kDisableSharedWorkers,
1064 switches::kDisableTouchAdjustment,
1065 switches::kDisableTouchDragDrop,
1066 switches::kDisableTouchEditing,
1067 switches::kDisableUniversalAcceleratedOverflowScroll,
1068 switches::kDisableZeroCopy,
1069 switches::kDomAutomationController,
1070 switches::kEnableAcceleratedFixedRootBackground,
1071 switches::kEnableAcceleratedOverflowScroll,
1072 switches::kEnableAccessibilityLogging,
1073 switches::kEnableADTSStreamParser,
1074 switches::kEnableBeginFrameScheduling,
1075 switches::kEnableBleedingEdgeRenderingFastPaths,
1076 switches::kEnableCompositingForFixedPosition,
1077 switches::kEnableCompositingForTransition,
1078 switches::kEnableDeferredImageDecoding,
1079 switches::kEnableDistanceFieldText,
1080 switches::kEnableEncryptedMedia,
1081 switches::kEnableExperimentalCanvasFeatures,
1082 switches::kEnableExperimentalWebPlatformFeatures,
1083 switches::kEnableFastTextAutosizing,
1084 switches::kEnableGPUClientLogging,
1085 switches::kEnableGpuClientTracing,
1086 switches::kEnableGPUServiceLogging,
1087 switches::kEnableHighDpiCompositingForFixedPosition,
1088 switches::kEnableLowResTiling,
1089 switches::kEnableInbandTextTracks,
1090 switches::kEnableLCDText,
1091 switches::kEnableLayerSquashing,
1092 switches::kEnableLogging,
1093 switches::kEnableMemoryBenchmarking,
1094 switches::kEnableOneCopy,
1095 switches::kEnableOverlayFullscreenVideo,
1096 switches::kEnableOverlayScrollbar,
1097 switches::kEnableOverscrollNotifications,
1098 switches::kEnablePinch,
1099 switches::kEnablePreciseMemoryInfo,
1100 switches::kEnablePreparsedJsCaching,
1101 switches::kEnableRepaintAfterLayout,
1102 switches::kEnableSeccompFilterSandbox,
1103 switches::kEnableServiceWorker,
1104 switches::kEnableSkiaBenchmarking,
1105 switches::kEnableSpeechSynthesis,
1106 switches::kEnableStatsTable,
1107 switches::kEnableStrictSiteIsolation,
1108 switches::kEnableTargetedStyleRecalc,
1109 switches::kEnableUniversalAcceleratedOverflowScroll,
1110 switches::kEnableTouchDragDrop,
1111 switches::kEnableTouchEditing,
1112 switches::kEnableViewport,
1113 switches::kEnableViewportMeta,
1114 switches::kMainFrameResizesAreOrientationChanges,
1115 switches::kEnableVtune,
1116 switches::kEnableWebAnimationsSVG,
1117 switches::kEnableWebGLDraftExtensions,
1118 switches::kEnableWebMIDI,
1119 switches::kEnableZeroCopy,
1120 switches::kForceCompositingMode,
1121 switches::kForceDeviceScaleFactor,
1122 switches::kFullMemoryCrashReport,
1123 switches::kJavaScriptFlags,
1124 switches::kLoggingLevel,
1125 switches::kMaxUntiledLayerWidth,
1126 switches::kMaxUntiledLayerHeight,
1127 switches::kMemoryMetrics,
1128 switches::kNoReferrers,
1129 switches::kNoSandbox,
1130 switches::kNumRasterThreads,
1131 switches::kPpapiInProcess,
1132 switches::kProfilerTiming,
1133 switches::kReduceSecurityForTesting,
1134 switches::kRegisterPepperPlugins,
1135 switches::kRendererAssertTest,
1136 switches::kRendererStartupDialog,
1137 switches::kShowPaintRects,
1138 switches::kSitePerProcess,
1139 switches::kStatsCollectionController,
1140 switches::kTestSandbox,
1141 switches::kTestType,
1142 switches::kTouchEvents,
1143 switches::kTraceToConsole,
1144 switches::kUseDiscardableMemory,
1145 // This flag needs to be propagated to the renderer process for
1146 // --in-process-webgl.
1148 switches::kUseMobileUserAgent,
1150 switches::kVideoThreads,
1152 switches::kWebGLCommandBufferSizeKb,
1153 // Please keep these in alphabetical order. Compositor switches here should
1154 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1155 cc::switches::kCompositeToMailbox,
1156 cc::switches::kDisableCompositedAntialiasing,
1157 cc::switches::kDisableCompositorTouchHitTesting,
1158 cc::switches::kDisableMainFrameBeforeActivation,
1159 cc::switches::kDisableMainFrameBeforeDraw,
1160 cc::switches::kDisableThreadedAnimation,
1161 cc::switches::kEnableGpuBenchmarking,
1162 cc::switches::kEnableMainFrameBeforeActivation,
1163 cc::switches::kEnableTopControlsPositionCalculation,
1164 cc::switches::kMaxTilesForInterestArea,
1165 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1166 cc::switches::kShowCompositedLayerBorders,
1167 cc::switches::kShowFPSCounter,
1168 cc::switches::kShowLayerAnimationBounds,
1169 cc::switches::kShowNonOccludingRects,
1170 cc::switches::kShowOccludingRects,
1171 cc::switches::kShowPropertyChangedRects,
1172 cc::switches::kShowReplicaScreenSpaceRects,
1173 cc::switches::kShowScreenSpaceRects,
1174 cc::switches::kShowSurfaceDamageRects,
1175 cc::switches::kSlowDownRasterScaleFactor,
1176 cc::switches::kStrictLayerPropertyChangeChecking,
1177 cc::switches::kTopControlsHeight,
1178 cc::switches::kTopControlsHideThreshold,
1179 cc::switches::kTopControlsShowThreshold,
1180 #if defined(ENABLE_PLUGINS)
1181 switches::kEnablePepperTesting,
1183 #if defined(ENABLE_WEBRTC)
1184 switches::kEnableAudioTrackProcessing,
1185 switches::kDisableDeviceEnumeration,
1186 switches::kDisableWebRtcHWDecoding,
1187 switches::kDisableWebRtcHWEncoding,
1188 switches::kEnableWebRtcHWVp8Encoding,
1189 switches::kEnableWebRtcTcpServerSocket,
1191 #if defined(OS_ANDROID)
1192 switches::kDisableGestureRequirementForMediaPlayback,
1193 switches::kDisableLowEndDeviceMode,
1194 switches::kDisableWebRTC,
1195 switches::kEnableLowEndDeviceMode,
1196 switches::kEnableSpeechRecognition,
1197 switches::kMediaDrmEnableNonCompositing,
1198 switches::kNetworkCountryIso,
1199 switches::kDisableWebAudio,
1201 #if defined(OS_MACOSX)
1202 // Allow this to be set when invoking the browser and relayed along.
1203 switches::kEnableSandboxLogging,
1206 switches::kEnableDirectWrite,
1207 switches::kEnableHighResolutionTime,
1208 switches::kHighDPISupport,
1211 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1212 arraysize(kSwitchNames));
1214 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1215 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1216 // Pass kTraceStartup switch to renderer only if startup tracing has not
1218 renderer_cmd->AppendSwitchASCII(
1219 switches::kTraceStartup,
1220 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1223 // Disable databases in incognito mode.
1224 if (GetBrowserContext()->IsOffTheRecord() &&
1225 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1226 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1227 #if defined(OS_ANDROID)
1228 renderer_cmd->AppendSwitch(switches::kDisableMediaHistoryLogging);
1232 // Enforce the extra command line flags for impl-side painting.
1233 if (IsImplSidePaintingEnabled() &&
1234 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1235 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1238 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1239 if (run_renderer_in_process())
1240 return base::Process::Current().handle();
1242 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1243 return base::kNullProcessHandle;
1245 return child_process_launcher_->GetHandle();
1248 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1249 if (run_renderer_in_process())
1250 return false; // Single process mode never shutdown the renderer.
1252 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1255 if (!child_process_launcher_.get() ||
1256 child_process_launcher_->IsStarting() ||
1258 return false; // Render process hasn't started or is probably crashed.
1260 // Test if there's an unload listener.
1261 // NOTE: It's possible that an onunload listener may be installed
1262 // while we're shutting down, so there's a small race here. Given that
1263 // the window is small, it's unlikely that the web page has much
1264 // state that will be lost by not calling its unload handlers properly.
1265 if (!SuddenTerminationAllowed())
1268 if (worker_ref_count_ != 0) {
1269 if (survive_for_worker_start_time_.is_null())
1270 survive_for_worker_start_time_ = base::TimeTicks::Now();
1274 // Set this before ProcessDied() so observers can tell if the render process
1275 // died due to fast shutdown versus another cause.
1276 fast_shutdown_started_ = true;
1278 ProcessDied(false /* already_dead */);
1282 void RenderProcessHostImpl::DumpHandles() {
1284 Send(new ChildProcessMsg_DumpHandles());
1290 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1291 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1293 if (!is_initialized_) {
1294 queued_messages_.push(msg);
1302 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1303 queued_messages_.push(msg);
1307 return channel_->Send(msg);
1310 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1311 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1312 // we ignore incoming messages.
1314 if (deleting_soon_ || fast_shutdown_started_)
1317 mark_child_process_activity_time();
1318 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1319 // Dispatch control messages.
1320 bool msg_is_ok = true;
1321 IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1322 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1324 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1326 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1327 SuddenTerminationChanged)
1328 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1329 OnUserMetricsRecordAction)
1330 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1331 // Adding single handlers for your service here is fine, but once your
1332 // service needs more than one handler, please extract them into a new
1333 // message filter and add that filter to CreateMessageFilters().
1334 IPC_END_MESSAGE_MAP_EX()
1337 // The message had a handler, but its de-serialization failed.
1338 // We consider this a capital crime. Kill the renderer if we have one.
1339 LOG(ERROR) << "bad message " << msg.type() << " terminating renderer.";
1340 RecordAction(base::UserMetricsAction("BadMessageTerminate_BRPH"));
1341 ReceivedBadMessage();
1346 // Dispatch incoming messages to the appropriate IPC::Listener.
1347 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1349 if (msg.is_sync()) {
1350 // The listener has gone away, so we must respond or else the caller will
1351 // hang waiting for a reply.
1352 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1353 reply->set_reply_error();
1357 // If this is a SwapBuffers, we need to ack it if we're not going to handle
1358 // it so that the GPU process doesn't get stuck in unscheduled state.
1359 bool msg_is_ok = true;
1360 IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1361 IPC_MESSAGE_HANDLER(ViewHostMsg_CompositorSurfaceBuffersSwapped,
1362 OnCompositorSurfaceBuffersSwappedNoHost)
1363 IPC_END_MESSAGE_MAP_EX()
1366 return listener->OnMessageReceived(msg);
1369 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1370 #if defined(IPC_MESSAGE_LOG_ENABLED)
1371 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1372 IPC::Logging::GetInstance()->Enabled()));
1375 tracked_objects::ThreadData::Status status =
1376 tracked_objects::ThreadData::status();
1377 Send(new ChildProcessMsg_SetProfilerStatus(status));
1380 void RenderProcessHostImpl::OnChannelError() {
1381 ProcessDied(true /* already_dead */);
1384 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1385 return browser_context_;
1388 bool RenderProcessHostImpl::InSameStoragePartition(
1389 StoragePartition* partition) const {
1390 return storage_partition_impl_ == partition;
1393 int RenderProcessHostImpl::GetID() const {
1397 bool RenderProcessHostImpl::HasConnection() const {
1398 return channel_.get() != NULL;
1401 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1402 ignore_input_events_ = ignore_input_events;
1405 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1406 return ignore_input_events_;
1409 void RenderProcessHostImpl::Cleanup() {
1410 // If within_process_died_observer_ is true, one of our observers performed an
1411 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1412 // delay the destruction until all of the observer callbacks have been made,
1413 // and guarantee that the RenderProcessHostDestroyed observer callback is
1414 // always the last callback fired.
1415 if (within_process_died_observer_) {
1416 delayed_cleanup_needed_ = true;
1419 delayed_cleanup_needed_ = false;
1421 // Records the time when the process starts surviving for workers for UMA.
1422 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1423 survive_for_worker_start_time_.is_null()) {
1424 survive_for_worker_start_time_ = base::TimeTicks::Now();
1427 // When there are no other owners of this object, we can delete ourselves.
1428 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1429 if (!survive_for_worker_start_time_.is_null()) {
1430 UMA_HISTOGRAM_LONG_TIMES(
1431 "SharedWorker.RendererSurviveForWorkerTime",
1432 base::TimeTicks::Now() - survive_for_worker_start_time_);
1434 // We cannot clean up twice; if this fails, there is an issue with our
1436 DCHECK(!deleting_soon_);
1438 DCHECK_EQ(0, pending_views_);
1439 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1441 RenderProcessHostDestroyed(this));
1442 NotificationService::current()->Notify(
1443 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1444 Source<RenderProcessHost>(this),
1445 NotificationService::NoDetails());
1448 is_self_deleted_ = true;
1450 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1451 deleting_soon_ = true;
1452 // It's important not to wait for the DeleteTask to delete the channel
1453 // proxy. Kill it off now. That way, in case the profile is going away, the
1454 // rest of the objects attached to this RenderProcessHost start going
1455 // away first, since deleting the channel proxy will post a
1456 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1458 gpu_message_filter_ = NULL;
1459 message_port_message_filter_ = NULL;
1460 geolocation_dispatcher_host_ = NULL;
1461 screen_orientation_dispatcher_host_ = NULL;
1463 // Remove ourself from the list of renderer processes so that we can't be
1464 // reused in between now and when the Delete task runs.
1465 UnregisterHost(GetID());
1469 void RenderProcessHostImpl::AddPendingView() {
1473 void RenderProcessHostImpl::RemovePendingView() {
1474 DCHECK(pending_views_);
1478 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1479 sudden_termination_allowed_ = enabled;
1482 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1483 return sudden_termination_allowed_;
1486 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1487 return base::TimeTicks::Now() - child_process_activity_time_;
1490 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1491 widget_helper_->ResumeRequestsForView(route_id);
1494 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1495 FilterURL(this, empty_allowed, url);
1498 #if defined(ENABLE_WEBRTC)
1499 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1500 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1501 BrowserThread::PostTaskAndReplyWithResult(
1502 BrowserThread::FILE, FROM_HERE,
1503 base::Bind(&CreateAecDumpFileForProcess, file, GetHandle()),
1504 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
1505 weak_factory_.GetWeakPtr()));
1508 void RenderProcessHostImpl::DisableAecDump() {
1509 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1510 // Posting on the FILE thread and then replying back on the UI thread is only
1511 // for avoiding races between enable and disable. Nothing is done on the FILE
1513 BrowserThread::PostTaskAndReply(
1514 BrowserThread::FILE, FROM_HERE,
1515 base::Bind(&DisableAecDumpOnFileThread),
1516 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1517 weak_factory_.GetWeakPtr()));
1520 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1521 base::Callback<void(const std::string&)> callback) {
1522 webrtc_log_message_callback_ = callback;
1526 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1527 return channel_.get();
1530 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1531 channel_->AddFilter(filter->GetFilter());
1534 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1535 if (static_cast<size_t>(GetActiveViewCount()) == count)
1536 return FastShutdownIfPossible();
1540 bool RenderProcessHostImpl::FastShutdownStarted() const {
1541 return fast_shutdown_started_;
1545 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1546 g_all_hosts.Get().AddWithID(host, host_id);
1550 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1551 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1555 g_all_hosts.Get().Remove(host_id);
1557 // Look up the map of site to process for the given browser_context,
1558 // in case we need to remove this process from it. It will be registered
1559 // under any sites it rendered that use process-per-site mode.
1560 SiteProcessMap* map =
1561 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1562 map->RemoveProcess(host);
1566 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1569 ChildProcessSecurityPolicyImpl* policy =
1570 ChildProcessSecurityPolicyImpl::GetInstance();
1572 if (empty_allowed && url->is_empty())
1575 // The browser process should never hear the swappedout:// URL from any
1576 // of the renderer's messages. Check for this in debug builds, but don't
1577 // let it crash a release browser.
1578 DCHECK(GURL(kSwappedOutURL) != *url);
1580 if (!url->is_valid()) {
1581 // Have to use about:blank for the denied case, instead of an empty GURL.
1582 // This is because the browser treats navigation to an empty GURL as a
1583 // navigation to the home page. This is often a privileged page
1584 // (chrome://newtab/) which is exactly what we don't want.
1585 *url = GURL(kAboutBlankURL);
1586 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1590 if (url->SchemeIs(kAboutScheme)) {
1591 // The renderer treats all URLs in the about: scheme as being about:blank.
1592 // Canonicalize about: URLs to about:blank.
1593 *url = GURL(kAboutBlankURL);
1594 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1597 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1598 // cannot swap processes or grant bindings.
1599 bool non_web_url_in_guest = rph->IsGuest() &&
1600 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1602 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1603 // If this renderer is not permitted to request this URL, we invalidate the
1604 // URL. This prevents us from storing the blocked URL and becoming confused
1606 VLOG(1) << "Blocked URL " << url->spec();
1607 *url = GURL(kAboutBlankURL);
1608 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1613 bool RenderProcessHostImpl::IsSuitableHost(
1614 RenderProcessHost* host,
1615 BrowserContext* browser_context,
1616 const GURL& site_url) {
1617 if (run_renderer_in_process())
1620 if (host->GetBrowserContext() != browser_context)
1623 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1624 // and non-guest storage gets mixed. In the future, we might consider enabling
1625 // the sharing of guests, in this case this check should be removed and
1626 // InSameStoragePartition should handle the possible sharing.
1627 if (host->IsGuest())
1630 // Check whether the given host and the intended site_url will be using the
1631 // same StoragePartition, since a RenderProcessHost can only support a single
1632 // StoragePartition. This is relevant for packaged apps and isolated sites.
1633 StoragePartition* dest_partition =
1634 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1635 if (!host->InSameStoragePartition(dest_partition))
1638 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1640 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1641 browser_context, site_url)) {
1645 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1649 bool RenderProcessHost::run_renderer_in_process() {
1650 return g_run_renderer_in_process_;
1654 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1655 g_run_renderer_in_process_ = value;
1657 CommandLine* command_line = CommandLine::ForCurrentProcess();
1659 if (!command_line->HasSwitch(switches::kLang)) {
1660 // Modify the current process' command line to include the browser locale,
1661 // as the renderer expects this flag to be set.
1662 const std::string locale =
1663 GetContentClient()->browser()->GetApplicationLocale();
1664 command_line->AppendSwitchASCII(switches::kLang, locale);
1666 // TODO(piman): we should really send configuration through bools rather
1667 // than by parsing strings, i.e. sending an IPC rather than command line
1668 // args. crbug.com/314909
1669 AppendCompositorCommandLineFlags(command_line);
1674 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1675 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1676 return iterator(g_all_hosts.Pointer());
1680 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1681 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1682 return g_all_hosts.Get().Lookup(render_process_id);
1686 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1687 BrowserContext* browser_context, const GURL& url) {
1689 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1690 // try to reuse renderer processes when over the limit. (We could allow pages
1691 // from the same site to share, if we knew what the given process was
1692 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1693 // resource exhaustion issues if too many sites are open at once.
1694 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1695 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1696 command_line.HasSwitch(switches::kSitePerProcess))
1699 if (run_renderer_in_process())
1702 // NOTE: Sometimes it's necessary to create more render processes than
1703 // GetMaxRendererProcessCount(), for instance when we want to create
1704 // a renderer process for a browser context that has no existing
1705 // renderers. This is OK in moderation, since the
1706 // GetMaxRendererProcessCount() is conservative.
1707 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1710 return GetContentClient()->browser()->
1711 ShouldTryToUseExistingProcessHost(browser_context, url);
1715 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1716 BrowserContext* browser_context,
1717 const GURL& site_url) {
1718 // First figure out which existing renderers we can use.
1719 std::vector<RenderProcessHost*> suitable_renderers;
1720 suitable_renderers.reserve(g_all_hosts.Get().size());
1722 iterator iter(AllHostsIterator());
1723 while (!iter.IsAtEnd()) {
1724 if (RenderProcessHostImpl::IsSuitableHost(
1725 iter.GetCurrentValue(),
1726 browser_context, site_url))
1727 suitable_renderers.push_back(iter.GetCurrentValue());
1732 // Now pick a random suitable renderer, if we have any.
1733 if (!suitable_renderers.empty()) {
1734 int suitable_count = static_cast<int>(suitable_renderers.size());
1735 int random_index = base::RandInt(0, suitable_count - 1);
1736 return suitable_renderers[random_index];
1743 bool RenderProcessHost::ShouldUseProcessPerSite(
1744 BrowserContext* browser_context,
1746 // Returns true if we should use the process-per-site model. This will be
1747 // the case if the --process-per-site switch is specified, or in
1748 // process-per-site-instance for particular sites (e.g., WebUI).
1749 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1750 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1751 if (command_line.HasSwitch(switches::kProcessPerSite))
1754 // We want to consolidate particular sites like WebUI even when we are using
1755 // the process-per-tab or process-per-site-instance models.
1756 // Note: DevTools pages have WebUI type but should not reuse the same host.
1757 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1758 browser_context, url) &&
1759 !url.SchemeIs(kChromeDevToolsScheme)) {
1763 // Otherwise let the content client decide, defaulting to false.
1764 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1769 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1770 BrowserContext* browser_context,
1772 // Look up the map of site to process for the given browser_context.
1773 SiteProcessMap* map =
1774 GetSiteProcessMapForBrowserContext(browser_context);
1776 // See if we have an existing process with appropriate bindings for this site.
1777 // If not, the caller should create a new process and register it.
1778 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1779 .possibly_invalid_spec();
1780 RenderProcessHost* host = map->FindProcess(site);
1781 if (host && !IsSuitableHost(host, browser_context, url)) {
1782 // The registered process does not have an appropriate set of bindings for
1783 // the url. Remove it from the map so we can register a better one.
1785 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1786 map->RemoveProcess(host);
1793 void RenderProcessHostImpl::RegisterProcessHostForSite(
1794 BrowserContext* browser_context,
1795 RenderProcessHost* process,
1797 // Look up the map of site to process for the given browser_context.
1798 SiteProcessMap* map =
1799 GetSiteProcessMapForBrowserContext(browser_context);
1801 // Only register valid, non-empty sites. Empty or invalid sites will not
1802 // use process-per-site mode. We cannot check whether the process has
1803 // appropriate bindings here, because the bindings have not yet been granted.
1804 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1805 .possibly_invalid_spec();
1807 map->RegisterProcess(site, process);
1810 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1811 // Our child process has died. If we didn't expect it, it's a crash.
1812 // In any case, we need to let everyone know it's gone.
1813 // The OnChannelError notification can fire multiple times due to nested sync
1814 // calls to a renderer. If we don't have a valid channel here it means we
1815 // already handled the error.
1817 // It should not be possible for us to be called re-entrantly.
1818 DCHECK(!within_process_died_observer_);
1820 // It should not be possible for a process death notification to come in while
1822 DCHECK(!deleting_soon_);
1824 // child_process_launcher_ can be NULL in single process mode or if fast
1825 // termination happened.
1827 base::TerminationStatus status =
1828 child_process_launcher_.get() ?
1829 child_process_launcher_->GetChildTerminationStatus(already_dead,
1831 base::TERMINATION_STATUS_NORMAL_TERMINATION;
1833 RendererClosedDetails details(GetHandle(), status, exit_code);
1834 within_process_died_observer_ = true;
1835 NotificationService::current()->Notify(
1836 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1837 Source<RenderProcessHost>(this),
1838 Details<RendererClosedDetails>(&details));
1839 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1841 RenderProcessExited(this, GetHandle(), status, exit_code));
1842 within_process_died_observer_ = false;
1844 child_process_launcher_.reset();
1846 gpu_message_filter_ = NULL;
1847 message_port_message_filter_ = NULL;
1848 geolocation_dispatcher_host_ = NULL;
1849 screen_orientation_dispatcher_host_ = NULL;
1851 IDMap<IPC::Listener>::iterator iter(&listeners_);
1852 while (!iter.IsAtEnd()) {
1853 iter.GetCurrentValue()->OnMessageReceived(
1854 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1855 static_cast<int>(status),
1860 mojo_application_host_.reset();
1862 // It's possible that one of the calls out to the observers might have caused
1863 // this object to be no longer needed.
1864 if (delayed_cleanup_needed_)
1867 // This object is not deleted at this point and might be reused later.
1868 // TODO(darin): clean this up
1871 int RenderProcessHostImpl::GetActiveViewCount() {
1872 int num_active_views = 0;
1873 scoped_ptr<RenderWidgetHostIterator> widgets(
1874 RenderWidgetHost::GetRenderWidgetHosts());
1875 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1876 // Count only RenderWidgetHosts in this process.
1877 if (widget->GetProcess()->GetID() == GetID())
1880 return num_active_views;
1883 // Frame subscription API for this class is for accelerated composited path
1884 // only. These calls are redirected to GpuMessageFilter.
1885 void RenderProcessHostImpl::BeginFrameSubscription(
1887 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1888 if (!gpu_message_filter_)
1890 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1891 &GpuMessageFilter::BeginFrameSubscription,
1892 gpu_message_filter_,
1893 route_id, base::Passed(&subscriber)));
1896 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1897 if (!gpu_message_filter_)
1899 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1900 &GpuMessageFilter::EndFrameSubscription,
1901 gpu_message_filter_,
1905 #if defined(ENABLE_WEBRTC)
1906 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
1907 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1908 if (!webrtc_log_message_callback_.is_null())
1909 webrtc_log_message_callback_.Run(message);
1913 scoped_refptr<ScreenOrientationDispatcherHost>
1914 RenderProcessHostImpl::screen_orientation_dispatcher_host() const {
1915 return make_scoped_refptr(screen_orientation_dispatcher_host_);
1918 void RenderProcessHostImpl::OnShutdownRequest() {
1919 // Don't shut down if there are active RenderViews, or if there are pending
1920 // RenderViews being swapped back in.
1921 // In single process mode, we never shutdown the renderer.
1922 int num_active_views = GetActiveViewCount();
1923 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
1926 // Notify any contents that might have swapped out renderers from this
1927 // process. They should not attempt to swap them back in.
1928 NotificationService::current()->Notify(
1929 NOTIFICATION_RENDERER_PROCESS_CLOSING,
1930 Source<RenderProcessHost>(this),
1931 NotificationService::NoDetails());
1933 Send(new ChildProcessMsg_Shutdown());
1936 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
1937 SetSuddenTerminationAllowed(enabled);
1940 void RenderProcessHostImpl::OnDumpHandlesDone() {
1944 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
1945 // Note: we always set the backgrounded_ value. If the process is NULL
1946 // (and hence hasn't been created yet), we will set the process priority
1947 // later when we create the process.
1948 backgrounded_ = backgrounded;
1949 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1953 // The cbstext.dll loads as a global GetMessage hook in the browser process
1954 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
1955 // background thread. If the UI thread invokes this API just when it is
1956 // intercepted the stack is messed up on return from the interceptor
1957 // which causes random crashes in the browser process. Our hack for now
1958 // is to not invoke the SetPriorityClass API if the dll is loaded.
1959 if (GetModuleHandle(L"cbstext.dll"))
1963 child_process_launcher_->SetProcessBackgrounded(backgrounded);
1966 void RenderProcessHostImpl::OnProcessLaunched() {
1967 // No point doing anything, since this object will be destructed soon. We
1968 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
1969 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
1970 // properly cleanup.
1974 if (child_process_launcher_) {
1975 if (!child_process_launcher_->GetHandle()) {
1980 child_process_launcher_->SetProcessBackgrounded(backgrounded_);
1983 // NOTE: This needs to be before sending queued messages because
1984 // ExtensionService uses this notification to initialize the renderer process
1985 // with state that must be there before any JavaScript executes.
1987 // The queued messages contain such things as "navigate". If this notification
1988 // was after, we can end up executing JavaScript before the initialization
1990 NotificationService::current()->Notify(
1991 NOTIFICATION_RENDERER_PROCESS_CREATED,
1992 Source<RenderProcessHost>(this),
1993 NotificationService::NoDetails());
1995 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
1996 // This way, Mojo can be safely used from the renderer in response to any
1997 // Chrome IPC message.
1998 MaybeActivateMojo();
2000 while (!queued_messages_.empty()) {
2001 Send(queued_messages_.front());
2002 queued_messages_.pop();
2005 #if defined(ENABLE_WEBRTC)
2006 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2007 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2011 scoped_refptr<AudioRendererHost>
2012 RenderProcessHostImpl::audio_renderer_host() const {
2013 return audio_renderer_host_;
2016 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2017 const std::string& action) {
2018 RecordComputedAction(action);
2021 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2022 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2025 void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost(
2026 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params) {
2027 TRACE_EVENT0("renderer_host",
2028 "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost");
2029 if (!ui::LatencyInfo::Verify(params.latency_info,
2030 "ViewHostMsg_CompositorSurfaceBuffersSwapped"))
2032 AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
2033 ack_params.sync_point = 0;
2034 RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id,
2035 params.gpu_process_host_id,
2039 void RenderProcessHostImpl::OnGpuSwitching() {
2040 // We are updating all widgets including swapped out ones.
2041 scoped_ptr<RenderWidgetHostIterator> widgets(
2042 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2043 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2044 if (!widget->IsRenderView())
2047 // Skip widgets in other processes.
2048 if (widget->GetProcess()->GetID() != GetID())
2051 RenderViewHost* rvh = RenderViewHost::From(widget);
2052 rvh->UpdateWebkitPreferences(rvh->GetWebkitPreferences());
2056 #if defined(ENABLE_WEBRTC)
2057 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2058 IPC::PlatformFileForTransit file_for_transit) {
2059 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2061 Send(new MediaStreamMsg_EnableAecDump(file_for_transit));
2064 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2065 Send(new MediaStreamMsg_DisableAecDump());
2069 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2070 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2071 ++worker_ref_count_;
2074 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2075 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2076 DCHECK_GT(worker_ref_count_, 0);
2077 --worker_ref_count_;
2078 if (worker_ref_count_ == 0)
2082 void RenderProcessHostImpl::ConnectTo(
2083 const base::StringPiece& service_name,
2084 mojo::ScopedMessagePipeHandle handle) {
2085 mojo_activation_required_ = true;
2086 MaybeActivateMojo();
2088 mojo::AllocationScope scope;
2089 mojo_application_host_->shell_client()->AcceptConnection(service_name,
2093 } // namespace content