1 // Copyright 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/debug/dump_without_crashing.h"
20 #include "base/files/file.h"
21 #include "base/lazy_instance.h"
22 #include "base/location.h"
23 #include "base/logging.h"
24 #include "base/metrics/field_trial.h"
25 #include "base/metrics/histogram.h"
26 #include "base/process/process_handle.h"
27 #include "base/profiler/scoped_tracker.h"
28 #include "base/rand_util.h"
29 #include "base/single_thread_task_runner.h"
30 #include "base/stl_util.h"
31 #include "base/strings/string_number_conversions.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/trace_event/trace_event.h"
38 #include "base/tracked_objects.h"
39 #include "cc/base/switches.h"
40 #include "components/scheduler/common/scheduler_switches.h"
41 #include "content/browser/appcache/appcache_dispatcher_host.h"
42 #include "content/browser/appcache/chrome_appcache_service.h"
43 #include "content/browser/background_sync/background_sync_service_impl.h"
44 #include "content/browser/bad_message.h"
45 #include "content/browser/bluetooth/bluetooth_dispatcher_host.h"
46 #include "content/browser/browser_child_process_host_impl.h"
47 #include "content/browser/browser_main.h"
48 #include "content/browser/browser_main_loop.h"
49 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
50 #include "content/browser/cache_storage/cache_storage_context_impl.h"
51 #include "content/browser/cache_storage/cache_storage_dispatcher_host.h"
52 #include "content/browser/child_process_security_policy_impl.h"
53 #include "content/browser/device_sensors/device_light_message_filter.h"
54 #include "content/browser/device_sensors/device_motion_message_filter.h"
55 #include "content/browser/device_sensors/device_orientation_message_filter.h"
56 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
57 #include "content/browser/dom_storage/dom_storage_message_filter.h"
58 #include "content/browser/download/mhtml_generation_manager.h"
59 #include "content/browser/fileapi/chrome_blob_storage_context.h"
60 #include "content/browser/fileapi/fileapi_message_filter.h"
61 #include "content/browser/frame_host/render_frame_message_filter.h"
62 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
63 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
64 #include "content/browser/gpu/compositor_util.h"
65 #include "content/browser/gpu/gpu_data_manager_impl.h"
66 #include "content/browser/gpu/gpu_process_host.h"
67 #include "content/browser/gpu/shader_disk_cache.h"
68 #include "content/browser/histogram_message_filter.h"
69 #include "content/browser/indexed_db/indexed_db_context_impl.h"
70 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
71 #include "content/browser/loader/resource_message_filter.h"
72 #include "content/browser/loader/resource_scheduler_filter.h"
73 #include "content/browser/media/capture/audio_mirroring_manager.h"
74 #include "content/browser/media/media_internals.h"
75 #include "content/browser/media/midi_host.h"
76 #include "content/browser/message_port_message_filter.h"
77 #include "content/browser/mime_registry_message_filter.h"
78 #include "content/browser/mojo/mojo_application_host.h"
79 #include "content/browser/navigator_connect/service_port_service_impl.h"
80 #include "content/browser/notifications/notification_message_filter.h"
81 #include "content/browser/permissions/permission_service_context.h"
82 #include "content/browser/permissions/permission_service_impl.h"
83 #include "content/browser/profiler_message_filter.h"
84 #include "content/browser/push_messaging/push_messaging_message_filter.h"
85 #include "content/browser/quota_dispatcher_host.h"
86 #include "content/browser/renderer_host/clipboard_message_filter.h"
87 #include "content/browser/renderer_host/database_message_filter.h"
88 #include "content/browser/renderer_host/file_utilities_message_filter.h"
89 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
90 #include "content/browser/renderer_host/gpu_message_filter.h"
91 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
92 #include "content/browser/renderer_host/media/audio_renderer_host.h"
93 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
94 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
95 #include "content/browser/renderer_host/media/video_capture_host.h"
96 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
97 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
98 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
99 #include "content/browser/renderer_host/render_message_filter.h"
100 #include "content/browser/renderer_host/render_view_host_delegate.h"
101 #include "content/browser/renderer_host/render_view_host_impl.h"
102 #include "content/browser/renderer_host/render_widget_helper.h"
103 #include "content/browser/renderer_host/render_widget_host_impl.h"
104 #include "content/browser/renderer_host/text_input_client_message_filter.h"
105 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
106 #include "content/browser/resolve_proxy_msg_helper.h"
107 #include "content/browser/service_worker/service_worker_context_wrapper.h"
108 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
109 #include "content/browser/shared_worker/shared_worker_message_filter.h"
110 #include "content/browser/shared_worker/worker_storage_partition.h"
111 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
112 #include "content/browser/storage_partition_impl.h"
113 #include "content/browser/streams/stream_context.h"
114 #include "content/browser/tracing/trace_message_filter.h"
115 #include "content/browser/webui/web_ui_controller_factory_registry.h"
116 #include "content/common/child_process_host_impl.h"
117 #include "content/common/child_process_messages.h"
118 #include "content/common/content_switches_internal.h"
119 #include "content/common/frame_messages.h"
120 #include "content/common/gpu/gpu_messages.h"
121 #include "content/common/in_process_child_thread_params.h"
122 #include "content/common/mojo/channel_init.h"
123 #include "content/common/mojo/mojo_messages.h"
124 #include "content/common/resource_messages.h"
125 #include "content/common/view_messages.h"
126 #include "content/public/browser/browser_context.h"
127 #include "content/public/browser/content_browser_client.h"
128 #include "content/public/browser/navigator_connect_context.h"
129 #include "content/public/browser/notification_service.h"
130 #include "content/public/browser/notification_types.h"
131 #include "content/public/browser/render_process_host_factory.h"
132 #include "content/public/browser/render_process_host_observer.h"
133 #include "content/public/browser/render_widget_host.h"
134 #include "content/public/browser/render_widget_host_iterator.h"
135 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
136 #include "content/public/browser/resource_context.h"
137 #include "content/public/browser/user_metrics.h"
138 #include "content/public/browser/worker_service.h"
139 #include "content/public/common/child_process_host.h"
140 #include "content/public/common/content_constants.h"
141 #include "content/public/common/content_switches.h"
142 #include "content/public/common/mojo_channel_switches.h"
143 #include "content/public/common/process_type.h"
144 #include "content/public/common/resource_type.h"
145 #include "content/public/common/result_codes.h"
146 #include "content/public/common/sandboxed_process_launcher_delegate.h"
147 #include "content/public/common/url_constants.h"
148 #include "device/battery/battery_monitor_impl.h"
149 #include "device/vibration/vibration_manager_impl.h"
150 #include "gpu/GLES2/gl2extchromium.h"
151 #include "gpu/command_buffer/client/gpu_switches.h"
152 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
153 #include "gpu/command_buffer/service/gpu_switches.h"
154 #include "ipc/ipc_channel.h"
155 #include "ipc/ipc_logging.h"
156 #include "ipc/ipc_switches.h"
157 #include "ipc/mojo/ipc_channel_mojo.h"
158 #include "media/base/media_switches.h"
159 #include "net/url_request/url_request_context_getter.h"
160 #include "ppapi/shared_impl/ppapi_switches.h"
161 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
162 #include "third_party/icu/source/common/unicode/unistr.h"
163 #include "third_party/icu/source/i18n/unicode/timezone.h"
164 #include "third_party/skia/include/core/SkBitmap.h"
165 #include "ui/base/ui_base_switches.h"
166 #include "ui/events/event_switches.h"
167 #include "ui/gfx/switches.h"
168 #include "ui/gl/gl_switches.h"
169 #include "ui/gl/gpu_switching_manager.h"
170 #include "ui/native_theme/native_theme_switches.h"
172 #if defined(OS_ANDROID)
173 #include "content/browser/android/child_process_launcher_android.h"
174 #include "content/browser/media/android/browser_demuxer_android.h"
175 #include "content/browser/mojo/service_registrar_android.h"
176 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
180 #include "base/win/scoped_com_initializer.h"
181 #include "base/win/windows_version.h"
182 #include "content/common/font_cache_dispatcher_win.h"
183 #include "content/common/sandbox_win.h"
184 #include "sandbox/win/src/sandbox_policy.h"
185 #include "ui/gfx/win/dpi.h"
188 #if defined(OS_MACOSX) && !defined(OS_IOS)
189 #include "content/browser/browser_io_surface_manager_mac.h"
192 #if defined(ENABLE_BROWSER_CDMS)
193 #include "content/browser/media/cdm/browser_cdm_manager.h"
196 #if defined(ENABLE_PLUGINS)
197 #include "content/browser/plugin_service_impl.h"
200 #if defined(ENABLE_WEBRTC)
201 #include "content/browser/media/webrtc_internals.h"
202 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
203 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
204 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
205 #include "content/common/media/aec_dump_messages.h"
206 #include "content/common/media/media_stream_messages.h"
209 extern bool g_exited_main_message_loop
;
214 const char kSiteProcessMapKeyName
[] = "content_site_process_map";
216 void CacheShaderInfo(int32 id
, base::FilePath path
) {
217 ShaderCacheFactory::GetInstance()->SetCacheInfo(id
, path
);
220 void RemoveShaderInfo(int32 id
) {
221 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id
);
224 net::URLRequestContext
* GetRequestContext(
225 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
226 scoped_refptr
<net::URLRequestContextGetter
> media_request_context
,
227 ResourceType resource_type
) {
228 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
229 // context specific to media for handling it because these resources have
230 // specific needs for caching.
231 if (resource_type
== RESOURCE_TYPE_MEDIA
)
232 return media_request_context
->GetURLRequestContext();
233 return request_context
->GetURLRequestContext();
237 ResourceContext
* resource_context
,
238 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
239 scoped_refptr
<net::URLRequestContextGetter
> media_request_context
,
240 const ResourceHostMsg_Request
& request
,
241 ResourceContext
** resource_context_out
,
242 net::URLRequestContext
** request_context_out
) {
243 *resource_context_out
= resource_context
;
244 *request_context_out
=
245 GetRequestContext(request_context
, media_request_context
,
246 request
.resource_type
);
249 #if defined(ENABLE_WEBRTC)
251 // Allow us to only run the trial in the first renderer.
252 bool has_done_stun_trials
= false;
254 // Creates a file used for diagnostic echo canceller recordings for handing
255 // over to the renderer.
256 IPC::PlatformFileForTransit
CreateAecDumpFileForProcess(
257 base::FilePath file_path
,
258 base::ProcessHandle process
) {
259 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
260 base::File
dump_file(file_path
,
261 base::File::FLAG_OPEN_ALWAYS
| base::File::FLAG_APPEND
);
262 if (!dump_file
.IsValid()) {
263 VLOG(1) << "Could not open AEC dump file, error=" <<
264 dump_file
.error_details();
265 return IPC::InvalidPlatformFileForTransit();
267 return IPC::TakeFileHandleForProcess(dump_file
.Pass(), process
);
270 // Does nothing. Just to avoid races between enable and disable.
271 void DisableAecDumpOnFileThread() {
272 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
276 // the global list of all renderer processes
277 base::LazyInstance
<IDMap
<RenderProcessHost
> >::Leaky
278 g_all_hosts
= LAZY_INSTANCE_INITIALIZER
;
280 // Map of site to process, to ensure we only have one RenderProcessHost per
281 // site in process-per-site mode. Each map is specific to a BrowserContext.
282 class SiteProcessMap
: public base::SupportsUserData::Data
{
284 typedef base::hash_map
<std::string
, RenderProcessHost
*> SiteToProcessMap
;
287 void RegisterProcess(const std::string
& site
, RenderProcessHost
* process
) {
288 map_
[site
] = process
;
291 RenderProcessHost
* FindProcess(const std::string
& site
) {
292 SiteToProcessMap::iterator i
= map_
.find(site
);
298 void RemoveProcess(RenderProcessHost
* host
) {
299 // Find all instances of this process in the map, then separately remove
301 std::set
<std::string
> sites
;
302 for (SiteToProcessMap::const_iterator i
= map_
.begin();
305 if (i
->second
== host
)
306 sites
.insert(i
->first
);
308 for (std::set
<std::string
>::iterator i
= sites
.begin();
311 SiteToProcessMap::iterator iter
= map_
.find(*i
);
312 if (iter
!= map_
.end()) {
313 DCHECK_EQ(iter
->second
, host
);
320 SiteToProcessMap map_
;
323 // Find the SiteProcessMap specific to the given context.
324 SiteProcessMap
* GetSiteProcessMapForBrowserContext(BrowserContext
* context
) {
326 SiteProcessMap
* map
= static_cast<SiteProcessMap
*>(
327 context
->GetUserData(kSiteProcessMapKeyName
));
329 map
= new SiteProcessMap();
330 context
->SetUserData(kSiteProcessMapKeyName
, map
);
335 // NOTE: changes to this class need to be reviewed by the security team.
336 class RendererSandboxedProcessLauncherDelegate
337 : public SandboxedProcessLauncherDelegate
{
339 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy
* channel
)
340 #if defined(OS_POSIX)
341 : ipc_fd_(channel
->TakeClientFileDescriptor())
345 ~RendererSandboxedProcessLauncherDelegate() override
{}
348 void PreSpawnTarget(sandbox::TargetPolicy
* policy
, bool* success
) override
{
349 AddBaseHandleClosePolicy(policy
);
351 const base::string16
& sid
=
352 GetContentClient()->browser()->GetAppContainerSidForSandboxType(
355 AddAppContainerPolicy(policy
, sid
.c_str());
357 GetContentClient()->browser()->PreSpawnRenderer(policy
, success
);
360 #elif defined(OS_POSIX)
361 bool ShouldUseZygote() override
{
362 const base::CommandLine
& browser_command_line
=
363 *base::CommandLine::ForCurrentProcess();
364 base::CommandLine::StringType renderer_prefix
=
365 browser_command_line
.GetSwitchValueNative(switches::kRendererCmdPrefix
);
366 return renderer_prefix
.empty();
368 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
371 SandboxType
GetSandboxType() override
{
372 return SANDBOX_TYPE_RENDERER
;
376 #if defined(OS_POSIX)
377 base::ScopedFD ipc_fd_
;
381 const char kSessionStorageHolderKey
[] = "kSessionStorageHolderKey";
383 class SessionStorageHolder
: public base::SupportsUserData::Data
{
385 SessionStorageHolder() {}
386 ~SessionStorageHolder() override
{}
388 void Hold(const SessionStorageNamespaceMap
& sessions
, int view_route_id
) {
389 session_storage_namespaces_awaiting_close_
[view_route_id
] = sessions
;
392 void Release(int old_route_id
) {
393 session_storage_namespaces_awaiting_close_
.erase(old_route_id
);
397 std::map
<int, SessionStorageNamespaceMap
>
398 session_storage_namespaces_awaiting_close_
;
399 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder
);
404 RendererMainThreadFactoryFunction g_renderer_main_thread_factory
= NULL
;
406 base::MessageLoop
* g_in_process_thread
;
409 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
410 return g_in_process_thread
;
413 // Stores the maximum number of renderer processes the content module can
415 static size_t g_max_renderer_count_override
= 0;
418 size_t RenderProcessHost::GetMaxRendererProcessCount() {
419 if (g_max_renderer_count_override
)
420 return g_max_renderer_count_override
;
422 #if defined(OS_ANDROID)
423 // On Android we don't maintain a limit of renderer process hosts - we are
424 // happy with keeping a lot of these, as long as the number of live renderer
425 // processes remains reasonable, and on Android the OS takes care of that.
426 return std::numeric_limits
<size_t>::max();
429 // On other platforms, we calculate the maximum number of renderer process
430 // hosts according to the amount of installed memory as reported by the OS.
431 // The calculation assumes that you want the renderers to use half of the
432 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
433 // this assumption, you need to adjust the ThirtyFourTabs test to match the
434 // expected number of processes.
436 // With the given amounts of installed memory below on a 32-bit CPU, the
437 // maximum renderer count will roughly be as follows:
443 // 16384 MB -> 82 (kMaxRendererProcessCount)
445 static size_t max_count
= 0;
447 const size_t kEstimatedWebContentsMemoryUsage
=
448 #if defined(ARCH_CPU_64_BITS)
453 max_count
= base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
454 max_count
/= kEstimatedWebContentsMemoryUsage
;
456 const size_t kMinRendererProcessCount
= 3;
457 max_count
= std::max(max_count
, kMinRendererProcessCount
);
458 max_count
= std::min(max_count
, kMaxRendererProcessCount
);
464 bool g_run_renderer_in_process_
= false;
467 void RenderProcessHost::SetMaxRendererProcessCount(size_t count
) {
468 g_max_renderer_count_override
= count
;
471 RenderProcessHostImpl::RenderProcessHostImpl(
472 BrowserContext
* browser_context
,
473 StoragePartitionImpl
* storage_partition_impl
,
474 bool is_for_guests_only
)
475 : fast_shutdown_started_(false),
476 deleting_soon_(false),
478 is_self_deleted_(false),
481 mojo_application_host_(new MojoApplicationHost
),
484 is_initialized_(false),
485 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
486 browser_context_(browser_context
),
487 storage_partition_impl_(storage_partition_impl
),
488 sudden_termination_allowed_(true),
489 ignore_input_events_(false),
490 is_for_guests_only_(is_for_guests_only
),
491 gpu_observer_registered_(false),
492 delayed_cleanup_needed_(false),
493 within_process_died_observer_(false),
494 power_monitor_broadcaster_(this),
495 worker_ref_count_(0),
496 max_worker_count_(0),
497 permission_service_context_(new PermissionServiceContext(this)),
498 pending_valuebuffer_state_(new gpu::ValueStateMap()),
499 subscribe_uniform_enabled_(false),
500 weak_factory_(this) {
501 widget_helper_
= new RenderWidgetHelper();
503 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
505 CHECK(!g_exited_main_message_loop
);
506 RegisterHost(GetID(), this);
507 g_all_hosts
.Get().set_check_on_null_data(true);
508 // Initialize |child_process_activity_time_| to a reasonable value.
509 mark_child_process_activity_time();
511 if (!GetBrowserContext()->IsOffTheRecord() &&
512 !base::CommandLine::ForCurrentProcess()->HasSwitch(
513 switches::kDisableGpuShaderDiskCache
)) {
514 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
515 base::Bind(&CacheShaderInfo
, GetID(),
516 storage_partition_impl_
->GetPath()));
518 subscribe_uniform_enabled_
=
519 base::CommandLine::ForCurrentProcess()->HasSwitch(
520 switches::kEnableSubscribeUniformExtension
);
522 // Note: When we create the RenderProcessHostImpl, it's technically
523 // backgrounded, because it has no visible listeners. But the process
524 // doesn't actually exist yet, so we'll Background it later, after
529 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
530 DCHECK(g_run_renderer_in_process_
);
532 switch (g_all_hosts
.Pointer()->size()) {
536 RenderProcessHostImpl
* host
= static_cast<RenderProcessHostImpl
*>(
537 AllHostsIterator().GetCurrentValue());
538 FOR_EACH_OBSERVER(RenderProcessHostObserver
,
540 RenderProcessHostDestroyed(host
));
542 host
->is_self_deleted_
= true;
548 NOTREACHED() << "There should be only one RenderProcessHost when running "
553 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
554 RendererMainThreadFactoryFunction create
) {
555 g_renderer_main_thread_factory
= create
;
558 RenderProcessHostImpl::~RenderProcessHostImpl() {
560 DCHECK(is_self_deleted_
)
561 << "RenderProcessHostImpl is destroyed by something other than itself";
564 // Make sure to clean up the in-process renderer before the channel, otherwise
565 // it may still run and have its IPCs fail, causing asserts.
566 in_process_renderer_
.reset();
568 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
570 if (gpu_observer_registered_
) {
571 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
572 gpu_observer_registered_
= false;
575 // We may have some unsent messages at this point, but that's OK.
577 while (!queued_messages_
.empty()) {
578 delete queued_messages_
.front();
579 queued_messages_
.pop();
582 UnregisterHost(GetID());
584 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
585 switches::kDisableGpuShaderDiskCache
)) {
586 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
587 base::Bind(&RemoveShaderInfo
, GetID()));
591 void RenderProcessHostImpl::EnableSendQueue() {
592 is_initialized_
= false;
595 bool RenderProcessHostImpl::Init() {
596 // calling Init() more than once does nothing, this makes it more convenient
597 // for the view host which may not be sure in some cases
601 base::CommandLine::StringType renderer_prefix
;
602 // A command prefix is something prepended to the command line of the spawned
604 const base::CommandLine
& browser_command_line
=
605 *base::CommandLine::ForCurrentProcess();
607 browser_command_line
.GetSwitchValueNative(switches::kRendererCmdPrefix
);
609 #if defined(OS_LINUX)
610 int flags
= renderer_prefix
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
611 ChildProcessHost::CHILD_NORMAL
;
613 int flags
= ChildProcessHost::CHILD_NORMAL
;
616 // Find the renderer before creating the channel so if this fails early we
617 // return without creating the channel.
618 base::FilePath renderer_path
= ChildProcessHost::GetChildPath(flags
);
619 if (renderer_path
.empty())
622 // Setup the IPC channel.
623 const std::string channel_id
=
624 IPC::Channel::GenerateVerifiedChannelID(std::string());
625 channel_
= CreateChannelProxy(channel_id
);
627 // Setup the Mojo channel.
628 mojo_application_host_
->Init();
630 // Call the embedder first so that their IPC filters have priority.
631 GetContentClient()->browser()->RenderProcessWillLaunch(this);
633 CreateMessageFilters();
634 RegisterMojoServices();
636 if (run_renderer_in_process()) {
637 DCHECK(g_renderer_main_thread_factory
);
638 // Crank up a thread and run the initialization there. With the way that
639 // messages flow between the browser and renderer, this thread is required
640 // to prevent a deadlock in single-process mode. Since the primordial
641 // thread in the renderer process runs the WebKit code and can sometimes
642 // make blocking calls to the UI thread (i.e. this thread), they need to run
643 // on separate threads.
644 in_process_renderer_
.reset(
645 g_renderer_main_thread_factory(InProcessChildThreadParams(
646 channel_id
, BrowserThread::UnsafeGetMessageLoopForThread(
647 BrowserThread::IO
)->task_runner())));
649 base::Thread::Options options
;
650 #if defined(OS_WIN) && !defined(OS_MACOSX)
651 // In-process plugins require this to be a UI message loop.
652 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
654 // We can't have multiple UI loops on Linux and Android, so we don't support
655 // in-process plugins.
656 options
.message_loop_type
= base::MessageLoop::TYPE_DEFAULT
;
659 // As for execution sequence, this callback should have no any dependency
660 // on starting in-process-render-thread.
661 // So put it here to trigger ChannelMojo initialization earlier to enable
662 // in-process-render-thread using ChannelMojo there.
663 OnProcessLaunched(); // Fake a callback that the process is ready.
665 in_process_renderer_
->StartWithOptions(options
);
667 g_in_process_thread
= in_process_renderer_
->message_loop();
670 // Build command line for renderer. We call AppendRendererCommandLine()
671 // first so the process type argument will appear first.
672 base::CommandLine
* cmd_line
= new base::CommandLine(renderer_path
);
673 if (!renderer_prefix
.empty())
674 cmd_line
->PrependWrapper(renderer_prefix
);
675 AppendRendererCommandLine(cmd_line
);
676 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
678 // Spawn the child process asynchronously to avoid blocking the UI thread.
679 // As long as there's no renderer prefix, we can use the zygote process
681 child_process_launcher_
.reset(new ChildProcessLauncher(
682 new RendererSandboxedProcessLauncherDelegate(channel_
.get()),
687 fast_shutdown_started_
= false;
690 if (!gpu_observer_registered_
) {
691 gpu_observer_registered_
= true;
692 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
695 power_monitor_broadcaster_
.Init();
697 is_initialized_
= true;
698 init_time_
= base::TimeTicks::Now();
702 scoped_ptr
<IPC::ChannelProxy
> RenderProcessHostImpl::CreateChannelProxy(
703 const std::string
& channel_id
) {
704 scoped_refptr
<base::SingleThreadTaskRunner
> runner
=
705 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
706 scoped_refptr
<base::SequencedTaskRunner
> mojo_task_runner
=
707 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO
)
709 if (ShouldUseMojoChannel()) {
710 VLOG(1) << "Mojo Channel is enabled on host";
712 return IPC::ChannelProxy::Create(
713 IPC::ChannelMojo::CreateServerFactory(
714 mojo_task_runner
, channel_id
,
715 content::ChildProcessHost::GetAttachmentBroker()),
719 return IPC::ChannelProxy::Create(
720 channel_id
, IPC::Channel::MODE_SERVER
, this, runner
.get(),
721 content::ChildProcessHost::GetAttachmentBroker());
724 void RenderProcessHostImpl::CreateMessageFilters() {
725 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
726 const base::CommandLine
& browser_command_line
=
727 *base::CommandLine::ForCurrentProcess();
728 AddFilter(new ResourceSchedulerFilter(GetID()));
729 MediaInternals
* media_internals
= MediaInternals::GetInstance();
730 media::AudioManager
* audio_manager
=
731 BrowserMainLoop::GetInstance()->audio_manager();
732 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
734 scoped_refptr
<BrowserPluginMessageFilter
> bp_message_filter(
735 new BrowserPluginMessageFilter(GetID()));
736 AddFilter(bp_message_filter
.get());
738 scoped_refptr
<RenderMessageFilter
> render_message_filter(
739 new RenderMessageFilter(
741 #if defined(ENABLE_PLUGINS)
742 PluginServiceImpl::GetInstance(),
747 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
748 widget_helper_
.get(),
751 storage_partition_impl_
->GetDOMStorageContext()));
752 AddFilter(render_message_filter
.get());
754 new RenderFrameMessageFilter(GetID(), widget_helper_
.get()));
755 BrowserContext
* browser_context
= GetBrowserContext();
756 ResourceContext
* resource_context
= browser_context
->GetResourceContext();
758 scoped_refptr
<net::URLRequestContextGetter
> request_context(
759 browser_context
->GetRequestContextForRenderProcess(GetID()));
760 scoped_refptr
<net::URLRequestContextGetter
> media_request_context(
761 browser_context
->GetMediaRequestContextForRenderProcess(GetID()));
763 ResourceMessageFilter::GetContextsCallback
get_contexts_callback(
764 base::Bind(&GetContexts
, browser_context
->GetResourceContext(),
765 request_context
, media_request_context
));
767 ResourceMessageFilter
* resource_message_filter
= new ResourceMessageFilter(
768 GetID(), PROCESS_TYPE_RENDERER
,
769 storage_partition_impl_
->GetAppCacheService(),
770 ChromeBlobStorageContext::GetFor(browser_context
),
771 storage_partition_impl_
->GetFileSystemContext(),
772 storage_partition_impl_
->GetServiceWorkerContext(),
773 storage_partition_impl_
->GetHostZoomLevelContext(),
774 get_contexts_callback
);
776 AddFilter(resource_message_filter
);
777 MediaStreamManager
* media_stream_manager
=
778 BrowserMainLoop::GetInstance()->media_stream_manager();
779 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 browser_context
->GetResourceContext()->GetMediaDeviceIDSalt());
794 AddFilter(audio_renderer_host_
.get());
796 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
797 AddFilter(new VideoCaptureHost(media_stream_manager
));
798 AddFilter(new AppCacheDispatcherHost(
799 storage_partition_impl_
->GetAppCacheService(),
801 AddFilter(new ClipboardMessageFilter
);
802 AddFilter(new DOMStorageMessageFilter(
803 storage_partition_impl_
->GetDOMStorageContext()));
804 AddFilter(new IndexedDBDispatcherHost(
806 storage_partition_impl_
->GetURLRequestContext(),
807 storage_partition_impl_
->GetIndexedDBContext(),
808 ChromeBlobStorageContext::GetFor(browser_context
)));
810 gpu_message_filter_
= new GpuMessageFilter(GetID(), widget_helper_
.get());
811 AddFilter(gpu_message_filter_
);
812 #if defined(ENABLE_WEBRTC)
813 AddFilter(new WebRTCIdentityServiceHost(
815 storage_partition_impl_
->GetWebRTCIdentityStore(),
817 peer_connection_tracker_host_
= new PeerConnectionTrackerHost(GetID());
818 AddFilter(peer_connection_tracker_host_
.get());
819 AddFilter(new MediaStreamDispatcherHost(
821 browser_context
->GetResourceContext()->GetMediaDeviceIDSalt(),
822 media_stream_manager
));
823 AddFilter(new MediaStreamTrackMetricsHost());
825 #if defined(ENABLE_PLUGINS)
826 AddFilter(new PepperRendererConnection(GetID()));
828 AddFilter(new SpeechRecognitionDispatcherHost(
829 GetID(), storage_partition_impl_
->GetURLRequestContext()));
830 AddFilter(new FileAPIMessageFilter(
832 storage_partition_impl_
->GetURLRequestContext(),
833 storage_partition_impl_
->GetFileSystemContext(),
834 ChromeBlobStorageContext::GetFor(browser_context
),
835 StreamContext::GetFor(browser_context
)));
836 AddFilter(new FileUtilitiesMessageFilter(GetID()));
837 AddFilter(new MimeRegistryMessageFilter());
838 AddFilter(new DatabaseMessageFilter(
839 storage_partition_impl_
->GetDatabaseTracker()));
840 #if defined(OS_MACOSX)
841 AddFilter(new TextInputClientMessageFilter(GetID()));
842 #elif defined(OS_WIN)
843 // The FontCacheDispatcher is required only when we're using GDI rendering.
844 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
845 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
846 // should eventually be if (!ShouldUseDirectWrite()) guarded.
847 channel_
->AddFilter(new FontCacheDispatcher());
848 #elif defined(OS_ANDROID)
849 browser_demuxer_android_
= new BrowserDemuxerAndroid();
850 AddFilter(browser_demuxer_android_
.get());
852 #if defined(ENABLE_BROWSER_CDMS)
853 AddFilter(new BrowserCdmManager(GetID(), NULL
));
856 WebSocketDispatcherHost::GetRequestContextCallback
857 websocket_request_context_callback(
858 base::Bind(&GetRequestContext
, request_context
,
859 media_request_context
, RESOURCE_TYPE_SUB_RESOURCE
));
862 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback
));
864 message_port_message_filter_
= new MessagePortMessageFilter(
865 base::Bind(&RenderWidgetHelper::GetNextRoutingID
,
866 base::Unretained(widget_helper_
.get())));
867 AddFilter(message_port_message_filter_
.get());
869 scoped_refptr
<CacheStorageDispatcherHost
> cache_storage_filter
=
870 new CacheStorageDispatcherHost();
871 cache_storage_filter
->Init(storage_partition_impl_
->GetCacheStorageContext());
872 AddFilter(cache_storage_filter
.get());
874 scoped_refptr
<ServiceWorkerDispatcherHost
> service_worker_filter
=
875 new ServiceWorkerDispatcherHost(
876 GetID(), message_port_message_filter_
.get(), resource_context
);
877 service_worker_filter
->Init(
878 storage_partition_impl_
->GetServiceWorkerContext());
879 AddFilter(service_worker_filter
.get());
881 AddFilter(new SharedWorkerMessageFilter(
884 WorkerStoragePartition(
885 storage_partition_impl_
->GetURLRequestContext(),
886 storage_partition_impl_
->GetMediaURLRequestContext(),
887 storage_partition_impl_
->GetAppCacheService(),
888 storage_partition_impl_
->GetQuotaManager(),
889 storage_partition_impl_
->GetFileSystemContext(),
890 storage_partition_impl_
->GetDatabaseTracker(),
891 storage_partition_impl_
->GetIndexedDBContext(),
892 storage_partition_impl_
->GetServiceWorkerContext()),
893 message_port_message_filter_
.get()));
895 #if defined(ENABLE_WEBRTC)
896 p2p_socket_dispatcher_host_
= new P2PSocketDispatcherHost(
898 browser_context
->GetRequestContextForRenderProcess(GetID()));
899 AddFilter(p2p_socket_dispatcher_host_
.get());
902 AddFilter(new TraceMessageFilter(GetID()));
903 AddFilter(new ResolveProxyMsgHelper(
904 browser_context
->GetRequestContextForRenderProcess(GetID())));
905 AddFilter(new QuotaDispatcherHost(
907 storage_partition_impl_
->GetQuotaManager(),
908 GetContentClient()->browser()->CreateQuotaPermissionContext()));
910 notification_message_filter_
= new NotificationMessageFilter(
912 storage_partition_impl_
->GetPlatformNotificationContext(),
915 AddFilter(notification_message_filter_
.get());
917 AddFilter(new GamepadBrowserMessageFilter());
918 AddFilter(new DeviceLightMessageFilter());
919 AddFilter(new DeviceMotionMessageFilter());
920 AddFilter(new DeviceOrientationMessageFilter());
921 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER
));
922 AddFilter(new HistogramMessageFilter());
923 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
924 if (browser_command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
925 AddFilter(new MemoryBenchmarkMessageFilter());
927 AddFilter(new PushMessagingMessageFilter(
928 GetID(), storage_partition_impl_
->GetServiceWorkerContext()));
929 #if defined(OS_ANDROID)
930 AddFilter(new ScreenOrientationMessageFilterAndroid());
932 AddFilter(new GeofencingDispatcherHost(
933 storage_partition_impl_
->GetGeofencingManager()));
934 if (browser_command_line
.HasSwitch(switches::kEnableWebBluetooth
)) {
935 bluetooth_dispatcher_host_
= new BluetoothDispatcherHost(GetID());
936 AddFilter(bluetooth_dispatcher_host_
.get());
940 void RenderProcessHostImpl::RegisterMojoServices() {
941 mojo_application_host_
->service_registry()->AddService(
942 base::Bind(&device::BatteryMonitorImpl::Create
));
944 mojo_application_host_
->service_registry()->AddService(
945 base::Bind(&device::VibrationManagerImpl::Create
));
947 mojo_application_host_
->service_registry()->AddService(
948 base::Bind(&PermissionServiceContext::CreateService
,
949 base::Unretained(permission_service_context_
.get())));
951 mojo_application_host_
->service_registry()->AddService(base::Bind(
952 &content::BackgroundSyncServiceImpl::Create
,
953 base::Unretained(storage_partition_impl_
->GetBackgroundSyncContext())));
955 mojo_application_host_
->service_registry()->AddService(base::Bind(
956 &content::ServicePortServiceImpl::Create
,
957 make_scoped_refptr(storage_partition_impl_
->GetNavigatorConnectContext()),
958 message_port_message_filter_
));
960 #if defined(OS_ANDROID)
961 ServiceRegistrarAndroid::RegisterProcessHostServices(
962 mojo_application_host_
->service_registry_android());
965 GetContentClient()->browser()->RegisterRenderProcessMojoServices(
966 mojo_application_host_
->service_registry());
969 int RenderProcessHostImpl::GetNextRoutingID() {
970 return widget_helper_
->GetNextRoutingID();
973 void RenderProcessHostImpl::ResumeDeferredNavigation(
974 const GlobalRequestID
& request_id
) {
975 widget_helper_
->ResumeDeferredNavigation(request_id
);
978 void RenderProcessHostImpl::NotifyTimezoneChange(const std::string
& zone_id
) {
979 Send(new ViewMsg_TimezoneChange(zone_id
));
982 ServiceRegistry
* RenderProcessHostImpl::GetServiceRegistry() {
983 DCHECK(mojo_application_host_
);
984 return mojo_application_host_
->service_registry();
987 const base::TimeTicks
& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
992 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
993 return subscribe_uniform_enabled_
;
996 void RenderProcessHostImpl::OnAddSubscription(unsigned int target
) {
997 DCHECK(subscribe_uniform_enabled_
);
998 subscription_set_
.insert(target
);
999 const gpu::ValueState
* state
= pending_valuebuffer_state_
->GetState(target
);
1001 SendUpdateValueState(target
, *state
);
1005 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target
) {
1006 DCHECK(subscribe_uniform_enabled_
);
1007 subscription_set_
.erase(target
);
1010 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target
,
1011 const gpu::ValueState
& state
) {
1012 DCHECK(subscribe_uniform_enabled_
);
1013 if (subscription_set_
.find(target
) != subscription_set_
.end()) {
1014 GpuProcessHost::SendOnIO(
1015 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
1016 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
,
1017 new GpuMsg_UpdateValueState(id_
, target
, state
));
1019 // Store the ValueState locally in case a Valuebuffer subscribes to it later
1020 pending_valuebuffer_state_
->UpdateState(target
, state
);
1024 #if defined(ENABLE_BROWSER_CDMS)
1025 media::BrowserCdm
* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id
,
1027 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1028 BrowserCdmManager
* manager
= BrowserCdmManager::FromProcess(GetID());
1031 return manager
->GetCdm(render_frame_id
, cdm_id
);
1035 void RenderProcessHostImpl::AddRoute(
1037 IPC::Listener
* listener
) {
1038 CHECK(!listeners_
.Lookup(routing_id
))
1039 << "Found Routing ID Conflict: " << routing_id
;
1040 listeners_
.AddWithID(listener
, routing_id
);
1043 void RenderProcessHostImpl::RemoveRoute(int32 routing_id
) {
1044 DCHECK(listeners_
.Lookup(routing_id
) != NULL
);
1045 listeners_
.Remove(routing_id
);
1047 // Keep the one renderer thread around forever in single process mode.
1048 if (!run_renderer_in_process())
1052 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver
* observer
) {
1053 observers_
.AddObserver(observer
);
1056 void RenderProcessHostImpl::RemoveObserver(
1057 RenderProcessHostObserver
* observer
) {
1058 observers_
.RemoveObserver(observer
);
1061 void RenderProcessHostImpl::ShutdownForBadMessage() {
1062 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
1063 if (command_line
->HasSwitch(switches::kDisableKillAfterBadIPC
))
1066 if (run_renderer_in_process()) {
1067 // In single process mode it is better if we don't suicide but just
1071 // We kill the renderer but don't include a NOTREACHED, because we want the
1072 // browser to try to survive when it gets illegal messages from the renderer.
1073 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE
, false);
1076 void RenderProcessHostImpl::WidgetRestored() {
1077 // Verify we were properly backgrounded.
1078 DCHECK_EQ(backgrounded_
, (visible_widgets_
== 0));
1080 SetBackgrounded(false);
1083 void RenderProcessHostImpl::WidgetHidden() {
1084 // On startup, the browser will call Hide
1088 DCHECK_EQ(backgrounded_
, (visible_widgets_
== 0));
1090 DCHECK_GE(visible_widgets_
, 0);
1091 if (visible_widgets_
== 0) {
1092 DCHECK(!backgrounded_
);
1093 SetBackgrounded(true);
1097 int RenderProcessHostImpl::VisibleWidgetCount() const {
1098 return visible_widgets_
;
1101 bool RenderProcessHostImpl::IsForGuestsOnly() const {
1102 return is_for_guests_only_
;
1105 StoragePartition
* RenderProcessHostImpl::GetStoragePartition() const {
1106 return storage_partition_impl_
;
1109 static void AppendCompositorCommandLineFlags(base::CommandLine
* command_line
) {
1110 if (IsPropertyTreeVerificationEnabled())
1111 command_line
->AppendSwitch(cc::switches::kEnablePropertyTreeVerification
);
1113 if (IsDelegatedRendererEnabled())
1114 command_line
->AppendSwitch(switches::kEnableDelegatedRenderer
);
1116 command_line
->AppendSwitchASCII(
1117 switches::kNumRasterThreads
,
1118 base::IntToString(NumberOfRendererRasterThreads()));
1120 if (IsGpuRasterizationEnabled())
1121 command_line
->AppendSwitch(switches::kEnableGpuRasterization
);
1123 int msaa_sample_count
= GpuRasterizationMSAASampleCount();
1124 if (msaa_sample_count
> 0) {
1125 command_line
->AppendSwitchASCII(
1126 switches::kGpuRasterizationMSAASampleCount
,
1127 base::IntToString(msaa_sample_count
));
1130 DCHECK_IMPLIES(IsZeroCopyUploadEnabled(), !IsOneCopyUploadEnabled());
1131 DCHECK_IMPLIES(IsOneCopyUploadEnabled(), !IsZeroCopyUploadEnabled());
1132 if (IsZeroCopyUploadEnabled())
1133 command_line
->AppendSwitch(switches::kEnableZeroCopy
);
1134 if (!IsOneCopyUploadEnabled())
1135 command_line
->AppendSwitch(switches::kDisableOneCopy
);
1137 if (IsForceGpuRasterizationEnabled())
1138 command_line
->AppendSwitch(switches::kForceGpuRasterization
);
1140 command_line
->AppendSwitchASCII(
1141 switches::kContentImageTextureTarget
,
1143 // TODO(reveman): We currently assume that the compositor will use
1144 // BGRA_8888 if it's able to, and RGBA_8888 otherwise. Since we don't
1145 // know what it will use we hardcode BGRA_8888 here for now. We should
1146 // instead move decisions about GpuMemoryBuffer format to the browser
1147 // embedder so we know it here, and pass that decision to the
1148 // compositor for each usage.
1150 BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1151 gfx::GpuMemoryBuffer::BGRA_8888
,
1152 // TODO(danakj): When one-copy supports partial update, change
1153 // this usage to PERSISTENT_MAP for one-copy.
1154 gfx::GpuMemoryBuffer::MAP
)));
1156 command_line
->AppendSwitchASCII(
1157 switches::kVideoImageTextureTarget
,
1158 base::UintToString(BrowserGpuMemoryBufferManager::GetImageTextureTarget(
1159 gfx::GpuMemoryBuffer::R_8
, gfx::GpuMemoryBuffer::MAP
)));
1161 // Appending disable-gpu-feature switches due to software rendering list.
1162 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
1163 DCHECK(gpu_data_manager
);
1164 gpu_data_manager
->AppendRendererCommandLine(command_line
);
1167 void RenderProcessHostImpl::AppendRendererCommandLine(
1168 base::CommandLine
* command_line
) const {
1169 // Pass the process type first, so it shows first in process listings.
1170 command_line
->AppendSwitchASCII(switches::kProcessType
,
1171 switches::kRendererProcess
);
1173 // Now send any options from our own command line we want to propagate.
1174 const base::CommandLine
& browser_command_line
=
1175 *base::CommandLine::ForCurrentProcess();
1176 PropagateBrowserCommandLineToRenderer(browser_command_line
, command_line
);
1178 // Pass on the browser locale.
1179 const std::string locale
=
1180 GetContentClient()->browser()->GetApplicationLocale();
1181 command_line
->AppendSwitchASCII(switches::kLang
, locale
);
1183 // If we run base::FieldTrials, we want to pass to their state to the
1184 // renderer so that it can act in accordance with each state, or record
1185 // histograms relating to the base::FieldTrial states.
1186 std::string field_trial_states
;
1187 base::FieldTrialList::AllStatesToString(&field_trial_states
);
1188 if (!field_trial_states
.empty()) {
1189 command_line
->AppendSwitchASCII(switches::kForceFieldTrials
,
1190 field_trial_states
);
1193 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1194 command_line
, GetID());
1196 if (IsPinchToZoomEnabled())
1197 command_line
->AppendSwitch(switches::kEnablePinch
);
1200 command_line
->AppendSwitchASCII(switches::kDeviceScaleFactor
,
1201 base::DoubleToString(gfx::GetDPIScale()));
1204 AppendCompositorCommandLineFlags(command_line
);
1207 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1208 const base::CommandLine
& browser_cmd
,
1209 base::CommandLine
* renderer_cmd
) const {
1210 // Propagate the following switches to the renderer command line (along
1211 // with any associated values) if present in the browser command line.
1212 static const char* const kSwitchNames
[] = {
1213 switches::kAllowLoopbackInPeerConnection
,
1214 switches::kAudioBufferSize
,
1215 switches::kBlinkPlatformLogChannels
,
1216 switches::kBlinkSettings
,
1217 switches::kDefaultTileWidth
,
1218 switches::kDefaultTileHeight
,
1219 switches::kDisable3DAPIs
,
1220 switches::kDisableAcceleratedJpegDecoding
,
1221 switches::kDisableAcceleratedVideoDecode
,
1222 switches::kDisableBlinkFeatures
,
1223 switches::kDisableBreakpad
,
1224 switches::kDisablePreferCompositingToLCDText
,
1225 switches::kDisableDatabases
,
1226 switches::kDisableDelayAgnosticAec
,
1227 switches::kDisableDirectNPAPIRequests
,
1228 switches::kDisableDisplayList2dCanvas
,
1229 switches::kDisableDistanceFieldText
,
1230 switches::kDisableEncryptedMedia
,
1231 switches::kDisableFileSystem
,
1232 switches::kDisableGpuCompositing
,
1233 switches::kDisableGpuVsync
,
1234 switches::kDisableLowResTiling
,
1235 switches::kDisableHistogramCustomizer
,
1236 switches::kDisableIconNtp
,
1237 switches::kDisableLCDText
,
1238 switches::kDisableLocalStorage
,
1239 switches::kDisableLogging
,
1240 switches::kDisableMediaSource
,
1241 switches::kDisableMojoChannel
,
1242 switches::kDisableNewVideoRenderer
,
1243 switches::kDisableNotifications
,
1244 switches::kDisableOverlayScrollbar
,
1245 switches::kDisablePermissionsAPI
,
1246 switches::kDisablePinch
,
1247 switches::kDisablePrefixedEncryptedMedia
,
1248 switches::kDisableSeccompFilterSandbox
,
1249 switches::kDisableSharedWorkers
,
1250 switches::kDisableSlimmingPaint
,
1251 switches::kDisableSpeechAPI
,
1252 switches::kDisableSVG1DOM
,
1253 switches::kDisableThreadedCompositing
,
1254 switches::kDisableThreadedScrolling
,
1255 switches::kDisableTouchAdjustment
,
1256 switches::kDisableTouchDragDrop
,
1257 switches::kDisableTouchEditing
,
1258 switches::kDisableV8IdleTasks
,
1259 switches::kDomAutomationController
,
1260 switches::kEnableBleedingEdgeRenderingFastPaths
,
1261 switches::kEnableBlinkFeatures
,
1262 switches::kEnableBrowserSideNavigation
,
1263 switches::kEnableCompositorAnimationTimelines
,
1264 switches::kEnableCredentialManagerAPI
,
1265 switches::kEnableDelayAgnosticAec
,
1266 switches::kEnableDisplayList2dCanvas
,
1267 switches::kEnableDistanceFieldText
,
1268 switches::kEnableExperimentalCanvasFeatures
,
1269 switches::kEnableExperimentalWebPlatformFeatures
,
1270 switches::kEnableGPUClientLogging
,
1271 switches::kEnableGpuClientTracing
,
1272 switches::kEnableGPUServiceLogging
,
1273 switches::kEnableIconNtp
,
1274 switches::kEnableLinkDisambiguationPopup
,
1275 switches::kEnableLowResTiling
,
1276 switches::kEnableInbandTextTracks
,
1277 switches::kEnableLCDText
,
1278 switches::kEnableLogging
,
1279 switches::kEnableMemoryBenchmarking
,
1280 switches::kEnableNetworkInformation
,
1281 switches::kEnableOverlayFullscreenVideo
,
1282 switches::kEnableOverlayScrollbar
,
1283 switches::kEnablePinch
,
1284 switches::kEnablePluginPlaceholderTesting
,
1285 switches::kEnablePreciseMemoryInfo
,
1286 switches::kEnablePreferCompositingToLCDText
,
1287 switches::kEnablePushMessagePayload
,
1288 switches::kEnableRendererMojoChannel
,
1289 switches::kEnableSeccompFilterSandbox
,
1290 switches::kEnableSkiaBenchmarking
,
1291 switches::kEnableSlimmingPaint
,
1292 switches::kEnableSmoothScrolling
,
1293 switches::kEnableStaleWhileRevalidate
,
1294 switches::kEnableStatsTable
,
1295 switches::kEnableThreadedCompositing
,
1296 switches::kEnableTouchDragDrop
,
1297 switches::kEnableTouchEditing
,
1298 switches::kEnableUnsafeES3APIs
,
1299 switches::kEnableViewport
,
1300 switches::kEnableViewportMeta
,
1301 switches::kInvertViewportScrollOrder
,
1302 switches::kEnableVtune
,
1303 switches::kEnableWebBluetooth
,
1304 switches::kEnableWebGLDraftExtensions
,
1305 switches::kEnableWebGLImageChromium
,
1306 switches::kEnableWebVR
,
1307 switches::kExplicitlyAllowedPorts
,
1308 switches::kForceDeviceScaleFactor
,
1309 switches::kForceDisplayList2dCanvas
,
1310 switches::kFullMemoryCrashReport
,
1311 switches::kIPCConnectionTimeout
,
1312 switches::kJavaScriptFlags
,
1313 switches::kLoggingLevel
,
1314 switches::kMainFrameResizesAreOrientationChanges
,
1315 switches::kMaxUntiledLayerWidth
,
1316 switches::kMaxUntiledLayerHeight
,
1317 switches::kMemoryMetrics
,
1318 switches::kNoReferrers
,
1319 switches::kNoSandbox
,
1320 switches::kOverridePluginPowerSaverForTesting
,
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::kTouchTextSelectionStrategy
,
1334 switches::kTraceToConsole
,
1335 // This flag needs to be propagated to the renderer process for
1336 // --in-process-webgl.
1338 switches::kUseMobileUserAgent
,
1339 switches::kUseNormalPriorityForTileTaskWorkerThreads
,
1341 switches::kVideoThreads
,
1342 switches::kVideoUnderflowThresholdMs
,
1344 // Please keep these in alphabetical order. Compositor switches here should
1345 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1346 cc::switches::kCompositeToMailbox
,
1347 cc::switches::kDisableCompositedAntialiasing
,
1348 cc::switches::kDisableMainFrameBeforeActivation
,
1349 cc::switches::kDisableThreadedAnimation
,
1350 cc::switches::kEnableBeginFrameScheduling
,
1351 cc::switches::kEnableGpuBenchmarking
,
1352 cc::switches::kEnableMainFrameBeforeActivation
,
1353 cc::switches::kMaxUnusedResourceMemoryUsagePercentage
,
1354 cc::switches::kShowCompositedLayerBorders
,
1355 cc::switches::kShowFPSCounter
,
1356 cc::switches::kShowLayerAnimationBounds
,
1357 cc::switches::kShowPropertyChangedRects
,
1358 cc::switches::kShowReplicaScreenSpaceRects
,
1359 cc::switches::kShowScreenSpaceRects
,
1360 cc::switches::kShowSurfaceDamageRects
,
1361 cc::switches::kSlowDownRasterScaleFactor
,
1362 cc::switches::kStrictLayerPropertyChangeChecking
,
1363 cc::switches::kTopControlsHideThreshold
,
1364 cc::switches::kTopControlsShowThreshold
,
1366 scheduler::switches::kDisableBlinkScheduler
,
1368 #if defined(ENABLE_PLUGINS)
1369 switches::kEnablePepperTesting
,
1371 #if defined(ENABLE_WEBRTC)
1372 switches::kDisableWebRtcHWDecoding
,
1373 switches::kDisableWebRtcHWEncoding
,
1374 switches::kEnableWebRtcDtls12
,
1375 switches::kEnableWebRtcHWH264Encoding
,
1376 switches::kEnableWebRtcStunOrigin
,
1377 switches::kWebRtcMaxCaptureFramerate
,
1379 switches::kEnableLowEndDeviceMode
,
1380 switches::kDisableLowEndDeviceMode
,
1381 #if defined(OS_ANDROID)
1382 switches::kDisableGestureRequirementForMediaPlayback
,
1383 switches::kDisableWebRTC
,
1384 switches::kDisableWebAudio
,
1385 switches::kRendererWaitForJavaDebugger
,
1387 #if defined(OS_MACOSX)
1388 // Allow this to be set when invoking the browser and relayed along.
1389 switches::kEnableSandboxLogging
,
1392 switches::kDisableDirectWrite
,
1393 switches::kDisableWin32kRendererLockDown
,
1394 switches::kTraceExportEventsToETW
,
1396 #if defined(OS_CHROMEOS)
1397 switches::kDisableVaapiAcceleratedVideoEncode
,
1400 renderer_cmd
->CopySwitchesFrom(browser_cmd
, kSwitchNames
,
1401 arraysize(kSwitchNames
));
1403 if (browser_cmd
.HasSwitch(switches::kTraceStartup
) &&
1404 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1405 // Pass kTraceStartup switch to renderer only if startup tracing has not
1407 renderer_cmd
->AppendSwitchASCII(
1408 switches::kTraceStartup
,
1409 browser_cmd
.GetSwitchValueASCII(switches::kTraceStartup
));
1412 #if defined(ENABLE_WEBRTC)
1413 // Only run the Stun trials in the first renderer.
1414 if (!has_done_stun_trials
&&
1415 browser_cmd
.HasSwitch(switches::kWebRtcStunProbeTrialParameter
)) {
1416 has_done_stun_trials
= true;
1417 renderer_cmd
->AppendSwitchASCII(
1418 switches::kWebRtcStunProbeTrialParameter
,
1419 browser_cmd
.GetSwitchValueASCII(
1420 switches::kWebRtcStunProbeTrialParameter
));
1424 // Disable databases in incognito mode.
1425 if (GetBrowserContext()->IsOffTheRecord() &&
1426 !browser_cmd
.HasSwitch(switches::kDisableDatabases
)) {
1427 renderer_cmd
->AppendSwitch(switches::kDisableDatabases
);
1430 // Add kWaitForDebugger to let renderer process wait for a debugger.
1431 if (browser_cmd
.HasSwitch(switches::kWaitForDebuggerChildren
)) {
1432 // Look to pass-on the kWaitForDebugger flag.
1434 browser_cmd
.GetSwitchValueASCII(switches::kWaitForDebuggerChildren
);
1435 if (value
.empty() || value
== switches::kRendererProcess
) {
1436 renderer_cmd
->AppendSwitch(switches::kWaitForDebugger
);
1441 base::ProcessHandle
RenderProcessHostImpl::GetHandle() const {
1442 if (run_renderer_in_process())
1443 return base::GetCurrentProcessHandle();
1445 if (!child_process_launcher_
.get() || child_process_launcher_
->IsStarting())
1446 return base::kNullProcessHandle
;
1448 return child_process_launcher_
->GetProcess().Handle();
1451 bool RenderProcessHostImpl::Shutdown(int exit_code
, bool wait
) {
1452 if (run_renderer_in_process())
1453 return false; // Single process mode never shuts down the renderer.
1455 #if defined(OS_ANDROID)
1456 // Android requires a different approach for killing.
1457 StopChildProcess(GetHandle());
1460 if (!child_process_launcher_
.get() || child_process_launcher_
->IsStarting())
1463 return child_process_launcher_
->GetProcess().Terminate(exit_code
, wait
);
1467 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1468 if (run_renderer_in_process())
1469 return false; // Single process mode never shuts down the renderer.
1471 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1474 if (!child_process_launcher_
.get() ||
1475 child_process_launcher_
->IsStarting() ||
1477 return false; // Render process hasn't started or is probably crashed.
1479 // Test if there's an unload listener.
1480 // NOTE: It's possible that an onunload listener may be installed
1481 // while we're shutting down, so there's a small race here. Given that
1482 // the window is small, it's unlikely that the web page has much
1483 // state that will be lost by not calling its unload handlers properly.
1484 if (!SuddenTerminationAllowed())
1487 if (worker_ref_count_
!= 0) {
1488 if (survive_for_worker_start_time_
.is_null())
1489 survive_for_worker_start_time_
= base::TimeTicks::Now();
1493 // Set this before ProcessDied() so observers can tell if the render process
1494 // died due to fast shutdown versus another cause.
1495 fast_shutdown_started_
= true;
1497 ProcessDied(false /* already_dead */, nullptr);
1501 bool RenderProcessHostImpl::Send(IPC::Message
* msg
) {
1502 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1504 if (!is_initialized_
) {
1505 queued_messages_
.push(msg
);
1513 if (child_process_launcher_
.get() && child_process_launcher_
->IsStarting()) {
1514 queued_messages_
.push(msg
);
1518 return channel_
->Send(msg
);
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(ViewHostMsg_SuddenTerminationChanged
,
1535 SuddenTerminationChanged
)
1536 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction
,
1537 OnUserMetricsRecordAction
)
1538 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML
, OnSavedPageAsMHTML
)
1539 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK
, OnCloseACK
)
1540 #if defined(ENABLE_WEBRTC)
1541 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer
,
1542 OnRegisterAecDumpConsumer
)
1543 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer
,
1544 OnUnregisterAecDumpConsumer
)
1546 // Adding single handlers for your service here is fine, but once your
1547 // service needs more than one handler, please extract them into a new
1548 // message filter and add that filter to CreateMessageFilters().
1549 IPC_END_MESSAGE_MAP()
1554 // Dispatch incoming messages to the appropriate IPC::Listener.
1555 IPC::Listener
* listener
= listeners_
.Lookup(msg
.routing_id());
1557 if (msg
.is_sync()) {
1558 // The listener has gone away, so we must respond or else the caller will
1559 // hang waiting for a reply.
1560 IPC::Message
* reply
= IPC::SyncMessage::GenerateReply(&msg
);
1561 reply
->set_reply_error();
1566 return listener
->OnMessageReceived(msg
);
1569 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid
) {
1570 #if defined(IPC_MESSAGE_LOG_ENABLED)
1571 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1572 IPC::Logging::GetInstance()->Enabled()));
1575 tracked_objects::ThreadData::Status status
=
1576 tracked_objects::ThreadData::status();
1577 Send(new ChildProcessMsg_SetProfilerStatus(status
));
1579 #if defined(OS_MACOSX) && !defined(OS_IOS)
1580 io_surface_manager_token_
=
1581 BrowserIOSurfaceManager::GetInstance()->GenerateChildProcessToken(
1583 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_
));
1587 void RenderProcessHostImpl::OnChannelError() {
1588 ProcessDied(true /* already_dead */, nullptr);
1591 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message
& message
) {
1592 // Message de-serialization failed. We consider this a capital crime. Kill the
1593 // renderer if we have one.
1594 LOG(ERROR
) << "bad message " << message
.type() << " terminating renderer.";
1595 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1596 PROCESS_TYPE_RENDERER
);
1598 // Create a memory dump. This will contain enough stack frames to work out
1599 // what the bad message was.
1600 base::debug::DumpWithoutCrashing();
1602 bad_message::ReceivedBadMessage(this,
1603 bad_message::RPH_DESERIALIZATION_FAILED
);
1606 BrowserContext
* RenderProcessHostImpl::GetBrowserContext() const {
1607 return browser_context_
;
1610 bool RenderProcessHostImpl::InSameStoragePartition(
1611 StoragePartition
* partition
) const {
1612 return storage_partition_impl_
== partition
;
1615 int RenderProcessHostImpl::GetID() const {
1619 bool RenderProcessHostImpl::HasConnection() const {
1620 return channel_
.get() != NULL
;
1623 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events
) {
1624 ignore_input_events_
= ignore_input_events
;
1627 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1628 return ignore_input_events_
;
1631 void RenderProcessHostImpl::Cleanup() {
1632 // If within_process_died_observer_ is true, one of our observers performed an
1633 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1634 // delay the destruction until all of the observer callbacks have been made,
1635 // and guarantee that the RenderProcessHostDestroyed observer callback is
1636 // always the last callback fired.
1637 if (within_process_died_observer_
) {
1638 delayed_cleanup_needed_
= true;
1641 delayed_cleanup_needed_
= false;
1643 // Records the time when the process starts surviving for workers for UMA.
1644 if (listeners_
.IsEmpty() && worker_ref_count_
> 0 &&
1645 survive_for_worker_start_time_
.is_null()) {
1646 survive_for_worker_start_time_
= base::TimeTicks::Now();
1649 // When there are no other owners of this object, we can delete ourselves.
1650 if (listeners_
.IsEmpty() && worker_ref_count_
== 0) {
1651 if (!survive_for_worker_start_time_
.is_null()) {
1652 UMA_HISTOGRAM_LONG_TIMES(
1653 "SharedWorker.RendererSurviveForWorkerTime",
1654 base::TimeTicks::Now() - survive_for_worker_start_time_
);
1657 if (max_worker_count_
> 0) {
1658 // Record the max number of workers (SharedWorker or ServiceWorker)
1659 // that are simultaneously hosted in this renderer process.
1660 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1664 // We cannot clean up twice; if this fails, there is an issue with our
1666 DCHECK(!deleting_soon_
);
1668 DCHECK_EQ(0, pending_views_
);
1669 FOR_EACH_OBSERVER(RenderProcessHostObserver
,
1671 RenderProcessHostDestroyed(this));
1672 NotificationService::current()->Notify(
1673 NOTIFICATION_RENDERER_PROCESS_TERMINATED
,
1674 Source
<RenderProcessHost
>(this),
1675 NotificationService::NoDetails());
1678 is_self_deleted_
= true;
1680 base::MessageLoop::current()->DeleteSoon(FROM_HERE
, this);
1681 deleting_soon_
= true;
1682 // It's important not to wait for the DeleteTask to delete the channel
1683 // proxy. Kill it off now. That way, in case the profile is going away, the
1684 // rest of the objects attached to this RenderProcessHost start going
1685 // away first, since deleting the channel proxy will post a
1686 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1689 // The following members should be cleared in ProcessDied() as well!
1690 gpu_message_filter_
= NULL
;
1691 message_port_message_filter_
= NULL
;
1693 RemoveUserData(kSessionStorageHolderKey
);
1695 // Remove ourself from the list of renderer processes so that we can't be
1696 // reused in between now and when the Delete task runs.
1697 UnregisterHost(GetID());
1699 #if defined(OS_MACOSX) && !defined(OS_IOS)
1700 if (!io_surface_manager_token_
.IsZero()) {
1701 BrowserIOSurfaceManager::GetInstance()->InvalidateChildProcessToken(
1702 io_surface_manager_token_
);
1703 io_surface_manager_token_
.SetZero();
1710 void RenderProcessHostImpl::AddPendingView() {
1714 void RenderProcessHostImpl::RemovePendingView() {
1715 DCHECK(pending_views_
);
1719 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled
) {
1720 sudden_termination_allowed_
= enabled
;
1723 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1724 return sudden_termination_allowed_
;
1727 base::TimeDelta
RenderProcessHostImpl::GetChildProcessIdleTime() const {
1728 return base::TimeTicks::Now() - child_process_activity_time_
;
1731 void RenderProcessHostImpl::ResumeRequestsForView(int route_id
) {
1732 widget_helper_
->ResumeRequestsForView(route_id
);
1735 void RenderProcessHostImpl::FilterURL(bool empty_allowed
, GURL
* url
) {
1736 FilterURL(this, empty_allowed
, url
);
1739 #if defined(ENABLE_WEBRTC)
1740 void RenderProcessHostImpl::EnableAecDump(const base::FilePath
& file
) {
1741 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1742 // Enable AEC dump for each registered consumer.
1743 for (std::vector
<int>::iterator it
= aec_dump_consumers_
.begin();
1744 it
!= aec_dump_consumers_
.end(); ++it
) {
1745 EnableAecDumpForId(file
, *it
);
1749 void RenderProcessHostImpl::DisableAecDump() {
1750 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1751 // Posting on the FILE thread and then replying back on the UI thread is only
1752 // for avoiding races between enable and disable. Nothing is done on the FILE
1754 BrowserThread::PostTaskAndReply(
1755 BrowserThread::FILE, FROM_HERE
,
1756 base::Bind(&DisableAecDumpOnFileThread
),
1757 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer
,
1758 weak_factory_
.GetWeakPtr()));
1761 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1762 base::Callback
<void(const std::string
&)> callback
) {
1763 webrtc_log_message_callback_
= callback
;
1766 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1767 RenderProcessHostImpl::StartRtpDump(
1770 const WebRtcRtpPacketCallback
& packet_callback
) {
1771 if (!p2p_socket_dispatcher_host_
.get())
1772 return WebRtcStopRtpDumpCallback();
1774 BrowserThread::PostTask(BrowserThread::IO
,
1776 base::Bind(&P2PSocketDispatcherHost::StartRtpDump
,
1777 p2p_socket_dispatcher_host_
,
1782 if (stop_rtp_dump_callback_
.is_null()) {
1783 stop_rtp_dump_callback_
=
1784 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread
,
1785 p2p_socket_dispatcher_host_
);
1787 return stop_rtp_dump_callback_
;
1791 IPC::ChannelProxy
* RenderProcessHostImpl::GetChannel() {
1792 return channel_
.get();
1795 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter
* filter
) {
1796 channel_
->AddFilter(filter
->GetFilter());
1799 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count
) {
1800 if (static_cast<size_t>(GetActiveViewCount()) == count
)
1801 return FastShutdownIfPossible();
1805 bool RenderProcessHostImpl::FastShutdownStarted() const {
1806 return fast_shutdown_started_
;
1810 void RenderProcessHostImpl::RegisterHost(int host_id
, RenderProcessHost
* host
) {
1811 g_all_hosts
.Get().AddWithID(host
, host_id
);
1815 void RenderProcessHostImpl::UnregisterHost(int host_id
) {
1816 RenderProcessHost
* host
= g_all_hosts
.Get().Lookup(host_id
);
1820 g_all_hosts
.Get().Remove(host_id
);
1822 // Look up the map of site to process for the given browser_context,
1823 // in case we need to remove this process from it. It will be registered
1824 // under any sites it rendered that use process-per-site mode.
1825 SiteProcessMap
* map
=
1826 GetSiteProcessMapForBrowserContext(host
->GetBrowserContext());
1827 map
->RemoveProcess(host
);
1831 void RenderProcessHostImpl::FilterURL(RenderProcessHost
* rph
,
1834 ChildProcessSecurityPolicyImpl
* policy
=
1835 ChildProcessSecurityPolicyImpl::GetInstance();
1837 if (empty_allowed
&& url
->is_empty())
1840 // The browser process should never hear the swappedout:// URL from any
1841 // of the renderer's messages. Check for this in debug builds, but don't
1842 // let it crash a release browser.
1843 DCHECK(GURL(kSwappedOutURL
) != *url
);
1845 if (!url
->is_valid()) {
1846 // Have to use about:blank for the denied case, instead of an empty GURL.
1847 // This is because the browser treats navigation to an empty GURL as a
1848 // navigation to the home page. This is often a privileged page
1849 // (chrome://newtab/) which is exactly what we don't want.
1850 *url
= GURL(url::kAboutBlankURL
);
1854 if (url
->SchemeIs(url::kAboutScheme
)) {
1855 // The renderer treats all URLs in the about: scheme as being about:blank.
1856 // Canonicalize about: URLs to about:blank.
1857 *url
= GURL(url::kAboutBlankURL
);
1860 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1861 // cannot swap processes or grant bindings.
1862 bool non_web_url_in_guest
= rph
->IsForGuestsOnly() &&
1863 !(url
->is_valid() && policy
->IsWebSafeScheme(url
->scheme()));
1865 if (non_web_url_in_guest
|| !policy
->CanRequestURL(rph
->GetID(), *url
)) {
1866 // If this renderer is not permitted to request this URL, we invalidate the
1867 // URL. This prevents us from storing the blocked URL and becoming confused
1869 VLOG(1) << "Blocked URL " << url
->spec();
1870 *url
= GURL(url::kAboutBlankURL
);
1875 bool RenderProcessHostImpl::IsSuitableHost(
1876 RenderProcessHost
* host
,
1877 BrowserContext
* browser_context
,
1878 const GURL
& site_url
) {
1879 if (run_renderer_in_process())
1882 if (host
->GetBrowserContext() != browser_context
)
1885 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1886 // and non-guest storage gets mixed. In the future, we might consider enabling
1887 // the sharing of guests, in this case this check should be removed and
1888 // InSameStoragePartition should handle the possible sharing.
1889 if (host
->IsForGuestsOnly())
1892 // Check whether the given host and the intended site_url will be using the
1893 // same StoragePartition, since a RenderProcessHost can only support a single
1894 // StoragePartition. This is relevant for packaged apps and isolated sites.
1895 StoragePartition
* dest_partition
=
1896 BrowserContext::GetStoragePartitionForSite(browser_context
, site_url
);
1897 if (!host
->InSameStoragePartition(dest_partition
))
1900 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1902 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1903 browser_context
, site_url
)) {
1907 return GetContentClient()->browser()->IsSuitableHost(host
, site_url
);
1911 bool RenderProcessHost::run_renderer_in_process() {
1912 return g_run_renderer_in_process_
;
1916 void RenderProcessHost::SetRunRendererInProcess(bool value
) {
1917 g_run_renderer_in_process_
= value
;
1919 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
1921 if (!command_line
->HasSwitch(switches::kLang
)) {
1922 // Modify the current process' command line to include the browser locale,
1923 // as the renderer expects this flag to be set.
1924 const std::string locale
=
1925 GetContentClient()->browser()->GetApplicationLocale();
1926 command_line
->AppendSwitchASCII(switches::kLang
, locale
);
1928 // TODO(piman): we should really send configuration through bools rather
1929 // than by parsing strings, i.e. sending an IPC rather than command line
1930 // args. crbug.com/314909
1931 AppendCompositorCommandLineFlags(command_line
);
1936 RenderProcessHost::iterator
RenderProcessHost::AllHostsIterator() {
1937 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1938 return iterator(g_all_hosts
.Pointer());
1942 RenderProcessHost
* RenderProcessHost::FromID(int render_process_id
) {
1943 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
1944 return g_all_hosts
.Get().Lookup(render_process_id
);
1948 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1949 BrowserContext
* browser_context
, const GURL
& url
) {
1950 // If --site-per-process is enabled, do not try to reuse renderer processes
1951 // when over the limit. (We could allow pages from the same site to share, if
1952 // we knew what the given process was dedicated to. Allowing no sharing is
1953 // simpler for now.) This may cause resource exhaustion issues if too many
1954 // sites are open at once.
1955 const base::CommandLine
& command_line
=
1956 *base::CommandLine::ForCurrentProcess();
1957 if (command_line
.HasSwitch(switches::kSitePerProcess
))
1960 if (run_renderer_in_process())
1963 // NOTE: Sometimes it's necessary to create more render processes than
1964 // GetMaxRendererProcessCount(), for instance when we want to create
1965 // a renderer process for a browser context that has no existing
1966 // renderers. This is OK in moderation, since the
1967 // GetMaxRendererProcessCount() is conservative.
1968 if (g_all_hosts
.Get().size() >= GetMaxRendererProcessCount())
1971 return GetContentClient()->browser()->
1972 ShouldTryToUseExistingProcessHost(browser_context
, url
);
1976 RenderProcessHost
* RenderProcessHost::GetExistingProcessHost(
1977 BrowserContext
* browser_context
,
1978 const GURL
& site_url
) {
1979 // First figure out which existing renderers we can use.
1980 std::vector
<RenderProcessHost
*> suitable_renderers
;
1981 suitable_renderers
.reserve(g_all_hosts
.Get().size());
1983 iterator
iter(AllHostsIterator());
1984 while (!iter
.IsAtEnd()) {
1985 if (GetContentClient()->browser()->MayReuseHost(iter
.GetCurrentValue()) &&
1986 RenderProcessHostImpl::IsSuitableHost(
1987 iter
.GetCurrentValue(),
1988 browser_context
, site_url
)) {
1989 suitable_renderers
.push_back(iter
.GetCurrentValue());
1994 // Now pick a random suitable renderer, if we have any.
1995 if (!suitable_renderers
.empty()) {
1996 int suitable_count
= static_cast<int>(suitable_renderers
.size());
1997 int random_index
= base::RandInt(0, suitable_count
- 1);
1998 return suitable_renderers
[random_index
];
2005 bool RenderProcessHost::ShouldUseProcessPerSite(
2006 BrowserContext
* browser_context
,
2008 // Returns true if we should use the process-per-site model. This will be
2009 // the case if the --process-per-site switch is specified, or in
2010 // process-per-site-instance for particular sites (e.g., WebUI).
2011 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
2012 const base::CommandLine
& command_line
=
2013 *base::CommandLine::ForCurrentProcess();
2014 if (command_line
.HasSwitch(switches::kProcessPerSite
))
2017 // We want to consolidate particular sites like WebUI even when we are using
2018 // the process-per-tab or process-per-site-instance models.
2019 // Note: DevTools pages have WebUI type but should not reuse the same host.
2020 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
2021 browser_context
, url
) &&
2022 !url
.SchemeIs(kChromeDevToolsScheme
)) {
2026 // Otherwise let the content client decide, defaulting to false.
2027 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context
,
2032 RenderProcessHost
* RenderProcessHostImpl::GetProcessHostForSite(
2033 BrowserContext
* browser_context
,
2035 // Look up the map of site to process for the given browser_context.
2036 SiteProcessMap
* map
=
2037 GetSiteProcessMapForBrowserContext(browser_context
);
2039 // See if we have an existing process with appropriate bindings for this site.
2040 // If not, the caller should create a new process and register it.
2041 std::string site
= SiteInstance::GetSiteForURL(browser_context
, url
)
2042 .possibly_invalid_spec();
2043 RenderProcessHost
* host
= map
->FindProcess(site
);
2044 if (host
&& (!GetContentClient()->browser()->MayReuseHost(host
) ||
2045 !IsSuitableHost(host
, browser_context
, url
))) {
2046 // The registered process does not have an appropriate set of bindings for
2047 // the url. Remove it from the map so we can register a better one.
2049 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2050 map
->RemoveProcess(host
);
2057 void RenderProcessHostImpl::RegisterProcessHostForSite(
2058 BrowserContext
* browser_context
,
2059 RenderProcessHost
* process
,
2061 // Look up the map of site to process for the given browser_context.
2062 SiteProcessMap
* map
=
2063 GetSiteProcessMapForBrowserContext(browser_context
);
2065 // Only register valid, non-empty sites. Empty or invalid sites will not
2066 // use process-per-site mode. We cannot check whether the process has
2067 // appropriate bindings here, because the bindings have not yet been granted.
2068 std::string site
= SiteInstance::GetSiteForURL(browser_context
, url
)
2069 .possibly_invalid_spec();
2071 map
->RegisterProcess(site
, process
);
2074 void RenderProcessHostImpl::ProcessDied(bool already_dead
,
2075 RendererClosedDetails
* known_details
) {
2076 // Our child process has died. If we didn't expect it, it's a crash.
2077 // In any case, we need to let everyone know it's gone.
2078 // The OnChannelError notification can fire multiple times due to nested sync
2079 // calls to a renderer. If we don't have a valid channel here it means we
2080 // already handled the error.
2082 // It should not be possible for us to be called re-entrantly.
2083 DCHECK(!within_process_died_observer_
);
2085 // It should not be possible for a process death notification to come in while
2087 DCHECK(!deleting_soon_
);
2089 // child_process_launcher_ can be NULL in single process mode or if fast
2090 // termination happened.
2091 base::TerminationStatus status
= base::TERMINATION_STATUS_NORMAL_TERMINATION
;
2093 if (known_details
) {
2094 status
= known_details
->status
;
2095 exit_code
= known_details
->exit_code
;
2096 } else if (child_process_launcher_
.get()) {
2097 status
= child_process_launcher_
->GetChildTerminationStatus(already_dead
,
2099 if (already_dead
&& status
== base::TERMINATION_STATUS_STILL_RUNNING
) {
2100 // May be in case of IPC error, if it takes long time for renderer
2101 // to exit. Child process will be killed in any case during
2102 // child_process_launcher_.reset(). Make sure we will not broadcast
2103 // FrameHostMsg_RenderProcessGone with status
2104 // TERMINATION_STATUS_STILL_RUNNING, since this will break WebContentsImpl
2106 status
= base::TERMINATION_STATUS_PROCESS_CRASHED
;
2110 RendererClosedDetails
details(status
, exit_code
);
2111 mojo_application_host_
->WillDestroySoon();
2113 child_process_launcher_
.reset();
2115 while (!queued_messages_
.empty()) {
2116 delete queued_messages_
.front();
2117 queued_messages_
.pop();
2120 within_process_died_observer_
= true;
2121 NotificationService::current()->Notify(
2122 NOTIFICATION_RENDERER_PROCESS_CLOSED
,
2123 Source
<RenderProcessHost
>(this),
2124 Details
<RendererClosedDetails
>(&details
));
2125 FOR_EACH_OBSERVER(RenderProcessHostObserver
,
2127 RenderProcessExited(this, status
, exit_code
));
2128 within_process_died_observer_
= false;
2130 gpu_message_filter_
= NULL
;
2131 message_port_message_filter_
= NULL
;
2132 RemoveUserData(kSessionStorageHolderKey
);
2134 IDMap
<IPC::Listener
>::iterator
iter(&listeners_
);
2135 while (!iter
.IsAtEnd()) {
2136 iter
.GetCurrentValue()->OnMessageReceived(
2137 FrameHostMsg_RenderProcessGone(iter
.GetCurrentKey(),
2138 static_cast<int>(status
),
2143 mojo_application_host_
.reset(new MojoApplicationHost
);
2145 // It's possible that one of the calls out to the observers might have caused
2146 // this object to be no longer needed.
2147 if (delayed_cleanup_needed_
)
2150 // This object is not deleted at this point and might be reused later.
2151 // TODO(darin): clean this up
2154 int RenderProcessHost::GetActiveViewCount() {
2155 int num_active_views
= 0;
2156 scoped_ptr
<RenderWidgetHostIterator
> widgets(
2157 RenderWidgetHost::GetRenderWidgetHosts());
2158 while (RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
2159 // Count only RenderWidgetHosts in this process.
2160 if (widget
->GetProcess()->GetID() == GetID())
2163 return num_active_views
;
2166 // Frame subscription API for this class is for accelerated composited path
2167 // only. These calls are redirected to GpuMessageFilter.
2168 void RenderProcessHostImpl::BeginFrameSubscription(
2170 scoped_ptr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
2171 if (!gpu_message_filter_
)
2173 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
, base::Bind(
2174 &GpuMessageFilter::BeginFrameSubscription
,
2175 gpu_message_filter_
,
2176 route_id
, base::Passed(&subscriber
)));
2179 void RenderProcessHostImpl::EndFrameSubscription(int route_id
) {
2180 if (!gpu_message_filter_
)
2182 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
, base::Bind(
2183 &GpuMessageFilter::EndFrameSubscription
,
2184 gpu_message_filter_
,
2188 #if defined(ENABLE_WEBRTC)
2189 void RenderProcessHostImpl::WebRtcLogMessage(const std::string
& message
) {
2190 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2191 if (!webrtc_log_message_callback_
.is_null())
2192 webrtc_log_message_callback_
.Run(message
);
2196 void RenderProcessHostImpl::ReleaseOnCloseACK(
2197 RenderProcessHost
* host
,
2198 const SessionStorageNamespaceMap
& sessions
,
2199 int view_route_id
) {
2201 if (sessions
.empty())
2203 SessionStorageHolder
* holder
= static_cast<SessionStorageHolder
*>
2204 (host
->GetUserData(kSessionStorageHolderKey
));
2206 holder
= new SessionStorageHolder();
2208 kSessionStorageHolderKey
,
2211 holder
->Hold(sessions
, view_route_id
);
2214 void RenderProcessHostImpl::OnShutdownRequest() {
2215 // Don't shut down if there are active RenderViews, or if there are pending
2216 // RenderViews being swapped back in.
2217 // In single process mode, we never shutdown the renderer.
2218 int num_active_views
= GetActiveViewCount();
2219 if (pending_views_
|| num_active_views
> 0 || run_renderer_in_process())
2222 // Notify any contents that might have swapped out renderers from this
2223 // process. They should not attempt to swap them back in.
2224 FOR_EACH_OBSERVER(RenderProcessHostObserver
, observers_
,
2225 RenderProcessWillExit(this));
2227 mojo_application_host_
->WillDestroySoon();
2229 Send(new ChildProcessMsg_Shutdown());
2232 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled
) {
2233 SetSuddenTerminationAllowed(enabled
);
2236 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded
) {
2237 TRACE_EVENT1("renderer_host", "RenderProcessHostImpl::SetBackgrounded",
2238 "backgrounded", backgrounded
);
2239 // Note: we always set the backgrounded_ value. If the process is NULL
2240 // (and hence hasn't been created yet), we will set the process priority
2241 // later when we create the process.
2242 backgrounded_
= backgrounded
;
2243 if (!child_process_launcher_
.get() || child_process_launcher_
->IsStarting())
2246 // Don't background processes which have active audio streams.
2247 if (backgrounded_
&& audio_renderer_host_
->HasActiveAudio())
2250 const base::CommandLine
* command_line
=
2251 base::CommandLine::ForCurrentProcess();
2252 if (command_line
->HasSwitch(switches::kDisableRendererBackgrounding
))
2256 // The cbstext.dll loads as a global GetMessage hook in the browser process
2257 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2258 // background thread. If the UI thread invokes this API just when it is
2259 // intercepted the stack is messed up on return from the interceptor
2260 // which causes random crashes in the browser process. Our hack for now
2261 // is to not invoke the SetPriorityClass API if the dll is loaded.
2262 if (GetModuleHandle(L
"cbstext.dll"))
2266 #if defined(OS_WIN) || defined(OS_MACOSX)
2267 // Same as below, but bound to an experiment (http://crbug.com/458594 on
2268 // Windows, http://crbug.com/398103 on the Mac). Enabled by default in the
2269 // absence of field trials to get coverage on the perf waterfall.
2270 base::FieldTrial
* trial
=
2271 base::FieldTrialList::Find("BackgroundRendererProcesses");
2272 if (!trial
|| !base::StartsWith(trial
->group_name(), "Disallow",
2273 base::CompareCase::SENSITIVE
)) {
2274 child_process_launcher_
->SetProcessBackgrounded(backgrounded
);
2277 // Control the background state from the browser process, otherwise the task
2278 // telling the renderer to "unbackground" itself may be preempted by other
2279 // tasks executing at lowered priority ahead of it or simply by not being
2280 // swiftly scheduled by the OS per the low process priority
2281 // (http://crbug.com/398103).
2282 child_process_launcher_
->SetProcessBackgrounded(backgrounded
);
2285 // Notify the child process of background state.
2286 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded
));
2289 void RenderProcessHostImpl::OnProcessLaunched() {
2290 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2292 tracked_objects::ScopedTracker
tracking_profile1(
2293 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2294 "465841 RenderProcessHostImpl::OnProcessLaunched::Start"));
2295 // No point doing anything, since this object will be destructed soon. We
2296 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2297 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2298 // properly cleanup.
2302 if (child_process_launcher_
) {
2303 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2305 tracked_objects::ScopedTracker
tracking_profile2(
2306 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2307 "465841 RenderProcessHostImpl::OnProcessLaunched::Backgrounded"));
2308 DCHECK(child_process_launcher_
->GetProcess().IsValid());
2309 SetBackgrounded(backgrounded_
);
2312 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2314 tracked_objects::ScopedTracker
tracking_profile3(
2315 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2316 "465841 RenderProcessHostImpl::OnProcessLaunched::Notify"));
2317 // NOTE: This needs to be before sending queued messages because
2318 // ExtensionService uses this notification to initialize the renderer process
2319 // with state that must be there before any JavaScript executes.
2321 // The queued messages contain such things as "navigate". If this notification
2322 // was after, we can end up executing JavaScript before the initialization
2324 NotificationService::current()->Notify(
2325 NOTIFICATION_RENDERER_PROCESS_CREATED
,
2326 Source
<RenderProcessHost
>(this),
2327 NotificationService::NoDetails());
2329 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2331 tracked_objects::ScopedTracker
tracking_profile4(
2332 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2333 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoActivate"));
2334 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2335 // This way, Mojo can be safely used from the renderer in response to any
2336 // Chrome IPC message.
2337 mojo_application_host_
->Activate(this, GetHandle());
2339 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2341 tracked_objects::ScopedTracker
tracking_profile5(
2342 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2343 "465841 RenderProcessHostImpl::OnProcessLaunched::MojoClientLaunch"));
2345 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2347 tracked_objects::ScopedTracker
tracking_profile6(
2348 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2350 "RenderProcessHostImpl::OnProcessLaunched::SendQueuedMessages"));
2351 while (!queued_messages_
.empty()) {
2352 Send(queued_messages_
.front());
2353 queued_messages_
.pop();
2356 #if defined(ENABLE_WEBRTC)
2357 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/465841
2359 tracked_objects::ScopedTracker
tracking_profile7(
2360 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2361 "465841 RenderProcessHostImpl::OnProcessLaunched::EnableAec"));
2362 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2363 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2367 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2368 // If this object will be destructed soon, then observers have already been
2369 // sent a RenderProcessHostDestroyed notification, and we must observe our
2370 // contract that says that will be the last call.
2374 RendererClosedDetails details
{ base::TERMINATION_STATUS_PROCESS_WAS_KILLED
,
2376 ProcessDied(true, &details
);
2379 scoped_refptr
<AudioRendererHost
>
2380 RenderProcessHostImpl::audio_renderer_host() const {
2381 return audio_renderer_host_
;
2384 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2385 const std::string
& action
) {
2386 RecordComputedAction(action
);
2389 void RenderProcessHostImpl::OnCloseACK(int old_route_id
) {
2390 SessionStorageHolder
* holder
= static_cast<SessionStorageHolder
*>
2391 (GetUserData(kSessionStorageHolderKey
));
2394 holder
->Release(old_route_id
);
2397 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id
, int64 data_size
) {
2398 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id
, data_size
);
2401 void RenderProcessHostImpl::OnGpuSwitched() {
2402 // We are updating all widgets including swapped out ones.
2403 scoped_ptr
<RenderWidgetHostIterator
> widgets(
2404 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2405 while (RenderWidgetHost
* widget
= widgets
->GetNextHost()) {
2406 if (!widget
->IsRenderView())
2409 // Skip widgets in other processes.
2410 if (widget
->GetProcess()->GetID() != GetID())
2413 RenderViewHost
* rvh
= RenderViewHost::From(widget
);
2414 rvh
->OnWebkitPreferencesChanged();
2418 #if defined(ENABLE_WEBRTC)
2419 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id
) {
2420 BrowserThread::PostTask(
2424 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread
,
2425 weak_factory_
.GetWeakPtr(),
2429 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id
) {
2430 BrowserThread::PostTask(
2434 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread
,
2435 weak_factory_
.GetWeakPtr(),
2439 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id
) {
2440 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2441 aec_dump_consumers_
.push_back(id
);
2442 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2443 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2448 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id
) {
2449 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2450 for (std::vector
<int>::iterator it
= aec_dump_consumers_
.begin();
2451 it
!= aec_dump_consumers_
.end(); ++it
) {
2453 aec_dump_consumers_
.erase(it
);
2460 #define IntToStringType base::IntToString16
2462 #define IntToStringType base::IntToString
2465 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath
& file
,
2467 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2468 base::FilePath unique_file
=
2469 file
.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2470 .AddExtension(IntToStringType(id
));
2471 BrowserThread::PostTaskAndReplyWithResult(
2472 BrowserThread::FILE, FROM_HERE
,
2473 base::Bind(&CreateAecDumpFileForProcess
, unique_file
, GetHandle()),
2474 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer
,
2475 weak_factory_
.GetWeakPtr(),
2479 #undef IntToStringType
2481 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2483 IPC::PlatformFileForTransit file_for_transit
) {
2484 if (file_for_transit
== IPC::InvalidPlatformFileForTransit())
2486 Send(new AecDumpMsg_EnableAecDump(id
, file_for_transit
));
2489 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2490 Send(new AecDumpMsg_DisableAecDump());
2494 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2495 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2496 ++worker_ref_count_
;
2497 if (worker_ref_count_
> max_worker_count_
)
2498 max_worker_count_
= worker_ref_count_
;
2501 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2502 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2503 DCHECK_GT(worker_ref_count_
, 0);
2504 --worker_ref_count_
;
2505 if (worker_ref_count_
== 0)
2509 void RenderProcessHostImpl::GetAudioOutputControllers(
2510 const GetAudioOutputControllersCallback
& callback
) const {
2511 audio_renderer_host()->GetOutputControllers(callback
);
2514 BluetoothDispatcherHost
* RenderProcessHostImpl::GetBluetoothDispatcherHost() {
2515 return bluetooth_dispatcher_host_
.get();
2518 } // namespace content