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"
14 #include "base/base_switches.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/callback.h"
18 #include "base/command_line.h"
19 #include "base/files/file.h"
20 #include "base/lazy_instance.h"
21 #include "base/logging.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/metrics/histogram.h"
24 #include "base/process/process_handle.h"
25 #include "base/profiler/scoped_tracker.h"
26 #include "base/rand_util.h"
27 #include "base/stl_util.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_util.h"
30 #include "base/supports_user_data.h"
31 #include "base/sys_info.h"
32 #include "base/threading/thread.h"
33 #include "base/threading/thread_restrictions.h"
34 #include "base/trace_event/trace_event.h"
35 #include "base/tracked_objects.h"
36 #include "cc/base/switches.h"
37 #include "content/browser/appcache/appcache_dispatcher_host.h"
38 #include "content/browser/appcache/chrome_appcache_service.h"
39 #include "content/browser/bad_message.h"
40 #include "content/browser/bluetooth/bluetooth_dispatcher_host.h"
41 #include "content/browser/browser_child_process_host_impl.h"
42 #include "content/browser/browser_main.h"
43 #include "content/browser/browser_main_loop.h"
44 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
45 #include "content/browser/child_process_security_policy_impl.h"
46 #include "content/browser/device_sensors/device_light_message_filter.h"
47 #include "content/browser/device_sensors/device_motion_message_filter.h"
48 #include "content/browser/device_sensors/device_orientation_message_filter.h"
49 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
50 #include "content/browser/dom_storage/dom_storage_message_filter.h"
51 #include "content/browser/download/mhtml_generation_manager.h"
52 #include "content/browser/fileapi/chrome_blob_storage_context.h"
53 #include "content/browser/fileapi/fileapi_message_filter.h"
54 #include "content/browser/frame_host/render_frame_message_filter.h"
55 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
56 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
57 #include "content/browser/gpu/compositor_util.h"
58 #include "content/browser/gpu/gpu_data_manager_impl.h"
59 #include "content/browser/gpu/gpu_process_host.h"
60 #include "content/browser/gpu/shader_disk_cache.h"
61 #include "content/browser/histogram_message_filter.h"
62 #include "content/browser/indexed_db/indexed_db_context_impl.h"
63 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
64 #include "content/browser/loader/resource_message_filter.h"
65 #include "content/browser/loader/resource_scheduler_filter.h"
66 #include "content/browser/media/capture/audio_mirroring_manager.h"
67 #include "content/browser/media/media_internals.h"
68 #include "content/browser/media/midi_host.h"
69 #include "content/browser/message_port_message_filter.h"
70 #include "content/browser/mime_registry_message_filter.h"
71 #include "content/browser/mojo/mojo_application_host.h"
72 #include "content/browser/navigator_connect/navigator_connect_dispatcher_host.h"
73 #include "content/browser/notifications/notification_message_filter.h"
74 #include "content/browser/permissions/permission_service_context.h"
75 #include "content/browser/permissions/permission_service_impl.h"
76 #include "content/browser/profiler_message_filter.h"
77 #include "content/browser/push_messaging/push_messaging_message_filter.h"
78 #include "content/browser/quota_dispatcher_host.h"
79 #include "content/browser/renderer_host/clipboard_message_filter.h"
80 #include "content/browser/renderer_host/database_message_filter.h"
81 #include "content/browser/renderer_host/file_utilities_message_filter.h"
82 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
83 #include "content/browser/renderer_host/gpu_message_filter.h"
84 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
85 #include "content/browser/renderer_host/media/audio_renderer_host.h"
86 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
87 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
88 #include "content/browser/renderer_host/media/video_capture_host.h"
89 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
90 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
91 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
92 #include "content/browser/renderer_host/render_message_filter.h"
93 #include "content/browser/renderer_host/render_view_host_delegate.h"
94 #include "content/browser/renderer_host/render_view_host_impl.h"
95 #include "content/browser/renderer_host/render_widget_helper.h"
96 #include "content/browser/renderer_host/render_widget_host_impl.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/cache_storage_context_impl.h"
101 #include "content/browser/service_worker/cache_storage_dispatcher_host.h"
102 #include "content/browser/service_worker/service_worker_context_wrapper.h"
103 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
104 #include "content/browser/shared_worker/shared_worker_message_filter.h"
105 #include "content/browser/shared_worker/worker_storage_partition.h"
106 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
107 #include "content/browser/storage_partition_impl.h"
108 #include "content/browser/streams/stream_context.h"
109 #include "content/browser/tracing/trace_message_filter.h"
110 #include "content/browser/webui/web_ui_controller_factory_registry.h"
111 #include "content/common/child_process_host_impl.h"
112 #include "content/common/child_process_messages.h"
113 #include "content/common/content_switches_internal.h"
114 #include "content/common/frame_messages.h"
115 #include "content/common/gpu/gpu_memory_buffer_factory.h"
116 #include "content/common/gpu/gpu_messages.h"
117 #include "content/common/in_process_child_thread_params.h"
118 #include "content/common/mojo/channel_init.h"
119 #include "content/common/mojo/mojo_messages.h"
120 #include "content/common/resource_messages.h"
121 #include "content/common/view_messages.h"
122 #include "content/public/browser/browser_context.h"
123 #include "content/public/browser/content_browser_client.h"
124 #include "content/public/browser/navigator_connect_context.h"
125 #include "content/public/browser/notification_service.h"
126 #include "content/public/browser/notification_types.h"
127 #include "content/public/browser/render_process_host_factory.h"
128 #include "content/public/browser/render_process_host_observer.h"
129 #include "content/public/browser/render_widget_host.h"
130 #include "content/public/browser/render_widget_host_iterator.h"
131 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
132 #include "content/public/browser/resource_context.h"
133 #include "content/public/browser/user_metrics.h"
134 #include "content/public/browser/worker_service.h"
135 #include "content/public/common/content_constants.h"
136 #include "content/public/common/content_switches.h"
137 #include "content/public/common/mojo_channel_switches.h"
138 #include "content/public/common/process_type.h"
139 #include "content/public/common/resource_type.h"
140 #include "content/public/common/result_codes.h"
141 #include "content/public/common/sandboxed_process_launcher_delegate.h"
142 #include "content/public/common/url_constants.h"
143 #include "device/battery/battery_monitor_impl.h"
144 #include "device/vibration/vibration_manager_impl.h"
145 #include "gpu/GLES2/gl2extchromium.h"
146 #include "gpu/command_buffer/client/gpu_switches.h"
147 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
148 #include "gpu/command_buffer/service/gpu_switches.h"
149 #include "ipc/ipc_channel.h"
150 #include "ipc/ipc_logging.h"
151 #include "ipc/ipc_switches.h"
152 #include "ipc/mojo/ipc_channel_mojo.h"
153 #include "ipc/mojo/ipc_channel_mojo_host.h"
154 #include "media/base/media_switches.h"
155 #include "net/url_request/url_request_context_getter.h"
156 #include "ppapi/shared_impl/ppapi_switches.h"
157 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
158 #include "third_party/skia/include/core/SkBitmap.h"
159 #include "ui/base/ui_base_switches.h"
160 #include "ui/events/event_switches.h"
161 #include "ui/gfx/switches.h"
162 #include "ui/gl/gl_switches.h"
163 #include "ui/gl/gpu_switching_manager.h"
164 #include "ui/native_theme/native_theme_switches.h"
166 #if defined(OS_ANDROID)
167 #include "content/browser/android/child_process_launcher_android.h"
168 #include "content/browser/media/android/browser_demuxer_android.h"
169 #include "content/browser/mojo/service_registrar_android.h"
170 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
174 #include "base/win/scoped_com_initializer.h"
175 #include "base/win/windows_version.h"
176 #include "content/common/font_cache_dispatcher_win.h"
177 #include "content/common/sandbox_win.h"
178 #include "sandbox/win/src/sandbox_policy.h"
179 #include "ui/gfx/win/dpi.h"
182 #if defined(ENABLE_BROWSER_CDMS)
183 #include "content/browser/media/cdm/browser_cdm_manager.h"
186 #if defined(ENABLE_PLUGINS)
187 #include "content/browser/plugin_service_impl.h"
190 #if defined(ENABLE_WEBRTC)
191 #include "content/browser/media/webrtc_internals.h"
192 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
193 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
194 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
195 #include "content/common/media/aec_dump_messages.h"
196 #include "content/common/media/media_stream_messages.h"
199 extern bool g_exited_main_message_loop
;
204 const char kSiteProcessMapKeyName
[] = "content_site_process_map";
206 void CacheShaderInfo(int32 id
, base::FilePath path
) {
207 ShaderCacheFactory::GetInstance()->SetCacheInfo(id
, path
);
210 void RemoveShaderInfo(int32 id
) {
211 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id
);
214 scoped_ptr
<IPC::Message
> SendAudioHardwareConfig() {
215 media::AudioManager
* am
= media::AudioManager::Get();
216 DCHECK(am
->GetWorkerTaskRunner()->BelongsToCurrentThread());
217 return make_scoped_ptr(new ViewMsg_SetAudioHardwareConfig(
218 am
->GetDefaultOutputStreamParameters(),
219 am
->GetInputStreamParameters(media::AudioManagerBase::kDefaultDeviceId
)));
222 net::URLRequestContext
* GetRequestContext(
223 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
224 scoped_refptr
<net::URLRequestContextGetter
> media_request_context
,
225 ResourceType resource_type
) {
226 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
227 // context specific to media for handling it because these resources have
228 // specific needs for caching.
229 if (resource_type
== RESOURCE_TYPE_MEDIA
)
230 return media_request_context
->GetURLRequestContext();
231 return request_context
->GetURLRequestContext();
235 ResourceContext
* resource_context
,
236 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
237 scoped_refptr
<net::URLRequestContextGetter
> media_request_context
,
238 const ResourceHostMsg_Request
& request
,
239 ResourceContext
** resource_context_out
,
240 net::URLRequestContext
** request_context_out
) {
241 *resource_context_out
= resource_context
;
242 *request_context_out
=
243 GetRequestContext(request_context
, media_request_context
,
244 request
.resource_type
);
247 #if defined(ENABLE_WEBRTC)
248 // Creates a file used for diagnostic echo canceller recordings for handing
249 // over to the renderer.
250 IPC::PlatformFileForTransit
CreateAecDumpFileForProcess(
251 base::FilePath file_path
,
252 base::ProcessHandle process
) {
253 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
254 base::File
dump_file(file_path
,
255 base::File::FLAG_OPEN_ALWAYS
| base::File::FLAG_APPEND
);
256 if (!dump_file
.IsValid()) {
257 VLOG(1) << "Could not open AEC dump file, error=" <<
258 dump_file
.error_details();
259 return IPC::InvalidPlatformFileForTransit();
261 return IPC::TakeFileHandleForProcess(dump_file
.Pass(), process
);
264 // Does nothing. Just to avoid races between enable and disable.
265 void DisableAecDumpOnFileThread() {
266 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
270 // the global list of all renderer processes
271 base::LazyInstance
<IDMap
<RenderProcessHost
> >::Leaky
272 g_all_hosts
= LAZY_INSTANCE_INITIALIZER
;
274 // Map of site to process, to ensure we only have one RenderProcessHost per
275 // site in process-per-site mode. Each map is specific to a BrowserContext.
276 class SiteProcessMap
: public base::SupportsUserData::Data
{
278 typedef base::hash_map
<std::string
, RenderProcessHost
*> SiteToProcessMap
;
281 void RegisterProcess(const std::string
& site
, RenderProcessHost
* process
) {
282 map_
[site
] = process
;
285 RenderProcessHost
* FindProcess(const std::string
& site
) {
286 SiteToProcessMap::iterator i
= map_
.find(site
);
292 void RemoveProcess(RenderProcessHost
* host
) {
293 // Find all instances of this process in the map, then separately remove
295 std::set
<std::string
> sites
;
296 for (SiteToProcessMap::const_iterator i
= map_
.begin();
299 if (i
->second
== host
)
300 sites
.insert(i
->first
);
302 for (std::set
<std::string
>::iterator i
= sites
.begin();
305 SiteToProcessMap::iterator iter
= map_
.find(*i
);
306 if (iter
!= map_
.end()) {
307 DCHECK_EQ(iter
->second
, host
);
314 SiteToProcessMap map_
;
317 // Find the SiteProcessMap specific to the given context.
318 SiteProcessMap
* GetSiteProcessMapForBrowserContext(BrowserContext
* context
) {
320 SiteProcessMap
* map
= static_cast<SiteProcessMap
*>(
321 context
->GetUserData(kSiteProcessMapKeyName
));
323 map
= new SiteProcessMap();
324 context
->SetUserData(kSiteProcessMapKeyName
, map
);
329 // NOTE: changes to this class need to be reviewed by the security team.
330 class RendererSandboxedProcessLauncherDelegate
331 : public SandboxedProcessLauncherDelegate
{
333 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy
* channel
)
334 #if defined(OS_POSIX)
335 : ipc_fd_(channel
->TakeClientFileDescriptor())
339 ~RendererSandboxedProcessLauncherDelegate() override
{}
342 virtual void PreSpawnTarget(sandbox::TargetPolicy
* policy
,
344 AddBaseHandleClosePolicy(policy
);
346 if (base::win::GetVersion() == base::win::VERSION_WIN8
||
347 base::win::GetVersion() == base::win::VERSION_WIN8_1
) {
348 // TODO(shrikant): Check if these constants should be different across
349 // various versions of Chromium code base or could be same.
350 // If there should be different SID per channel then move this code
351 // in chrome rather than content and assign SID based on
352 // VersionInfo::GetChannel().
353 const wchar_t kAppContainerSid
[] =
354 L
"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
355 L
"924012148-129201922";
357 policy
->SetLowBox(kAppContainerSid
);
360 GetContentClient()->browser()->PreSpawnRenderer(policy
, success
);
363 #elif defined(OS_POSIX)
364 bool ShouldUseZygote() override
{
365 const base::CommandLine
& browser_command_line
=
366 *base::CommandLine::ForCurrentProcess();
367 base::CommandLine::StringType renderer_prefix
=
368 browser_command_line
.GetSwitchValueNative(switches::kRendererCmdPrefix
);
369 return renderer_prefix
.empty();
371 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
375 #if defined(OS_POSIX)
376 base::ScopedFD ipc_fd_
;
380 const char kSessionStorageHolderKey
[] = "kSessionStorageHolderKey";
382 class SessionStorageHolder
: public base::SupportsUserData::Data
{
384 SessionStorageHolder() {}
385 ~SessionStorageHolder() override
{}
387 void Hold(const SessionStorageNamespaceMap
& sessions
, int view_route_id
) {
388 session_storage_namespaces_awaiting_close_
[view_route_id
] = sessions
;
391 void Release(int old_route_id
) {
392 session_storage_namespaces_awaiting_close_
.erase(old_route_id
);
396 std::map
<int, SessionStorageNamespaceMap
>
397 session_storage_namespaces_awaiting_close_
;
398 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder
);
403 RendererMainThreadFactoryFunction g_renderer_main_thread_factory
= NULL
;
405 base::MessageLoop
* g_in_process_thread
;
408 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
409 return g_in_process_thread
;
412 // Stores the maximum number of renderer processes the content module can
414 static size_t g_max_renderer_count_override
= 0;
417 size_t RenderProcessHost::GetMaxRendererProcessCount() {
418 if (g_max_renderer_count_override
)
419 return g_max_renderer_count_override
;
421 #if defined(OS_ANDROID)
422 // On Android we don't maintain a limit of renderer process hosts - we are
423 // happy with keeping a lot of these, as long as the number of live renderer
424 // processes remains reasonable, and on Android the OS takes care of that.
425 return std::numeric_limits
<size_t>::max();
428 // On other platforms, we calculate the maximum number of renderer process
429 // hosts according to the amount of installed memory as reported by the OS.
430 // The calculation assumes that you want the renderers to use half of the
431 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
432 // this assumption, you need to adjust the ThirtyFourTabs test to match the
433 // expected number of processes.
435 // With the given amounts of installed memory below on a 32-bit CPU, the
436 // maximum renderer count will roughly be as follows:
442 // 16384 MB -> 82 (kMaxRendererProcessCount)
444 static size_t max_count
= 0;
446 const size_t kEstimatedWebContentsMemoryUsage
=
447 #if defined(ARCH_CPU_64_BITS)
452 max_count
= base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
453 max_count
/= kEstimatedWebContentsMemoryUsage
;
455 const size_t kMinRendererProcessCount
= 3;
456 max_count
= std::max(max_count
, kMinRendererProcessCount
);
457 max_count
= std::min(max_count
, kMaxRendererProcessCount
);
463 bool g_run_renderer_in_process_
= false;
466 void RenderProcessHost::SetMaxRendererProcessCount(size_t count
) {
467 g_max_renderer_count_override
= count
;
470 RenderProcessHostImpl::RenderProcessHostImpl(
471 BrowserContext
* browser_context
,
472 StoragePartitionImpl
* storage_partition_impl
,
473 bool is_isolated_guest
)
474 : fast_shutdown_started_(false),
475 deleting_soon_(false),
477 is_self_deleted_(false),
480 mojo_application_host_(new MojoApplicationHost
),
483 is_initialized_(false),
484 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
485 browser_context_(browser_context
),
486 storage_partition_impl_(storage_partition_impl
),
487 sudden_termination_allowed_(true),
488 ignore_input_events_(false),
489 is_isolated_guest_(is_isolated_guest
),
490 gpu_observer_registered_(false),
491 delayed_cleanup_needed_(false),
492 within_process_died_observer_(false),
493 power_monitor_broadcaster_(this),
494 worker_ref_count_(0),
495 max_worker_count_(0),
496 permission_service_context_(new PermissionServiceContext(this)),
497 pending_valuebuffer_state_(new gpu::ValueStateMap()),
498 subscribe_uniform_enabled_(false),
499 weak_factory_(this) {
500 widget_helper_
= new RenderWidgetHelper();
502 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
504 CHECK(!g_exited_main_message_loop
);
505 RegisterHost(GetID(), this);
506 g_all_hosts
.Get().set_check_on_null_data(true);
507 // Initialize |child_process_activity_time_| to a reasonable value.
508 mark_child_process_activity_time();
510 if (!GetBrowserContext()->IsOffTheRecord() &&
511 !base::CommandLine::ForCurrentProcess()->HasSwitch(
512 switches::kDisableGpuShaderDiskCache
)) {
513 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
514 base::Bind(&CacheShaderInfo
, GetID(),
515 storage_partition_impl_
->GetPath()));
517 subscribe_uniform_enabled_
=
518 base::CommandLine::ForCurrentProcess()->HasSwitch(
519 switches::kEnableSubscribeUniformExtension
);
521 // Note: When we create the RenderProcessHostImpl, it's technically
522 // backgrounded, because it has no visible listeners. But the process
523 // doesn't actually exist yet, so we'll Background it later, after
528 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
529 DCHECK(g_run_renderer_in_process_
);
531 switch (g_all_hosts
.Pointer()->size()) {
535 RenderProcessHostImpl
* host
= static_cast<RenderProcessHostImpl
*>(
536 AllHostsIterator().GetCurrentValue());
537 FOR_EACH_OBSERVER(RenderProcessHostObserver
,
539 RenderProcessHostDestroyed(host
));
541 host
->is_self_deleted_
= true;
547 NOTREACHED() << "There should be only one RenderProcessHost when running "
552 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
553 RendererMainThreadFactoryFunction create
) {
554 g_renderer_main_thread_factory
= create
;
557 RenderProcessHostImpl::~RenderProcessHostImpl() {
559 DCHECK(is_self_deleted_
)
560 << "RenderProcessHostImpl is destroyed by something other than itself";
563 // Make sure to clean up the in-process renderer before the channel, otherwise
564 // it may still run and have its IPCs fail, causing asserts.
565 in_process_renderer_
.reset();
567 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
569 if (gpu_observer_registered_
) {
570 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
571 gpu_observer_registered_
= false;
574 // We may have some unsent messages at this point, but that's OK.
576 while (!queued_messages_
.empty()) {
577 delete queued_messages_
.front();
578 queued_messages_
.pop();
581 UnregisterHost(GetID());
583 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
584 switches::kDisableGpuShaderDiskCache
)) {
585 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
586 base::Bind(&RemoveShaderInfo
, GetID()));
590 void RenderProcessHostImpl::EnableSendQueue() {
591 is_initialized_
= false;
594 bool RenderProcessHostImpl::Init() {
595 // calling Init() more than once does nothing, this makes it more convenient
596 // for the view host which may not be sure in some cases
600 base::CommandLine::StringType renderer_prefix
;
601 // A command prefix is something prepended to the command line of the spawned
603 const base::CommandLine
& browser_command_line
=
604 *base::CommandLine::ForCurrentProcess();
606 browser_command_line
.GetSwitchValueNative(switches::kRendererCmdPrefix
);
608 #if defined(OS_LINUX)
609 int flags
= renderer_prefix
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
610 ChildProcessHost::CHILD_NORMAL
;
612 int flags
= ChildProcessHost::CHILD_NORMAL
;
615 // Find the renderer before creating the channel so if this fails early we
616 // return without creating the channel.
617 base::FilePath renderer_path
= ChildProcessHost::GetChildPath(flags
);
618 if (renderer_path
.empty())
621 // Setup the IPC channel.
622 const std::string channel_id
=
623 IPC::Channel::GenerateVerifiedChannelID(std::string());
624 channel_
= CreateChannelProxy(channel_id
);
626 // Setup the Mojo channel.
627 mojo_application_host_
->Init();
629 // Call the embedder first so that their IPC filters have priority.
630 GetContentClient()->browser()->RenderProcessWillLaunch(this);
632 CreateMessageFilters();
633 RegisterMojoServices();
635 if (run_renderer_in_process()) {
636 DCHECK(g_renderer_main_thread_factory
);
637 // Crank up a thread and run the initialization there. With the way that
638 // messages flow between the browser and renderer, this thread is required
639 // to prevent a deadlock in single-process mode. Since the primordial
640 // thread in the renderer process runs the WebKit code and can sometimes
641 // make blocking calls to the UI thread (i.e. this thread), they need to run
642 // on separate threads.
643 in_process_renderer_
.reset(
644 g_renderer_main_thread_factory(InProcessChildThreadParams(
645 channel_id
, BrowserThread::UnsafeGetMessageLoopForThread(
646 BrowserThread::IO
)->task_runner())));
648 base::Thread::Options options
;
649 #if defined(OS_WIN) && !defined(OS_MACOSX)
650 // In-process plugins require this to be a UI message loop.
651 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
653 // We can't have multiple UI loops on Linux and Android, so we don't support
654 // in-process plugins.
655 options
.message_loop_type
= base::MessageLoop::TYPE_DEFAULT
;
658 // As for execution sequence, this callback should have no any dependency
659 // on starting in-process-render-thread.
660 // So put it here to trigger ChannelMojo initialization earlier to enable
661 // in-process-render-thread using ChannelMojo there.
662 OnProcessLaunched(); // Fake a callback that the process is ready.
664 in_process_renderer_
->StartWithOptions(options
);
666 g_in_process_thread
= in_process_renderer_
->message_loop();
669 // Build command line for renderer. We call AppendRendererCommandLine()
670 // first so the process type argument will appear first.
671 base::CommandLine
* cmd_line
= new base::CommandLine(renderer_path
);
672 if (!renderer_prefix
.empty())
673 cmd_line
->PrependWrapper(renderer_prefix
);
674 AppendRendererCommandLine(cmd_line
);
675 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
677 // Spawn the child process asynchronously to avoid blocking the UI thread.
678 // As long as there's no renderer prefix, we can use the zygote process
680 child_process_launcher_
.reset(new ChildProcessLauncher(
681 new RendererSandboxedProcessLauncherDelegate(channel_
.get()),
686 fast_shutdown_started_
= false;
689 if (!gpu_observer_registered_
) {
690 gpu_observer_registered_
= true;
691 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
694 power_monitor_broadcaster_
.Init();
696 is_initialized_
= true;
697 init_time_
= base::TimeTicks::Now();
701 scoped_ptr
<IPC::ChannelProxy
> RenderProcessHostImpl::CreateChannelProxy(
702 const std::string
& channel_id
) {
703 scoped_refptr
<base::SingleThreadTaskRunner
> runner
=
704 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
705 scoped_refptr
<base::SequencedTaskRunner
> mojo_task_runner
=
706 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO
)
708 if (ShouldUseMojoChannel()) {
709 VLOG(1) << "Mojo Channel is enabled on host";
710 if (!channel_mojo_host_
) {
711 channel_mojo_host_
.reset(new IPC::ChannelMojoHost(mojo_task_runner
));
714 return IPC::ChannelProxy::Create(
715 IPC::ChannelMojo::CreateServerFactory(
716 channel_mojo_host_
->channel_delegate(), channel_id
),
721 return IPC::ChannelProxy::Create(
722 channel_id
, IPC::Channel::MODE_SERVER
, this, runner
.get());
725 void RenderProcessHostImpl::CreateMessageFilters() {
726 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
727 const base::CommandLine
& browser_command_line
=
728 *base::CommandLine::ForCurrentProcess();
729 AddFilter(new ResourceSchedulerFilter(GetID()));
730 MediaInternals
* media_internals
= MediaInternals::GetInstance();
731 media::AudioManager
* audio_manager
=
732 BrowserMainLoop::GetInstance()->audio_manager();
733 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
735 scoped_refptr
<BrowserPluginMessageFilter
> bp_message_filter(
736 new BrowserPluginMessageFilter(GetID()));
737 AddFilter(bp_message_filter
.get());
739 scoped_refptr
<RenderMessageFilter
> render_message_filter(
740 new RenderMessageFilter(
742 #if defined(ENABLE_PLUGINS)
743 PluginServiceImpl::GetInstance(),
748 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
749 widget_helper_
.get(),
752 storage_partition_impl_
->GetDOMStorageContext()));
753 AddFilter(render_message_filter
.get());
755 new RenderFrameMessageFilter(GetID(), widget_helper_
.get()));
756 BrowserContext
* browser_context
= GetBrowserContext();
757 ResourceContext
* resource_context
= browser_context
->GetResourceContext();
759 scoped_refptr
<net::URLRequestContextGetter
> request_context(
760 browser_context
->GetRequestContextForRenderProcess(GetID()));
761 scoped_refptr
<net::URLRequestContextGetter
> media_request_context(
762 browser_context
->GetMediaRequestContextForRenderProcess(GetID()));
764 ResourceMessageFilter::GetContextsCallback
get_contexts_callback(
765 base::Bind(&GetContexts
, browser_context
->GetResourceContext(),
766 request_context
, media_request_context
));
768 ResourceMessageFilter
* resource_message_filter
= new ResourceMessageFilter(
769 GetID(), PROCESS_TYPE_RENDERER
,
770 storage_partition_impl_
->GetAppCacheService(),
771 ChromeBlobStorageContext::GetFor(browser_context
),
772 storage_partition_impl_
->GetFileSystemContext(),
773 storage_partition_impl_
->GetServiceWorkerContext(),
774 storage_partition_impl_
->GetHostZoomLevelContext(),
775 get_contexts_callback
);
777 AddFilter(resource_message_filter
);
778 MediaStreamManager
* media_stream_manager
=
779 BrowserMainLoop::GetInstance()->media_stream_manager();
780 AddFilter(new AudioInputRendererHost(
782 media_stream_manager
,
783 AudioMirroringManager::GetInstance(),
784 BrowserMainLoop::GetInstance()->user_input_monitor()));
785 // The AudioRendererHost needs to be available for lookup, so it's
786 // stashed in a member variable.
787 audio_renderer_host_
= new AudioRendererHost(
790 AudioMirroringManager::GetInstance(),
792 media_stream_manager
);
793 AddFilter(audio_renderer_host_
.get());
795 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
796 AddFilter(new VideoCaptureHost(media_stream_manager
));
797 AddFilter(new AppCacheDispatcherHost(
798 storage_partition_impl_
->GetAppCacheService(),
800 AddFilter(new ClipboardMessageFilter
);
801 AddFilter(new DOMStorageMessageFilter(
802 storage_partition_impl_
->GetDOMStorageContext()));
803 AddFilter(new IndexedDBDispatcherHost(
805 storage_partition_impl_
->GetURLRequestContext(),
806 storage_partition_impl_
->GetIndexedDBContext(),
807 ChromeBlobStorageContext::GetFor(browser_context
)));
809 gpu_message_filter_
= new GpuMessageFilter(GetID(), widget_helper_
.get());
810 AddFilter(gpu_message_filter_
);
811 #if defined(ENABLE_WEBRTC)
812 AddFilter(new WebRTCIdentityServiceHost(
813 GetID(), storage_partition_impl_
->GetWebRTCIdentityStore()));
814 peer_connection_tracker_host_
= new PeerConnectionTrackerHost(GetID());
815 AddFilter(peer_connection_tracker_host_
.get());
816 AddFilter(new MediaStreamDispatcherHost(
818 browser_context
->GetResourceContext()->GetMediaDeviceIDSalt(),
819 media_stream_manager
));
820 AddFilter(new MediaStreamTrackMetricsHost());
822 #if defined(ENABLE_PLUGINS)
823 AddFilter(new PepperRendererConnection(GetID()));
825 AddFilter(new SpeechRecognitionDispatcherHost(
826 GetID(), storage_partition_impl_
->GetURLRequestContext()));
827 AddFilter(new FileAPIMessageFilter(
829 storage_partition_impl_
->GetURLRequestContext(),
830 storage_partition_impl_
->GetFileSystemContext(),
831 ChromeBlobStorageContext::GetFor(browser_context
),
832 StreamContext::GetFor(browser_context
)));
833 AddFilter(new FileUtilitiesMessageFilter(GetID()));
834 AddFilter(new MimeRegistryMessageFilter());
835 AddFilter(new DatabaseMessageFilter(
836 storage_partition_impl_
->GetDatabaseTracker()));
837 #if defined(OS_MACOSX)
838 AddFilter(new TextInputClientMessageFilter(GetID()));
839 #elif defined(OS_WIN)
840 // The FontCacheDispatcher is required only when we're using GDI rendering.
841 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
842 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
843 // should eventually be if (!ShouldUseDirectWrite()) guarded.
844 channel_
->AddFilter(new FontCacheDispatcher());
845 #elif defined(OS_ANDROID)
846 browser_demuxer_android_
= new BrowserDemuxerAndroid();
847 AddFilter(browser_demuxer_android_
.get());
849 #if defined(ENABLE_BROWSER_CDMS)
850 browser_cdm_manager_
= new BrowserCdmManager(GetID(), NULL
);
851 AddFilter(browser_cdm_manager_
.get());
854 WebSocketDispatcherHost::GetRequestContextCallback
855 websocket_request_context_callback(
856 base::Bind(&GetRequestContext
, request_context
,
857 media_request_context
, RESOURCE_TYPE_SUB_RESOURCE
));
860 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback
));
862 message_port_message_filter_
= new MessagePortMessageFilter(
863 base::Bind(&RenderWidgetHelper::GetNextRoutingID
,
864 base::Unretained(widget_helper_
.get())));
865 AddFilter(message_port_message_filter_
.get());
867 scoped_refptr
<CacheStorageDispatcherHost
> cache_storage_filter
=
868 new CacheStorageDispatcherHost();
869 cache_storage_filter
->Init(storage_partition_impl_
->GetCacheStorageContext());
870 AddFilter(cache_storage_filter
.get());
872 scoped_refptr
<ServiceWorkerDispatcherHost
> service_worker_filter
=
873 new ServiceWorkerDispatcherHost(
874 GetID(), message_port_message_filter_
.get(), resource_context
);
875 service_worker_filter
->Init(
876 storage_partition_impl_
->GetServiceWorkerContext());
877 AddFilter(service_worker_filter
.get());
879 AddFilter(new SharedWorkerMessageFilter(
882 WorkerStoragePartition(
883 storage_partition_impl_
->GetURLRequestContext(),
884 storage_partition_impl_
->GetMediaURLRequestContext(),
885 storage_partition_impl_
->GetAppCacheService(),
886 storage_partition_impl_
->GetQuotaManager(),
887 storage_partition_impl_
->GetFileSystemContext(),
888 storage_partition_impl_
->GetDatabaseTracker(),
889 storage_partition_impl_
->GetIndexedDBContext(),
890 storage_partition_impl_
->GetServiceWorkerContext()),
891 message_port_message_filter_
.get()));
893 #if defined(ENABLE_WEBRTC)
894 p2p_socket_dispatcher_host_
= new P2PSocketDispatcherHost(
896 browser_context
->GetRequestContextForRenderProcess(GetID()));
897 AddFilter(p2p_socket_dispatcher_host_
.get());
900 AddFilter(new TraceMessageFilter());
901 AddFilter(new ResolveProxyMsgHelper(
902 browser_context
->GetRequestContextForRenderProcess(GetID())));
903 AddFilter(new QuotaDispatcherHost(
905 storage_partition_impl_
->GetQuotaManager(),
906 GetContentClient()->browser()->CreateQuotaPermissionContext()));
908 notification_message_filter_
= new NotificationMessageFilter(
910 storage_partition_impl_
->GetPlatformNotificationContext(),
913 AddFilter(notification_message_filter_
.get());
915 AddFilter(new GamepadBrowserMessageFilter());
916 AddFilter(new DeviceLightMessageFilter());
917 AddFilter(new DeviceMotionMessageFilter());
918 AddFilter(new DeviceOrientationMessageFilter());
919 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER
));
920 AddFilter(new HistogramMessageFilter());
921 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
922 if (browser_command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
923 AddFilter(new MemoryBenchmarkMessageFilter());
925 AddFilter(new PushMessagingMessageFilter(
926 GetID(), storage_partition_impl_
->GetServiceWorkerContext()));
927 #if defined(OS_ANDROID)
928 AddFilter(new ScreenOrientationMessageFilterAndroid());
930 AddFilter(new GeofencingDispatcherHost(
931 storage_partition_impl_
->GetGeofencingManager()));
932 AddFilter(new NavigatorConnectDispatcherHost(
933 storage_partition_impl_
->GetNavigatorConnectContext(),
934 message_port_message_filter_
.get()));
935 if (browser_command_line
.HasSwitch(
936 switches::kEnableExperimentalWebPlatformFeatures
)) {
937 scoped_refptr
<BluetoothDispatcherHost
> bluetooth_dispatcher_host(
938 BluetoothDispatcherHost::Create());
939 AddFilter(bluetooth_dispatcher_host
.get());
943 void RenderProcessHostImpl::RegisterMojoServices() {
944 mojo_application_host_
->service_registry()->AddService(
945 base::Bind(&device::BatteryMonitorImpl::Create
));
947 mojo_application_host_
->service_registry()->AddService(
948 base::Bind(&device::VibrationManagerImpl::Create
));
950 mojo_application_host_
->service_registry()->AddService(
951 base::Bind(&PermissionServiceContext::CreateService
,
952 base::Unretained(permission_service_context_
.get())));
954 #if defined(OS_ANDROID)
955 ServiceRegistrarAndroid::RegisterProcessHostServices(
956 mojo_application_host_
->service_registry_android());
959 GetContentClient()->browser()->OverrideRenderProcessMojoServices(
960 mojo_application_host_
->service_registry());
963 int RenderProcessHostImpl::GetNextRoutingID() {
964 return widget_helper_
->GetNextRoutingID();
967 void RenderProcessHostImpl::ResumeDeferredNavigation(
968 const GlobalRequestID
& request_id
) {
969 widget_helper_
->ResumeDeferredNavigation(request_id
);
972 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
973 const GlobalRequestID
& request_id
) {
974 widget_helper_
->ResumeResponseDeferredAtStart(request_id
);
977 void RenderProcessHostImpl::NotifyTimezoneChange() {
978 Send(new ViewMsg_TimezoneChange());
981 ServiceRegistry
* RenderProcessHostImpl::GetServiceRegistry() {
982 DCHECK(mojo_application_host_
);
983 return mojo_application_host_
->service_registry();
986 const base::TimeTicks
& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
991 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
992 return subscribe_uniform_enabled_
;
995 void RenderProcessHostImpl::OnAddSubscription(unsigned int target
) {
996 DCHECK(subscribe_uniform_enabled_
);
997 subscription_set_
.insert(target
);
998 const gpu::ValueState
* state
= pending_valuebuffer_state_
->GetState(target
);
1000 SendUpdateValueState(target
, *state
);
1004 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target
) {
1005 DCHECK(subscribe_uniform_enabled_
);
1006 subscription_set_
.erase(target
);
1009 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target
,
1010 const gpu::ValueState
& state
) {
1011 DCHECK(subscribe_uniform_enabled_
);
1012 if (subscription_set_
.find(target
) != subscription_set_
.end()) {
1013 GpuProcessHost::SendOnIO(
1014 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1015 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
,
1016 new GpuMsg_UpdateValueState(id_
, target
, state
));
1018 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1019 pending_valuebuffer_state_
->UpdateState(target
, state
);
1023 #if defined(ENABLE_BROWSER_CDMS)
1024 media::BrowserCdm
* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id
,
1026 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1027 return browser_cdm_manager_
->GetCdm(render_frame_id
, cdm_id
);
1031 void RenderProcessHostImpl::AddRoute(
1033 IPC::Listener
* listener
) {
1034 CHECK(!listeners_
.Lookup(routing_id
))
1035 << "Found Routing ID Conflict: " << routing_id
;
1036 listeners_
.AddWithID(listener
, routing_id
);
1039 void RenderProcessHostImpl::RemoveRoute(int32 routing_id
) {
1040 DCHECK(listeners_
.Lookup(routing_id
) != NULL
);
1041 listeners_
.Remove(routing_id
);
1044 // Dump the handle table if handle auditing is enabled.
1045 const base::CommandLine
& browser_command_line
=
1046 *base::CommandLine::ForCurrentProcess();
1047 if (browser_command_line
.HasSwitch(switches::kAuditHandles
) ||
1048 browser_command_line
.HasSwitch(switches::kAuditAllHandles
)) {
1051 // We wait to close the channels until the child process has finished
1052 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
1056 // Keep the one renderer thread around forever in single process mode.
1057 if (!run_renderer_in_process())
1061 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver
* observer
) {
1062 observers_
.AddObserver(observer
);
1065 void RenderProcessHostImpl::RemoveObserver(
1066 RenderProcessHostObserver
* observer
) {
1067 observers_
.RemoveObserver(observer
);
1070 void RenderProcessHostImpl::ShutdownForBadMessage() {
1071 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
1072 if (command_line
->HasSwitch(switches::kDisableKillAfterBadIPC
))
1075 if (run_renderer_in_process()) {
1076 // In single process mode it is better if we don't suicide but just
1080 // We kill the renderer but don't include a NOTREACHED, because we want the
1081 // browser to try to survive when it gets illegal messages from the renderer.
1082 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE
, false);
1085 void RenderProcessHostImpl::WidgetRestored() {
1086 // Verify we were properly backgrounded.
1087 DCHECK_EQ(backgrounded_
, (visible_widgets_
== 0));
1089 SetBackgrounded(false);
1092 void RenderProcessHostImpl::WidgetHidden() {
1093 // On startup, the browser will call Hide
1097 DCHECK_EQ(backgrounded_
, (visible_widgets_
== 0));
1099 DCHECK_GE(visible_widgets_
, 0);
1100 if (visible_widgets_
== 0) {
1101 DCHECK(!backgrounded_
);
1102 SetBackgrounded(true);
1106 int RenderProcessHostImpl::VisibleWidgetCount() const {
1107 return visible_widgets_
;
1110 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1111 return is_isolated_guest_
;
1114 StoragePartition
* RenderProcessHostImpl::GetStoragePartition() const {
1115 return storage_partition_impl_
;
1118 static void AppendCompositorCommandLineFlags(base::CommandLine
* command_line
) {
1119 if (IsPinchVirtualViewportEnabled())
1120 command_line
->AppendSwitch(cc::switches::kEnablePinchVirtualViewport
);
1122 if (IsPropertyTreeVerificationEnabled())
1123 command_line
->AppendSwitch(cc::switches::kEnablePropertyTreeVerification
);
1125 if (IsDelegatedRendererEnabled())
1126 command_line
->AppendSwitch(switches::kEnableDelegatedRenderer
);
1128 if (IsImplSidePaintingEnabled()) {
1129 command_line
->AppendSwitchASCII(
1130 switches::kNumRasterThreads
,
1131 base::IntToString(NumberOfRendererRasterThreads()));
1133 command_line
->AppendSwitch(switches::kDisableImplSidePainting
);
1136 if (IsGpuRasterizationEnabled())
1137 command_line
->AppendSwitch(switches::kEnableGpuRasterization
);
1139 if (IsThreadedGpuRasterizationEnabled())
1140 command_line
->AppendSwitch(switches::kEnableThreadedGpuRasterization
);
1142 int msaa_sample_count
= GpuRasterizationMSAASampleCount();
1143 if (msaa_sample_count
> 0) {
1144 command_line
->AppendSwitchASCII(
1145 switches::kGpuRasterizationMSAASampleCount
,
1146 base::IntToString(msaa_sample_count
));
1149 DCHECK_IMPLIES(IsZeroCopyUploadEnabled(), !IsOneCopyUploadEnabled());
1150 DCHECK_IMPLIES(IsOneCopyUploadEnabled(), !IsZeroCopyUploadEnabled());
1151 if (IsZeroCopyUploadEnabled())
1152 command_line
->AppendSwitch(switches::kEnableZeroCopy
);
1153 if (!IsOneCopyUploadEnabled())
1154 command_line
->AppendSwitch(switches::kDisableOneCopy
);
1156 if (IsForceGpuRasterizationEnabled())
1157 command_line
->AppendSwitch(switches::kForceGpuRasterization
);
1159 command_line
->AppendSwitchASCII(
1160 switches::kUseImageTextureTarget
,
1162 BrowserGpuChannelHostFactory::GetImageTextureTarget()));
1164 // Appending disable-gpu-feature switches due to software rendering list.
1165 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
1166 DCHECK(gpu_data_manager
);
1167 gpu_data_manager
->AppendRendererCommandLine(command_line
);
1170 void RenderProcessHostImpl::AppendRendererCommandLine(
1171 base::CommandLine
* command_line
) const {
1172 // Pass the process type first, so it shows first in process listings.
1173 command_line
->AppendSwitchASCII(switches::kProcessType
,
1174 switches::kRendererProcess
);
1176 // Now send any options from our own command line we want to propagate.
1177 const base::CommandLine
& browser_command_line
=
1178 *base::CommandLine::ForCurrentProcess();
1179 PropagateBrowserCommandLineToRenderer(browser_command_line
, command_line
);
1181 // Pass on the browser locale.
1182 const std::string locale
=
1183 GetContentClient()->browser()->GetApplicationLocale();
1184 command_line
->AppendSwitchASCII(switches::kLang
, locale
);
1186 // If we run base::FieldTrials, we want to pass to their state to the
1187 // renderer so that it can act in accordance with each state, or record
1188 // histograms relating to the base::FieldTrial states.
1189 std::string field_trial_states
;
1190 base::FieldTrialList::AllStatesToString(&field_trial_states
);
1191 if (!field_trial_states
.empty()) {
1192 command_line
->AppendSwitchASCII(switches::kForceFieldTrials
,
1193 field_trial_states
);
1196 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1197 command_line
, GetID());
1199 if (IsPinchToZoomEnabled())
1200 command_line
->AppendSwitch(switches::kEnablePinch
);
1203 command_line
->AppendSwitchASCII(switches::kDeviceScaleFactor
,
1204 base::DoubleToString(gfx::GetDPIScale()));
1205 command_line
->AppendSwitchASCII(
1206 switches::kFontCacheSharedMemSuffix
,
1207 base::UintToString(base::GetCurrentProcId()));
1210 AppendCompositorCommandLineFlags(command_line
);
1213 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1214 const base::CommandLine
& browser_cmd
,
1215 base::CommandLine
* renderer_cmd
) const {
1216 // Propagate the following switches to the renderer command line (along
1217 // with any associated values) if present in the browser command line.
1218 static const char* const kSwitchNames
[] = {
1219 switches::kAllowInsecureWebSocketFromHttpsOrigin
,
1220 switches::kAllowLoopbackInPeerConnection
,
1221 switches::kAudioBufferSize
,
1222 switches::kAuditAllHandles
,
1223 switches::kAuditHandles
,
1224 switches::kBlinkPlatformLogChannels
,
1225 switches::kBlockCrossSiteDocuments
,
1226 switches::kDefaultTileWidth
,
1227 switches::kDefaultTileHeight
,
1228 switches::kDisable3DAPIs
,
1229 switches::kDisableAcceleratedJpegDecoding
,
1230 switches::kDisableAcceleratedVideoDecode
,
1231 switches::kDisableBlinkScheduler
,
1232 switches::kDisableBlinkFeatures
,
1233 switches::kDisableBreakpad
,
1234 switches::kDisablePreferCompositingToLCDText
,
1235 switches::kDisableDatabases
,
1236 switches::kDisableDirectNPAPIRequests
,
1237 switches::kDisableDisplayList2dCanvas
,
1238 switches::kDisableDistanceFieldText
,
1239 switches::kDisableEncryptedMedia
,
1240 switches::kDisableFileSystem
,
1241 switches::kDisableGpuCompositing
,
1242 switches::kDisableGpuVsync
,
1243 switches::kDisableLowResTiling
,
1244 switches::kDisableHistogramCustomizer
,
1245 switches::kDisableLCDText
,
1246 switches::kDisableLocalStorage
,
1247 switches::kDisableLogging
,
1248 switches::kDisableMediaSource
,
1249 switches::kDisableMojoChannel
,
1250 switches::kDisableNotifications
,
1251 switches::kDisableOverlayScrollbar
,
1252 switches::kDisablePinch
,
1253 switches::kDisablePrefixedEncryptedMedia
,
1254 switches::kDisableSeccompFilterSandbox
,
1255 switches::kDisableSharedWorkers
,
1256 switches::kDisableSVG1DOM
,
1257 switches::kDisableThreadedCompositing
,
1258 switches::kDisableThreadedScrolling
,
1259 switches::kDisableTouchAdjustment
,
1260 switches::kDisableTouchDragDrop
,
1261 switches::kDisableTouchEditing
,
1262 switches::kDisableV8IdleTasks
,
1263 switches::kDomAutomationController
,
1264 switches::kEnableBeginFrameScheduling
,
1265 switches::kEnableBleedingEdgeRenderingFastPaths
,
1266 switches::kEnableBlinkFeatures
,
1267 switches::kEnableBrowserSideNavigation
,
1268 switches::kEnablePreferCompositingToLCDText
,
1269 switches::kEnableCredentialManagerAPI
,
1270 switches::kEnableDeferredImageDecoding
,
1271 switches::kEnableDelayAgnosticAec
,
1272 switches::kEnableDisplayList2dCanvas
,
1273 switches::kEnableDistanceFieldText
,
1274 switches::kEnableExperimentalCanvasFeatures
,
1275 switches::kEnableExperimentalWebPlatformFeatures
,
1276 switches::kEnableGPUClientLogging
,
1277 switches::kEnableGpuClientTracing
,
1278 switches::kEnableGPUServiceLogging
,
1279 switches::kEnableLinkDisambiguationPopup
,
1280 switches::kEnableLowResTiling
,
1281 switches::kEnableInbandTextTracks
,
1282 switches::kEnableLCDText
,
1283 switches::kEnableLogging
,
1284 switches::kEnableMemoryBenchmarking
,
1285 switches::kEnableNetworkInformation
,
1286 switches::kEnableOverlayFullscreenVideo
,
1287 switches::kEnableOverlayScrollbar
,
1288 switches::kEnablePinch
,
1289 switches::kEnablePreciseMemoryInfo
,
1290 switches::kEnablePushMessagePayload
,
1291 switches::kEnablePushMessagingHasPermission
,
1292 switches::kEnableRendererMojoChannel
,
1293 switches::kEnableSeccompFilterSandbox
,
1294 switches::kEnableSkiaBenchmarking
,
1295 switches::kEnableSlimmingPaint
,
1296 switches::kEnableSmoothScrolling
,
1297 switches::kEnableStatsTable
,
1298 switches::kEnableStrictSiteIsolation
,
1299 switches::kEnableThreadedCompositing
,
1300 switches::kEnableTouchDragDrop
,
1301 switches::kEnableTouchEditing
,
1302 switches::kEnableUnsafeES3APIs
,
1303 switches::kEnableViewport
,
1304 switches::kEnableViewportMeta
,
1305 switches::kEnableVtune
,
1306 switches::kEnableWebGLDraftExtensions
,
1307 switches::kEnableWebGLImageChromium
,
1308 switches::kForceDeviceScaleFactor
,
1309 switches::kForceDisplayList2dCanvas
,
1310 switches::kFullMemoryCrashReport
,
1311 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode
,
1312 switches::kIPCConnectionTimeout
,
1313 switches::kJavaScriptFlags
,
1314 switches::kLoggingLevel
,
1315 switches::kMainFrameResizesAreOrientationChanges
,
1316 switches::kMaxUntiledLayerWidth
,
1317 switches::kMaxUntiledLayerHeight
,
1318 switches::kMemoryMetrics
,
1319 switches::kNoReferrers
,
1320 switches::kNoSandbox
,
1321 switches::kPpapiInProcess
,
1322 switches::kProfilerTiming
,
1323 switches::kReducedReferrerGranularity
,
1324 switches::kReduceSecurityForTesting
,
1325 switches::kRegisterPepperPlugins
,
1326 switches::kRendererStartupDialog
,
1327 switches::kRootLayerScrolls
,
1328 switches::kShowPaintRects
,
1329 switches::kSitePerProcess
,
1330 switches::kStatsCollectionController
,
1331 switches::kTestType
,
1332 switches::kTouchEvents
,
1333 switches::kTraceToConsole
,
1334 // This flag needs to be propagated to the renderer process for
1335 // --in-process-webgl.
1337 switches::kUseMobileUserAgent
,
1338 switches::kUseNormalPriorityForTileTaskWorkerThreads
,
1340 switches::kVideoThreads
,
1342 // Please keep these in alphabetical order. Compositor switches here should
1343 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1344 cc::switches::kCompositeToMailbox
,
1345 cc::switches::kDisableCompositedAntialiasing
,
1346 cc::switches::kDisableMainFrameBeforeActivation
,
1347 cc::switches::kDisableThreadedAnimation
,
1348 cc::switches::kEnableGpuBenchmarking
,
1349 cc::switches::kEnableMainFrameBeforeActivation
,
1350 cc::switches::kMaxTilesForInterestArea
,
1351 cc::switches::kMaxUnusedResourceMemoryUsagePercentage
,
1352 cc::switches::kShowCompositedLayerBorders
,
1353 cc::switches::kShowFPSCounter
,
1354 cc::switches::kShowLayerAnimationBounds
,
1355 cc::switches::kShowPropertyChangedRects
,
1356 cc::switches::kShowReplicaScreenSpaceRects
,
1357 cc::switches::kShowScreenSpaceRects
,
1358 cc::switches::kShowSurfaceDamageRects
,
1359 cc::switches::kSlowDownRasterScaleFactor
,
1360 cc::switches::kStrictLayerPropertyChangeChecking
,
1361 cc::switches::kTopControlsHideThreshold
,
1362 cc::switches::kTopControlsShowThreshold
,
1363 #if defined(ENABLE_PLUGINS)
1364 switches::kEnablePepperTesting
,
1365 switches::kEnablePluginPowerSaver
,
1367 #if defined(ENABLE_WEBRTC)
1368 switches::kDisableWebRtcHWDecoding
,
1369 switches::kDisableWebRtcHWEncoding
,
1370 switches::kEnableWebRtcHWH264Encoding
,
1371 switches::kEnableWebRtcStunOrigin
,
1372 switches::kWebRtcMaxCaptureFramerate
,
1374 switches::kEnableLowEndDeviceMode
,
1375 switches::kDisableLowEndDeviceMode
,
1376 #if defined(OS_ANDROID)
1377 switches::kDisableGestureRequirementForMediaPlayback
,
1378 switches::kDisableWebRTC
,
1379 switches::kMediaDrmEnableNonCompositing
,
1380 switches::kNetworkCountryIso
,
1381 switches::kDisableWebAudio
,
1382 switches::kRendererWaitForJavaDebugger
,
1384 #if defined(OS_MACOSX)
1385 // Allow this to be set when invoking the browser and relayed along.
1386 switches::kEnableSandboxLogging
,
1389 switches::kDisableDirectWrite
,
1390 switches::kEnableWin32kRendererLockDown
,
1391 switches::kDisableWin32kRendererLockDown
,
1393 #if defined(OS_CHROMEOS)
1394 switches::kDisableVaapiAcceleratedVideoEncode
,
1397 renderer_cmd
->CopySwitchesFrom(browser_cmd
, kSwitchNames
,
1398 arraysize(kSwitchNames
));
1400 if (browser_cmd
.HasSwitch(switches::kTraceStartup
) &&
1401 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1402 // Pass kTraceStartup switch to renderer only if startup tracing has not
1404 renderer_cmd
->AppendSwitchASCII(
1405 switches::kTraceStartup
,
1406 browser_cmd
.GetSwitchValueASCII(switches::kTraceStartup
));
1409 // Disable databases in incognito mode.
1410 if (GetBrowserContext()->IsOffTheRecord() &&
1411 !browser_cmd
.HasSwitch(switches::kDisableDatabases
)) {
1412 renderer_cmd
->AppendSwitch(switches::kDisableDatabases
);
1415 // Enforce the extra command line flags for impl-side painting.
1416 if (IsImplSidePaintingEnabled() &&
1417 !browser_cmd
.HasSwitch(switches::kEnableDeferredImageDecoding
))
1418 renderer_cmd
->AppendSwitch(switches::kEnableDeferredImageDecoding
);
1420 // Add kWaitForDebugger to let renderer process wait for a debugger.
1421 if (browser_cmd
.HasSwitch(switches::kWaitForDebuggerChildren
)) {
1422 // Look to pass-on the kWaitForDebugger flag.
1424 browser_cmd
.GetSwitchValueASCII(switches::kWaitForDebuggerChildren
);
1425 if (value
.empty() || value
== switches::kRendererProcess
) {
1426 renderer_cmd
->AppendSwitch(switches::kWaitForDebugger
);
1431 base::ProcessHandle
RenderProcessHostImpl::GetHandle() const {
1432 if (run_renderer_in_process())
1433 return base::GetCurrentProcessHandle();
1435 if (!child_process_launcher_
.get() || child_process_launcher_
->IsStarting())
1436 return base::kNullProcessHandle
;
1438 return child_process_launcher_
->GetProcess().Handle();
1441 bool RenderProcessHostImpl::Shutdown(int exit_code
, bool wait
) {
1442 if (run_renderer_in_process())
1443 return false; // Single process mode never shuts down the renderer.
1445 #if defined(OS_ANDROID)
1446 // Android requires a different approach for killing.
1447 StopChildProcess(GetHandle());
1450 return base::KillProcess(GetHandle(), exit_code
, wait
);
1454 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1455 if (run_renderer_in_process())
1456 return false; // Single process mode never shuts down the renderer.
1458 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1461 if (!child_process_launcher_
.get() ||
1462 child_process_launcher_
->IsStarting() ||
1464 return false; // Render process hasn't started or is probably crashed.
1466 // Test if there's an unload listener.
1467 // NOTE: It's possible that an onunload listener may be installed
1468 // while we're shutting down, so there's a small race here. Given that
1469 // the window is small, it's unlikely that the web page has much
1470 // state that will be lost by not calling its unload handlers properly.
1471 if (!SuddenTerminationAllowed())
1474 if (worker_ref_count_
!= 0) {
1475 if (survive_for_worker_start_time_
.is_null())
1476 survive_for_worker_start_time_
= base::TimeTicks::Now();
1480 // Set this before ProcessDied() so observers can tell if the render process
1481 // died due to fast shutdown versus another cause.
1482 fast_shutdown_started_
= true;
1484 ProcessDied(false /* already_dead */, nullptr);
1488 void RenderProcessHostImpl::DumpHandles() {
1490 Send(new ChildProcessMsg_DumpHandles());
1496 bool RenderProcessHostImpl::Send(IPC::Message
* msg
) {
1497 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1499 if (!is_initialized_
) {
1500 queued_messages_
.push(msg
);
1508 if (child_process_launcher_
.get() && child_process_launcher_
->IsStarting()) {
1509 queued_messages_
.push(msg
);
1513 return channel_
->Send(msg
);
1516 bool RenderProcessHostImpl::SendHelper(scoped_ptr
<IPC::Message
> msg
) {
1517 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1518 return Send(msg
.release());
1521 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message
& msg
) {
1522 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1523 // we ignore incoming messages.
1525 if (deleting_soon_
|| fast_shutdown_started_
)
1528 mark_child_process_activity_time();
1529 if (msg
.routing_id() == MSG_ROUTING_CONTROL
) {
1530 // Dispatch control messages.
1531 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl
, msg
)
1532 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest
,
1534 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone
,
1536 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged
,
1537 SuddenTerminationChanged
)
1538 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction
,
1539 OnUserMetricsRecordAction
)
1540 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML
, OnSavedPageAsMHTML
)
1541 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK
, OnCloseACK
)
1542 #if defined(ENABLE_WEBRTC)
1543 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer
,
1544 OnRegisterAecDumpConsumer
)
1545 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer
,
1546 OnUnregisterAecDumpConsumer
)
1548 // Adding single handlers for your service here is fine, but once your
1549 // service needs more than one handler, please extract them into a new
1550 // message filter and add that filter to CreateMessageFilters().
1551 IPC_END_MESSAGE_MAP()
1556 // Dispatch incoming messages to the appropriate IPC::Listener.
1557 IPC::Listener
* listener
= listeners_
.Lookup(msg
.routing_id());
1559 if (msg
.is_sync()) {
1560 // The listener has gone away, so we must respond or else the caller will
1561 // hang waiting for a reply.
1562 IPC::Message
* reply
= IPC::SyncMessage::GenerateReply(&msg
);
1563 reply
->set_reply_error();
1568 return listener
->OnMessageReceived(msg
);
1571 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid
) {
1572 #if defined(IPC_MESSAGE_LOG_ENABLED)
1573 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1574 IPC::Logging::GetInstance()->Enabled()));
1577 tracked_objects::ThreadData::Status status
=
1578 tracked_objects::ThreadData::status();
1579 Send(new ChildProcessMsg_SetProfilerStatus(status
));
1582 void RenderProcessHostImpl::OnChannelError() {
1583 ProcessDied(true /* already_dead */, nullptr);
1586 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message
& message
) {
1587 // Message de-serialization failed. We consider this a capital crime. Kill the
1588 // renderer if we have one.
1589 LOG(ERROR
) << "bad message " << message
.type() << " terminating renderer.";
1590 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1591 PROCESS_TYPE_RENDERER
);
1592 bad_message::ReceivedBadMessage(this,
1593 bad_message::RPH_DESERIALIZATION_FAILED
);
1596 BrowserContext
* RenderProcessHostImpl::GetBrowserContext() const {
1597 return browser_context_
;
1600 bool RenderProcessHostImpl::InSameStoragePartition(
1601 StoragePartition
* partition
) const {
1602 return storage_partition_impl_
== partition
;
1605 int RenderProcessHostImpl::GetID() const {
1609 bool RenderProcessHostImpl::HasConnection() const {
1610 return channel_
.get() != NULL
;
1613 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events
) {
1614 ignore_input_events_
= ignore_input_events
;
1617 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1618 return ignore_input_events_
;
1621 void RenderProcessHostImpl::Cleanup() {
1622 // If within_process_died_observer_ is true, one of our observers performed an
1623 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1624 // delay the destruction until all of the observer callbacks have been made,
1625 // and guarantee that the RenderProcessHostDestroyed observer callback is
1626 // always the last callback fired.
1627 if (within_process_died_observer_
) {
1628 delayed_cleanup_needed_
= true;
1631 delayed_cleanup_needed_
= false;
1633 // Records the time when the process starts surviving for workers for UMA.
1634 if (listeners_
.IsEmpty() && worker_ref_count_
> 0 &&
1635 survive_for_worker_start_time_
.is_null()) {
1636 survive_for_worker_start_time_
= base::TimeTicks::Now();
1639 // When there are no other owners of this object, we can delete ourselves.
1640 if (listeners_
.IsEmpty() && worker_ref_count_
== 0) {
1641 if (!survive_for_worker_start_time_
.is_null()) {
1642 UMA_HISTOGRAM_LONG_TIMES(
1643 "SharedWorker.RendererSurviveForWorkerTime",
1644 base::TimeTicks::Now() - survive_for_worker_start_time_
);
1647 if (max_worker_count_
> 0) {
1648 // Record the max number of workers (SharedWorker or ServiceWorker)
1649 // that are simultaneously hosted in this renderer process.
1650 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1654 // We cannot clean up twice; if this fails, there is an issue with our
1656 DCHECK(!deleting_soon_
);
1658 DCHECK_EQ(0, pending_views_
);
1659 FOR_EACH_OBSERVER(RenderProcessHostObserver
,
1661 RenderProcessHostDestroyed(this));
1662 NotificationService::current()->Notify(
1663 NOTIFICATION_RENDERER_PROCESS_TERMINATED
,
1664 Source
<RenderProcessHost
>(this),
1665 NotificationService::NoDetails());
1668 is_self_deleted_
= true;
1670 base::MessageLoop::current()->DeleteSoon(FROM_HERE
, this);
1671 deleting_soon_
= true;
1672 // It's important not to wait for the DeleteTask to delete the channel
1673 // proxy. Kill it off now. That way, in case the profile is going away, the
1674 // rest of the objects attached to this RenderProcessHost start going
1675 // away first, since deleting the channel proxy will post a
1676 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1679 // The following members should be cleared in ProcessDied() as well!
1680 gpu_message_filter_
= NULL
;
1681 message_port_message_filter_
= NULL
;
1682 #if defined(ENABLE_BROWSER_CDMS)
1683 browser_cdm_manager_
= NULL
;
1686 RemoveUserData(kSessionStorageHolderKey
);
1688 // Remove ourself from the list of renderer processes so that we can't be
1689 // reused in between now and when the Delete task runs.
1690 UnregisterHost(GetID());
1694 void RenderProcessHostImpl::AddPendingView() {
1698 void RenderProcessHostImpl::RemovePendingView() {
1699 DCHECK(pending_views_
);
1703 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled
) {
1704 sudden_termination_allowed_
= enabled
;
1707 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1708 return sudden_termination_allowed_
;
1711 base::TimeDelta
RenderProcessHostImpl::GetChildProcessIdleTime() const {
1712 return base::TimeTicks::Now() - child_process_activity_time_
;
1715 void RenderProcessHostImpl::ResumeRequestsForView(int route_id
) {
1716 widget_helper_
->ResumeRequestsForView(route_id
);
1719 void RenderProcessHostImpl::FilterURL(bool empty_allowed
, GURL
* url
) {
1720 FilterURL(this, empty_allowed
, url
);
1723 #if defined(ENABLE_WEBRTC)
1724 void RenderProcessHostImpl::EnableAecDump(const base::FilePath
& file
) {
1725 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1726 // Enable AEC dump for each registered consumer.
1727 for (std::vector
<int>::iterator it
= aec_dump_consumers_
.begin();
1728 it
!= aec_dump_consumers_
.end(); ++it
) {
1729 EnableAecDumpForId(file
, *it
);
1733 void RenderProcessHostImpl::DisableAecDump() {
1734 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1735 // Posting on the FILE thread and then replying back on the UI thread is only
1736 // for avoiding races between enable and disable. Nothing is done on the FILE
1738 BrowserThread::PostTaskAndReply(
1739 BrowserThread::FILE, FROM_HERE
,
1740 base::Bind(&DisableAecDumpOnFileThread
),
1741 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer
,
1742 weak_factory_
.GetWeakPtr()));
1745 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1746 base::Callback
<void(const std::string
&)> callback
) {
1747 webrtc_log_message_callback_
= callback
;
1750 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1751 RenderProcessHostImpl::StartRtpDump(
1754 const WebRtcRtpPacketCallback
& packet_callback
) {
1755 if (!p2p_socket_dispatcher_host_
.get())
1756 return WebRtcStopRtpDumpCallback();
1758 BrowserThread::PostTask(BrowserThread::IO
,
1760 base::Bind(&P2PSocketDispatcherHost::StartRtpDump
,
1761 p2p_socket_dispatcher_host_
,
1766 if (stop_rtp_dump_callback_
.is_null()) {
1767 stop_rtp_dump_callback_
=
1768 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread
,
1769 p2p_socket_dispatcher_host_
);
1771 return stop_rtp_dump_callback_
;
1775 IPC::ChannelProxy
* RenderProcessHostImpl::GetChannel() {
1776 return channel_
.get();
1779 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter
* filter
) {
1780 channel_
->AddFilter(filter
->GetFilter());
1783 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count
) {
1784 if (static_cast<size_t>(GetActiveViewCount()) == count
)
1785 return FastShutdownIfPossible();
1789 bool RenderProcessHostImpl::FastShutdownStarted() const {
1790 return fast_shutdown_started_
;
1794 void RenderProcessHostImpl::RegisterHost(int host_id
, RenderProcessHost
* host
) {
1795 g_all_hosts
.Get().AddWithID(host
, host_id
);
1799 void RenderProcessHostImpl::UnregisterHost(int host_id
) {
1800 RenderProcessHost
* host
= g_all_hosts
.Get().Lookup(host_id
);
1804 g_all_hosts
.Get().Remove(host_id
);
1806 // Look up the map of site to process for the given browser_context,
1807 // in case we need to remove this process from it. It will be registered
1808 // under any sites it rendered that use process-per-site mode.
1809 SiteProcessMap
* map
=
1810 GetSiteProcessMapForBrowserContext(host
->GetBrowserContext());
1811 map
->RemoveProcess(host
);
1815 void RenderProcessHostImpl::FilterURL(RenderProcessHost
* rph
,
1818 ChildProcessSecurityPolicyImpl
* policy
=
1819 ChildProcessSecurityPolicyImpl::GetInstance();
1821 if (empty_allowed
&& url
->is_empty())
1824 // The browser process should never hear the swappedout:// URL from any
1825 // of the renderer's messages. Check for this in debug builds, but don't
1826 // let it crash a release browser.
1827 DCHECK(GURL(kSwappedOutURL
) != *url
);
1829 if (!url
->is_valid()) {
1830 // Have to use about:blank for the denied case, instead of an empty GURL.
1831 // This is because the browser treats navigation to an empty GURL as a
1832 // navigation to the home page. This is often a privileged page
1833 // (chrome://newtab/) which is exactly what we don't want.
1834 *url
= GURL(url::kAboutBlankURL
);
1835 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1839 if (url
->SchemeIs(url::kAboutScheme
)) {
1840 // The renderer treats all URLs in the about: scheme as being about:blank.
1841 // Canonicalize about: URLs to about:blank.
1842 *url
= GURL(url::kAboutBlankURL
);
1843 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1846 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1847 // cannot swap processes or grant bindings.
1848 bool non_web_url_in_guest
= rph
->IsIsolatedGuest() &&
1849 !(url
->is_valid() && policy
->IsWebSafeScheme(url
->scheme()));
1851 if (non_web_url_in_guest
|| !policy
->CanRequestURL(rph
->GetID(), *url
)) {
1852 // If this renderer is not permitted to request this URL, we invalidate the
1853 // URL. This prevents us from storing the blocked URL and becoming confused
1855 VLOG(1) << "Blocked URL " << url
->spec();
1856 *url
= GURL(url::kAboutBlankURL
);
1857 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1862 bool RenderProcessHostImpl::IsSuitableHost(
1863 RenderProcessHost
* host
,
1864 BrowserContext
* browser_context
,
1865 const GURL
& site_url
) {
1866 if (run_renderer_in_process())
1869 if (host
->GetBrowserContext() != browser_context
)
1872 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1873 // and non-guest storage gets mixed. In the future, we might consider enabling
1874 // the sharing of guests, in this case this check should be removed and
1875 // InSameStoragePartition should handle the possible sharing.
1876 if (host
->IsIsolatedGuest())
1879 // Check whether the given host and the intended site_url will be using the
1880 // same StoragePartition, since a RenderProcessHost can only support a single
1881 // StoragePartition. This is relevant for packaged apps and isolated sites.
1882 StoragePartition
* dest_partition
=
1883 BrowserContext::GetStoragePartitionForSite(browser_context
, site_url
);
1884 if (!host
->InSameStoragePartition(dest_partition
))
1887 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1889 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1890 browser_context
, site_url
)) {
1894 return GetContentClient()->browser()->IsSuitableHost(host
, site_url
);
1898 bool RenderProcessHost::run_renderer_in_process() {
1899 return g_run_renderer_in_process_
;
1903 void RenderProcessHost::SetRunRendererInProcess(bool value
) {
1904 g_run_renderer_in_process_
= value
;
1906 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
1908 if (!command_line
->HasSwitch(switches::kLang
)) {
1909 // Modify the current process' command line to include the browser locale,
1910 // as the renderer expects this flag to be set.
1911 const std::string locale
=
1912 GetContentClient()->browser()->GetApplicationLocale();
1913 command_line
->AppendSwitchASCII(switches::kLang
, locale
);
1915 // TODO(piman): we should really send configuration through bools rather
1916 // than by parsing strings, i.e. sending an IPC rather than command line
1917 // args. crbug.com/314909
1918 AppendCompositorCommandLineFlags(command_line
);
1923 RenderProcessHost::iterator
RenderProcessHost::AllHostsIterator() {
1924 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1925 return iterator(g_all_hosts
.Pointer());
1929 RenderProcessHost
* RenderProcessHost::FromID(int render_process_id
) {
1930 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1931 return g_all_hosts
.Get().Lookup(render_process_id
);
1935 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1936 BrowserContext
* browser_context
, const GURL
& url
) {
1938 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1939 // try to reuse renderer processes when over the limit. (We could allow pages
1940 // from the same site to share, if we knew what the given process was
1941 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1942 // resource exhaustion issues if too many sites are open at once.
1943 const base::CommandLine
& command_line
=
1944 *base::CommandLine::ForCurrentProcess();
1945 if (command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
) ||
1946 command_line
.HasSwitch(switches::kSitePerProcess
))
1949 if (run_renderer_in_process())
1952 // NOTE: Sometimes it's necessary to create more render processes than
1953 // GetMaxRendererProcessCount(), for instance when we want to create
1954 // a renderer process for a browser context that has no existing
1955 // renderers. This is OK in moderation, since the
1956 // GetMaxRendererProcessCount() is conservative.
1957 if (g_all_hosts
.Get().size() >= GetMaxRendererProcessCount())
1960 return GetContentClient()->browser()->
1961 ShouldTryToUseExistingProcessHost(browser_context
, url
);
1965 RenderProcessHost
* RenderProcessHost::GetExistingProcessHost(
1966 BrowserContext
* browser_context
,
1967 const GURL
& site_url
) {
1968 // First figure out which existing renderers we can use.
1969 std::vector
<RenderProcessHost
*> suitable_renderers
;
1970 suitable_renderers
.reserve(g_all_hosts
.Get().size());
1972 iterator
iter(AllHostsIterator());
1973 while (!iter
.IsAtEnd()) {
1974 if (GetContentClient()->browser()->MayReuseHost(iter
.GetCurrentValue()) &&
1975 RenderProcessHostImpl::IsSuitableHost(
1976 iter
.GetCurrentValue(),
1977 browser_context
, site_url
)) {
1978 suitable_renderers
.push_back(iter
.GetCurrentValue());
1983 // Now pick a random suitable renderer, if we have any.
1984 if (!suitable_renderers
.empty()) {
1985 int suitable_count
= static_cast<int>(suitable_renderers
.size());
1986 int random_index
= base::RandInt(0, suitable_count
- 1);
1987 return suitable_renderers
[random_index
];
1994 bool RenderProcessHost::ShouldUseProcessPerSite(
1995 BrowserContext
* browser_context
,
1997 // Returns true if we should use the process-per-site model. This will be
1998 // the case if the --process-per-site switch is specified, or in
1999 // process-per-site-instance for particular sites (e.g., WebUI).
2000 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2001 const base::CommandLine
& command_line
=
2002 *base::CommandLine::ForCurrentProcess();
2003 if (command_line
.HasSwitch(switches::kProcessPerSite
))
2006 // We want to consolidate particular sites like WebUI even when we are using
2007 // the process-per-tab or process-per-site-instance models.
2008 // Note: DevTools pages have WebUI type but should not reuse the same host.
2009 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2010 browser_context
, url
) &&
2011 !url
.SchemeIs(kChromeDevToolsScheme
)) {
2015 // Otherwise let the content client decide, defaulting to false.
2016 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context
,
2021 RenderProcessHost
* RenderProcessHostImpl::GetProcessHostForSite(
2022 BrowserContext
* browser_context
,
2024 // Look up the map of site to process for the given browser_context.
2025 SiteProcessMap
* map
=
2026 GetSiteProcessMapForBrowserContext(browser_context
);
2028 // See if we have an existing process with appropriate bindings for this site.
2029 // If not, the caller should create a new process and register it.
2030 std::string site
= SiteInstance::GetSiteForURL(browser_context
, url
)
2031 .possibly_invalid_spec();
2032 RenderProcessHost
* host
= map
->FindProcess(site
);
2033 if (host
&& (!GetContentClient()->browser()->MayReuseHost(host
) ||
2034 !IsSuitableHost(host
, browser_context
, url
))) {
2035 // The registered process does not have an appropriate set of bindings for
2036 // the url. Remove it from the map so we can register a better one.
2038 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2039 map
->RemoveProcess(host
);
2046 void RenderProcessHostImpl::RegisterProcessHostForSite(
2047 BrowserContext
* browser_context
,
2048 RenderProcessHost
* process
,
2050 // Look up the map of site to process for the given browser_context.
2051 SiteProcessMap
* map
=
2052 GetSiteProcessMapForBrowserContext(browser_context
);
2054 // Only register valid, non-empty sites. Empty or invalid sites will not
2055 // use process-per-site mode. We cannot check whether the process has
2056 // appropriate bindings here, because the bindings have not yet been granted.
2057 std::string site
= SiteInstance::GetSiteForURL(browser_context
, url
)
2058 .possibly_invalid_spec();
2060 map
->RegisterProcess(site
, process
);
2063 void RenderProcessHostImpl::ProcessDied(bool already_dead
,
2064 RendererClosedDetails
* known_details
) {
2065 // Our child process has died. If we didn't expect it, it's a crash.
2066 // In any case, we need to let everyone know it's gone.
2067 // The OnChannelError notification can fire multiple times due to nested sync
2068 // calls to a renderer. If we don't have a valid channel here it means we
2069 // already handled the error.
2071 // It should not be possible for us to be called re-entrantly.
2072 DCHECK(!within_process_died_observer_
);
2074 // It should not be possible for a process death notification to come in while
2076 DCHECK(!deleting_soon_
);
2078 // child_process_launcher_ can be NULL in single process mode or if fast
2079 // termination happened.
2080 base::TerminationStatus status
= base::TERMINATION_STATUS_NORMAL_TERMINATION
;
2082 if (known_details
) {
2083 status
= known_details
->status
;
2084 exit_code
= known_details
->exit_code
;
2085 } else if (child_process_launcher_
.get()) {
2086 status
= child_process_launcher_
->GetChildTerminationStatus(already_dead
,
2090 RendererClosedDetails
details(status
, exit_code
);
2091 mojo_application_host_
->WillDestroySoon();
2093 child_process_launcher_
.reset();
2095 while (!queued_messages_
.empty()) {
2096 delete queued_messages_
.front();
2097 queued_messages_
.pop();
2100 within_process_died_observer_
= true;
2101 NotificationService::current()->Notify(
2102 NOTIFICATION_RENDERER_PROCESS_CLOSED
,
2103 Source
<RenderProcessHost
>(this),
2104 Details
<RendererClosedDetails
>(&details
));
2105 FOR_EACH_OBSERVER(RenderProcessHostObserver
,
2107 RenderProcessExited(this, status
, exit_code
));
2108 within_process_died_observer_
= false;
2110 gpu_message_filter_
= NULL
;
2111 message_port_message_filter_
= NULL
;
2112 #if defined(ENABLE_BROWSER_CDMS)
2113 browser_cdm_manager_
= NULL
;
2115 RemoveUserData(kSessionStorageHolderKey
);
2117 IDMap
<IPC::Listener
>::iterator
iter(&listeners_
);
2118 while (!iter
.IsAtEnd()) {
2119 iter
.GetCurrentValue()->OnMessageReceived(
2120 FrameHostMsg_RenderProcessGone(iter
.GetCurrentKey(),
2121 static_cast<int>(status
),
2126 mojo_application_host_
.reset(new MojoApplicationHost
);
2128 // It's possible that one of the calls out to the observers might have caused
2129 // this object to be no longer needed.
2130 if (delayed_cleanup_needed_
)
2133 // This object is not deleted at this point and might be reused later.
2134 // TODO(darin): clean this up
2137 int RenderProcessHost::GetActiveViewCount() {
2138 int num_active_views
= 0;
2139 scoped_ptr
<RenderWidgetHostIterator
> widgets(
2140 RenderWidgetHost::GetRenderWidgetHosts());
2141 while (RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
2142 // Count only RenderWidgetHosts in this process.
2143 if (widget
->GetProcess()->GetID() == GetID())
2146 return num_active_views
;
2149 // Frame subscription API for this class is for accelerated composited path
2150 // only. These calls are redirected to GpuMessageFilter.
2151 void RenderProcessHostImpl::BeginFrameSubscription(
2153 scoped_ptr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
2154 if (!gpu_message_filter_
)
2156 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
, base::Bind(
2157 &GpuMessageFilter::BeginFrameSubscription
,
2158 gpu_message_filter_
,
2159 route_id
, base::Passed(&subscriber
)));
2162 void RenderProcessHostImpl::EndFrameSubscription(int route_id
) {
2163 if (!gpu_message_filter_
)
2165 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
, base::Bind(
2166 &GpuMessageFilter::EndFrameSubscription
,
2167 gpu_message_filter_
,
2171 #if defined(ENABLE_WEBRTC)
2172 void RenderProcessHostImpl::WebRtcLogMessage(const std::string
& message
) {
2173 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2174 if (!webrtc_log_message_callback_
.is_null())
2175 webrtc_log_message_callback_
.Run(message
);
2179 void RenderProcessHostImpl::ReleaseOnCloseACK(
2180 RenderProcessHost
* host
,
2181 const SessionStorageNamespaceMap
& sessions
,
2182 int view_route_id
) {
2184 if (sessions
.empty())
2186 SessionStorageHolder
* holder
= static_cast<SessionStorageHolder
*>
2187 (host
->GetUserData(kSessionStorageHolderKey
));
2189 holder
= new SessionStorageHolder();
2191 kSessionStorageHolderKey
,
2194 holder
->Hold(sessions
, view_route_id
);
2197 void RenderProcessHostImpl::OnShutdownRequest() {
2198 // Don't shut down if there are active RenderViews, or if there are pending
2199 // RenderViews being swapped back in.
2200 // In single process mode, we never shutdown the renderer.
2201 int num_active_views
= GetActiveViewCount();
2202 if (pending_views_
|| num_active_views
> 0 || run_renderer_in_process())
2205 // Notify any contents that might have swapped out renderers from this
2206 // process. They should not attempt to swap them back in.
2207 NotificationService::current()->Notify(
2208 NOTIFICATION_RENDERER_PROCESS_CLOSING
,
2209 Source
<RenderProcessHost
>(this),
2210 NotificationService::NoDetails());
2212 mojo_application_host_
->WillDestroySoon();
2214 Send(new ChildProcessMsg_Shutdown());
2217 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled
) {
2218 SetSuddenTerminationAllowed(enabled
);
2221 void RenderProcessHostImpl::OnDumpHandlesDone() {
2225 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded
) {
2226 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2227 "backgrounded", backgrounded
);
2228 // Note: we always set the backgrounded_ value. If the process is NULL
2229 // (and hence hasn't been created yet), we will set the process priority
2230 // later when we create the process.
2231 backgrounded_
= backgrounded
;
2232 if (!child_process_launcher_
.get() || child_process_launcher_
->IsStarting())
2235 // Don't background processes which have active audio streams.
2236 if (backgrounded_
&& audio_renderer_host_
->HasActiveAudio())
2240 // The cbstext.dll loads as a global GetMessage hook in the browser process
2241 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2242 // background thread. If the UI thread invokes this API just when it is
2243 // intercepted the stack is messed up on return from the interceptor
2244 // which causes random crashes in the browser process. Our hack for now
2245 // is to not invoke the SetPriorityClass API if the dll is loaded.
2246 if (GetModuleHandle(L
"cbstext.dll"))
2251 // Same as below, but bound to an experiment (http://crbug.com/458594)
2252 // initially on Windows. Enabled by default in the asbence of field trials to
2253 // get coverage on the perf waterfall.
2254 base::FieldTrial
* trial
=
2255 base::FieldTrialList::Find("BackgroundRendererProcesses");
2256 if (!trial
|| (trial
->group_name() != "Disallow" &&
2257 trial
->group_name() != "AllowBackgroundModeFromRenderer")) {
2258 child_process_launcher_
->SetProcessBackgrounded(backgrounded
);
2261 // Control the background state from the browser process, otherwise the task
2262 // telling the renderer to "unbackground" itself may be preempted by other
2263 // tasks executing at lowered priority ahead of it or simply by not being
2264 // swiftly scheduled by the OS per the low process priority
2265 // (http://crbug.com/398103).
2266 child_process_launcher_
->SetProcessBackgrounded(backgrounded
);
2269 // Notify the child process of background state.
2270 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded
));
2273 void RenderProcessHostImpl::OnProcessLaunched() {
2274 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2276 tracked_objects::ScopedTracker
tracking_profile1(
2277 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2278 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2279 // No point doing anything, since this object will be destructed soon. We
2280 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2281 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2282 // properly cleanup.
2286 if (child_process_launcher_
) {
2287 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2289 tracked_objects::ScopedTracker
tracking_profile2(
2290 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2291 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2292 DCHECK(child_process_launcher_
->GetProcess().IsValid());
2293 SetBackgrounded(backgrounded_
);
2296 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2298 tracked_objects::ScopedTracker
tracking_profile3(
2299 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2300 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2301 // NOTE: This needs to be before sending queued messages because
2302 // ExtensionService uses this notification to initialize the renderer process
2303 // with state that must be there before any JavaScript executes.
2305 // The queued messages contain such things as "navigate". If this notification
2306 // was after, we can end up executing JavaScript before the initialization
2308 NotificationService::current()->Notify(
2309 NOTIFICATION_RENDERER_PROCESS_CREATED
,
2310 Source
<RenderProcessHost
>(this),
2311 NotificationService::NoDetails());
2313 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2315 tracked_objects::ScopedTracker
tracking_profile4(
2316 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2317 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2318 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2319 // This way, Mojo can be safely used from the renderer in response to any
2320 // Chrome IPC message.
2321 mojo_application_host_
->Activate(this, GetHandle());
2323 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2325 tracked_objects::ScopedTracker
tracking_profile5(
2326 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2327 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2328 if (channel_mojo_host_
)
2329 channel_mojo_host_
->OnClientLaunched(GetHandle());
2331 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2333 tracked_objects::ScopedTracker
tracking_profile6(
2334 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2336 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2337 while (!queued_messages_
.empty()) {
2338 Send(queued_messages_
.front());
2339 queued_messages_
.pop();
2342 base::PostTaskAndReplyWithResult(
2343 media::AudioManager::Get()->GetWorkerTaskRunner().get(), FROM_HERE
,
2344 base::Bind(&SendAudioHardwareConfig
),
2345 base::Bind(base::IgnoreResult(&RenderProcessHostImpl::SendHelper
),
2346 weak_factory_
.GetWeakPtr()));
2348 #if defined(ENABLE_WEBRTC)
2349 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2351 tracked_objects::ScopedTracker
tracking_profile7(
2352 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2353 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2354 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2355 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2359 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2360 RendererClosedDetails details
{ base::TERMINATION_STATUS_PROCESS_WAS_KILLED
,
2362 ProcessDied(true, &details
);
2365 scoped_refptr
<AudioRendererHost
>
2366 RenderProcessHostImpl::audio_renderer_host() const {
2367 return audio_renderer_host_
;
2370 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2371 const std::string
& action
) {
2372 RecordComputedAction(action
);
2375 void RenderProcessHostImpl::OnCloseACK(int old_route_id
) {
2376 SessionStorageHolder
* holder
= static_cast<SessionStorageHolder
*>
2377 (GetUserData(kSessionStorageHolderKey
));
2380 holder
->Release(old_route_id
);
2383 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id
, int64 data_size
) {
2384 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id
, data_size
);
2387 void RenderProcessHostImpl::OnGpuSwitched() {
2388 // We are updating all widgets including swapped out ones.
2389 scoped_ptr
<RenderWidgetHostIterator
> widgets(
2390 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2391 while (RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
2392 if (!widget
->IsRenderView())
2395 // Skip widgets in other processes.
2396 if (widget
->GetProcess()->GetID() != GetID())
2399 RenderViewHost
* rvh
= RenderViewHost::From(widget
);
2400 rvh
->OnWebkitPreferencesChanged();
2404 #if defined(ENABLE_WEBRTC)
2405 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id
) {
2406 BrowserThread::PostTask(
2410 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread
,
2411 weak_factory_
.GetWeakPtr(),
2415 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id
) {
2416 BrowserThread::PostTask(
2420 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread
,
2421 weak_factory_
.GetWeakPtr(),
2425 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id
) {
2426 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2427 aec_dump_consumers_
.push_back(id
);
2428 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2429 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2434 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id
) {
2435 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2436 for (std::vector
<int>::iterator it
= aec_dump_consumers_
.begin();
2437 it
!= aec_dump_consumers_
.end(); ++it
) {
2439 aec_dump_consumers_
.erase(it
);
2446 #define IntToStringType base::IntToString16
2448 #define IntToStringType base::IntToString
2451 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath
& file
,
2453 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2454 base::FilePath unique_file
=
2455 file
.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2456 .AddExtension(IntToStringType(id
));
2457 BrowserThread::PostTaskAndReplyWithResult(
2458 BrowserThread::FILE, FROM_HERE
,
2459 base::Bind(&CreateAecDumpFileForProcess
, unique_file
, GetHandle()),
2460 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer
,
2461 weak_factory_
.GetWeakPtr(),
2465 #undef IntToStringType
2467 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2469 IPC::PlatformFileForTransit file_for_transit
) {
2470 if (file_for_transit
== IPC::InvalidPlatformFileForTransit())
2472 Send(new AecDumpMsg_EnableAecDump(id
, file_for_transit
));
2475 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2476 Send(new AecDumpMsg_DisableAecDump());
2480 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2481 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2482 ++worker_ref_count_
;
2483 if (worker_ref_count_
> max_worker_count_
)
2484 max_worker_count_
= worker_ref_count_
;
2487 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2488 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2489 DCHECK_GT(worker_ref_count_
, 0);
2490 --worker_ref_count_
;
2491 if (worker_ref_count_
== 0)
2495 void RenderProcessHostImpl::GetAudioOutputControllers(
2496 const GetAudioOutputControllersCallback
& callback
) const {
2497 audio_renderer_host()->GetOutputControllers(callback
);
2500 } // namespace content