Always create top controls manager.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobb1eae97ef079c75e35ef28ae8cf786ae341899a5
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Represents the browser side of the browser <--> renderer communication
6 // channel. There will be one RenderProcessHost per renderer process.
8 #include "content/browser/renderer_host/render_process_host_impl.h"
10 #include <algorithm>
11 #include <limits>
12 #include <vector>
14 #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/rand_util.h"
26 #include "base/stl_util.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_util.h"
29 #include "base/supports_user_data.h"
30 #include "base/sys_info.h"
31 #include "base/threading/thread.h"
32 #include "base/threading/thread_restrictions.h"
33 #include "base/trace_event/trace_event.h"
34 #include "base/tracked_objects.h"
35 #include "cc/base/switches.h"
36 #include "content/browser/appcache/appcache_dispatcher_host.h"
37 #include "content/browser/appcache/chrome_appcache_service.h"
38 #include "content/browser/bluetooth/bluetooth_dispatcher_host.h"
39 #include "content/browser/browser_child_process_host_impl.h"
40 #include "content/browser/browser_main.h"
41 #include "content/browser/browser_main_loop.h"
42 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
43 #include "content/browser/child_process_security_policy_impl.h"
44 #include "content/browser/device_sensors/device_light_message_filter.h"
45 #include "content/browser/device_sensors/device_motion_message_filter.h"
46 #include "content/browser/device_sensors/device_orientation_message_filter.h"
47 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
48 #include "content/browser/dom_storage/dom_storage_message_filter.h"
49 #include "content/browser/download/mhtml_generation_manager.h"
50 #include "content/browser/fileapi/chrome_blob_storage_context.h"
51 #include "content/browser/fileapi/fileapi_message_filter.h"
52 #include "content/browser/frame_host/render_frame_message_filter.h"
53 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
54 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
55 #include "content/browser/gpu/compositor_util.h"
56 #include "content/browser/gpu/gpu_data_manager_impl.h"
57 #include "content/browser/gpu/gpu_process_host.h"
58 #include "content/browser/gpu/shader_disk_cache.h"
59 #include "content/browser/histogram_message_filter.h"
60 #include "content/browser/indexed_db/indexed_db_context_impl.h"
61 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
62 #include "content/browser/loader/resource_message_filter.h"
63 #include "content/browser/loader/resource_scheduler_filter.h"
64 #include "content/browser/media/capture/audio_mirroring_manager.h"
65 #include "content/browser/media/media_internals.h"
66 #include "content/browser/media/midi_host.h"
67 #include "content/browser/message_port_message_filter.h"
68 #include "content/browser/mime_registry_message_filter.h"
69 #include "content/browser/mojo/mojo_application_host.h"
70 #include "content/browser/navigator_connect/navigator_connect_dispatcher_host.h"
71 #include "content/browser/notifications/notification_message_filter.h"
72 #include "content/browser/permissions/permission_service_context.h"
73 #include "content/browser/permissions/permission_service_impl.h"
74 #include "content/browser/profiler_message_filter.h"
75 #include "content/browser/push_messaging/push_messaging_message_filter.h"
76 #include "content/browser/quota_dispatcher_host.h"
77 #include "content/browser/renderer_host/clipboard_message_filter.h"
78 #include "content/browser/renderer_host/database_message_filter.h"
79 #include "content/browser/renderer_host/file_utilities_message_filter.h"
80 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
81 #include "content/browser/renderer_host/gpu_message_filter.h"
82 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
83 #include "content/browser/renderer_host/media/audio_renderer_host.h"
84 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
85 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
86 #include "content/browser/renderer_host/media/video_capture_host.h"
87 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
88 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
89 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
90 #include "content/browser/renderer_host/render_message_filter.h"
91 #include "content/browser/renderer_host/render_view_host_delegate.h"
92 #include "content/browser/renderer_host/render_view_host_impl.h"
93 #include "content/browser/renderer_host/render_widget_helper.h"
94 #include "content/browser/renderer_host/render_widget_host_impl.h"
95 #include "content/browser/renderer_host/text_input_client_message_filter.h"
96 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
97 #include "content/browser/resolve_proxy_msg_helper.h"
98 #include "content/browser/service_worker/service_worker_context_wrapper.h"
99 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
100 #include "content/browser/shared_worker/shared_worker_message_filter.h"
101 #include "content/browser/shared_worker/worker_storage_partition.h"
102 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
103 #include "content/browser/storage_partition_impl.h"
104 #include "content/browser/streams/stream_context.h"
105 #include "content/browser/tracing/trace_message_filter.h"
106 #include "content/browser/webui/web_ui_controller_factory_registry.h"
107 #include "content/common/child_process_host_impl.h"
108 #include "content/common/child_process_messages.h"
109 #include "content/common/content_switches_internal.h"
110 #include "content/common/frame_messages.h"
111 #include "content/common/gpu/gpu_memory_buffer_factory.h"
112 #include "content/common/gpu/gpu_messages.h"
113 #include "content/common/mojo/channel_init.h"
114 #include "content/common/mojo/mojo_messages.h"
115 #include "content/common/resource_messages.h"
116 #include "content/common/view_messages.h"
117 #include "content/public/browser/browser_context.h"
118 #include "content/public/browser/content_browser_client.h"
119 #include "content/public/browser/navigator_connect_context.h"
120 #include "content/public/browser/notification_service.h"
121 #include "content/public/browser/notification_types.h"
122 #include "content/public/browser/render_process_host_factory.h"
123 #include "content/public/browser/render_process_host_observer.h"
124 #include "content/public/browser/render_widget_host.h"
125 #include "content/public/browser/render_widget_host_iterator.h"
126 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
127 #include "content/public/browser/resource_context.h"
128 #include "content/public/browser/user_metrics.h"
129 #include "content/public/browser/worker_service.h"
130 #include "content/public/common/content_constants.h"
131 #include "content/public/common/content_switches.h"
132 #include "content/public/common/mojo_channel_switches.h"
133 #include "content/public/common/process_type.h"
134 #include "content/public/common/resource_type.h"
135 #include "content/public/common/result_codes.h"
136 #include "content/public/common/sandboxed_process_launcher_delegate.h"
137 #include "content/public/common/url_constants.h"
138 #include "device/battery/battery_monitor_impl.h"
139 #include "device/vibration/vibration_manager_impl.h"
140 #include "gpu/GLES2/gl2extchromium.h"
141 #include "gpu/command_buffer/client/gpu_switches.h"
142 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
143 #include "gpu/command_buffer/service/gpu_switches.h"
144 #include "ipc/ipc_channel.h"
145 #include "ipc/ipc_logging.h"
146 #include "ipc/ipc_switches.h"
147 #include "ipc/mojo/ipc_channel_mojo.h"
148 #include "ipc/mojo/ipc_channel_mojo_host.h"
149 #include "media/base/media_switches.h"
150 #include "net/url_request/url_request_context_getter.h"
151 #include "ppapi/shared_impl/ppapi_switches.h"
152 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
153 #include "third_party/skia/include/core/SkBitmap.h"
154 #include "ui/base/ui_base_switches.h"
155 #include "ui/events/event_switches.h"
156 #include "ui/gfx/switches.h"
157 #include "ui/gl/gl_switches.h"
158 #include "ui/gl/gpu_switching_manager.h"
159 #include "ui/native_theme/native_theme_switches.h"
161 #if defined(OS_ANDROID)
162 #include "content/browser/android/child_process_launcher_android.h"
163 #include "content/browser/media/android/browser_demuxer_android.h"
164 #include "content/browser/mojo/service_registrar_android.h"
165 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
166 #endif
168 #if defined(OS_WIN)
169 #include "base/win/scoped_com_initializer.h"
170 #include "base/win/windows_version.h"
171 #include "content/common/font_cache_dispatcher_win.h"
172 #include "content/common/sandbox_win.h"
173 #include "sandbox/win/src/sandbox_policy.h"
174 #include "ui/gfx/win/dpi.h"
175 #endif
177 #if defined(ENABLE_BROWSER_CDMS)
178 #include "content/browser/media/cdm/browser_cdm_manager.h"
179 #endif
181 #if defined(ENABLE_PLUGINS)
182 #include "content/browser/plugin_service_impl.h"
183 #endif
185 #if defined(ENABLE_WEBRTC)
186 #include "content/browser/media/webrtc_internals.h"
187 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
188 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
189 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
190 #include "content/common/media/aec_dump_messages.h"
191 #include "content/common/media/media_stream_messages.h"
192 #endif
194 extern bool g_exited_main_message_loop;
196 namespace content {
197 namespace {
199 const char kSiteProcessMapKeyName[] = "content_site_process_map";
201 void CacheShaderInfo(int32 id, base::FilePath path) {
202 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
205 void RemoveShaderInfo(int32 id) {
206 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
209 net::URLRequestContext* GetRequestContext(
210 scoped_refptr<net::URLRequestContextGetter> request_context,
211 scoped_refptr<net::URLRequestContextGetter> media_request_context,
212 ResourceType resource_type) {
213 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
214 // context specific to media for handling it because these resources have
215 // specific needs for caching.
216 if (resource_type == RESOURCE_TYPE_MEDIA)
217 return media_request_context->GetURLRequestContext();
218 return request_context->GetURLRequestContext();
221 void GetContexts(
222 ResourceContext* resource_context,
223 scoped_refptr<net::URLRequestContextGetter> request_context,
224 scoped_refptr<net::URLRequestContextGetter> media_request_context,
225 const ResourceHostMsg_Request& request,
226 ResourceContext** resource_context_out,
227 net::URLRequestContext** request_context_out) {
228 *resource_context_out = resource_context;
229 *request_context_out =
230 GetRequestContext(request_context, media_request_context,
231 request.resource_type);
234 #if defined(ENABLE_WEBRTC)
235 // Creates a file used for diagnostic echo canceller recordings for handing
236 // over to the renderer.
237 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
238 base::FilePath file_path,
239 base::ProcessHandle process) {
240 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
241 base::File dump_file(file_path,
242 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
243 if (!dump_file.IsValid()) {
244 VLOG(1) << "Could not open AEC dump file, error=" <<
245 dump_file.error_details();
246 return IPC::InvalidPlatformFileForTransit();
248 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
251 // Does nothing. Just to avoid races between enable and disable.
252 void DisableAecDumpOnFileThread() {
253 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
255 #endif
257 // the global list of all renderer processes
258 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
259 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
261 // Map of site to process, to ensure we only have one RenderProcessHost per
262 // site in process-per-site mode. Each map is specific to a BrowserContext.
263 class SiteProcessMap : public base::SupportsUserData::Data {
264 public:
265 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
266 SiteProcessMap() {}
268 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
269 map_[site] = process;
272 RenderProcessHost* FindProcess(const std::string& site) {
273 SiteToProcessMap::iterator i = map_.find(site);
274 if (i != map_.end())
275 return i->second;
276 return NULL;
279 void RemoveProcess(RenderProcessHost* host) {
280 // Find all instances of this process in the map, then separately remove
281 // them.
282 std::set<std::string> sites;
283 for (SiteToProcessMap::const_iterator i = map_.begin();
284 i != map_.end();
285 i++) {
286 if (i->second == host)
287 sites.insert(i->first);
289 for (std::set<std::string>::iterator i = sites.begin();
290 i != sites.end();
291 i++) {
292 SiteToProcessMap::iterator iter = map_.find(*i);
293 if (iter != map_.end()) {
294 DCHECK_EQ(iter->second, host);
295 map_.erase(iter);
300 private:
301 SiteToProcessMap map_;
304 // Find the SiteProcessMap specific to the given context.
305 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
306 DCHECK(context);
307 SiteProcessMap* map = static_cast<SiteProcessMap*>(
308 context->GetUserData(kSiteProcessMapKeyName));
309 if (!map) {
310 map = new SiteProcessMap();
311 context->SetUserData(kSiteProcessMapKeyName, map);
313 return map;
316 // NOTE: changes to this class need to be reviewed by the security team.
317 class RendererSandboxedProcessLauncherDelegate
318 : public SandboxedProcessLauncherDelegate {
319 public:
320 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
321 #if defined(OS_POSIX)
322 : ipc_fd_(channel->TakeClientFileDescriptor())
323 #endif // OS_POSIX
326 ~RendererSandboxedProcessLauncherDelegate() override {}
328 #if defined(OS_WIN)
329 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
330 bool* success) {
331 AddBaseHandleClosePolicy(policy);
333 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
334 // TODO(shrikant): Check if these constants should be different across
335 // various versions of Chromium code base or could be same.
336 // If there should be different SID per channel then move this code
337 // in chrome rather than content and assign SID based on
338 // VersionInfo::GetChannel().
339 const wchar_t kAppContainerSid[] =
340 L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
341 L"924012148-129201922";
343 policy->SetLowBox(kAppContainerSid);
346 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
349 #elif defined(OS_POSIX)
350 bool ShouldUseZygote() override {
351 const base::CommandLine& browser_command_line =
352 *base::CommandLine::ForCurrentProcess();
353 base::CommandLine::StringType renderer_prefix =
354 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
355 return renderer_prefix.empty();
357 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
358 #endif // OS_WIN
360 private:
361 #if defined(OS_POSIX)
362 base::ScopedFD ipc_fd_;
363 #endif // OS_POSIX
366 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
368 class SessionStorageHolder : public base::SupportsUserData::Data {
369 public:
370 SessionStorageHolder() {}
371 ~SessionStorageHolder() override {}
373 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
374 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
377 void Release(int old_route_id) {
378 session_storage_namespaces_awaiting_close_.erase(old_route_id);
381 private:
382 std::map<int, SessionStorageNamespaceMap >
383 session_storage_namespaces_awaiting_close_;
384 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
387 } // namespace
389 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
391 base::MessageLoop* g_in_process_thread;
393 base::MessageLoop*
394 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
395 return g_in_process_thread;
398 // Stores the maximum number of renderer processes the content module can
399 // create.
400 static size_t g_max_renderer_count_override = 0;
402 // static
403 size_t RenderProcessHost::GetMaxRendererProcessCount() {
404 if (g_max_renderer_count_override)
405 return g_max_renderer_count_override;
407 #if defined(OS_ANDROID)
408 // On Android we don't maintain a limit of renderer process hosts - we are
409 // happy with keeping a lot of these, as long as the number of live renderer
410 // processes remains reasonable, and on Android the OS takes care of that.
411 return std::numeric_limits<size_t>::max();
412 #endif
414 // On other platforms, we calculate the maximum number of renderer process
415 // hosts according to the amount of installed memory as reported by the OS.
416 // The calculation assumes that you want the renderers to use half of the
417 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
418 // this assumption, you need to adjust the ThirtyFourTabs test to match the
419 // expected number of processes.
421 // With the given amounts of installed memory below on a 32-bit CPU, the
422 // maximum renderer count will roughly be as follows:
424 // 128 MB -> 3
425 // 512 MB -> 6
426 // 1024 MB -> 12
427 // 4096 MB -> 51
428 // 16384 MB -> 82 (kMaxRendererProcessCount)
430 static size_t max_count = 0;
431 if (!max_count) {
432 const size_t kEstimatedWebContentsMemoryUsage =
433 #if defined(ARCH_CPU_64_BITS)
434 60; // In MB
435 #else
436 40; // In MB
437 #endif
438 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
439 max_count /= kEstimatedWebContentsMemoryUsage;
441 const size_t kMinRendererProcessCount = 3;
442 max_count = std::max(max_count, kMinRendererProcessCount);
443 max_count = std::min(max_count, kMaxRendererProcessCount);
445 return max_count;
448 // static
449 bool g_run_renderer_in_process_ = false;
451 // static
452 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
453 g_max_renderer_count_override = count;
456 RenderProcessHostImpl::RenderProcessHostImpl(
457 BrowserContext* browser_context,
458 StoragePartitionImpl* storage_partition_impl,
459 bool is_isolated_guest)
460 : fast_shutdown_started_(false),
461 deleting_soon_(false),
462 #ifndef NDEBUG
463 is_self_deleted_(false),
464 #endif
465 pending_views_(0),
466 mojo_application_host_(new MojoApplicationHost),
467 visible_widgets_(0),
468 backgrounded_(true),
469 is_initialized_(false),
470 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
471 browser_context_(browser_context),
472 storage_partition_impl_(storage_partition_impl),
473 sudden_termination_allowed_(true),
474 ignore_input_events_(false),
475 is_isolated_guest_(is_isolated_guest),
476 gpu_observer_registered_(false),
477 delayed_cleanup_needed_(false),
478 within_process_died_observer_(false),
479 power_monitor_broadcaster_(this),
480 worker_ref_count_(0),
481 max_worker_count_(0),
482 permission_service_context_(new PermissionServiceContext(this)),
483 pending_valuebuffer_state_(new gpu::ValueStateMap()),
484 subscribe_uniform_enabled_(false),
485 weak_factory_(this) {
486 widget_helper_ = new RenderWidgetHelper();
488 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
490 CHECK(!g_exited_main_message_loop);
491 RegisterHost(GetID(), this);
492 g_all_hosts.Get().set_check_on_null_data(true);
493 // Initialize |child_process_activity_time_| to a reasonable value.
494 mark_child_process_activity_time();
496 if (!GetBrowserContext()->IsOffTheRecord() &&
497 !base::CommandLine::ForCurrentProcess()->HasSwitch(
498 switches::kDisableGpuShaderDiskCache)) {
499 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
500 base::Bind(&CacheShaderInfo, GetID(),
501 storage_partition_impl_->GetPath()));
503 subscribe_uniform_enabled_ =
504 base::CommandLine::ForCurrentProcess()->HasSwitch(
505 switches::kEnableSubscribeUniformExtension);
507 // Note: When we create the RenderProcessHostImpl, it's technically
508 // backgrounded, because it has no visible listeners. But the process
509 // doesn't actually exist yet, so we'll Background it later, after
510 // creation.
513 // static
514 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
515 DCHECK(g_run_renderer_in_process_);
517 switch (g_all_hosts.Pointer()->size()) {
518 case 0:
519 return;
520 case 1: {
521 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
522 AllHostsIterator().GetCurrentValue());
523 FOR_EACH_OBSERVER(RenderProcessHostObserver,
524 host->observers_,
525 RenderProcessHostDestroyed(host));
526 #ifndef NDEBUG
527 host->is_self_deleted_ = true;
528 #endif
529 delete host;
530 return;
532 default:
533 NOTREACHED() << "There should be only one RenderProcessHost when running "
534 << "in-process.";
538 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
539 RendererMainThreadFactoryFunction create) {
540 g_renderer_main_thread_factory = create;
543 RenderProcessHostImpl::~RenderProcessHostImpl() {
544 #ifndef NDEBUG
545 DCHECK(is_self_deleted_)
546 << "RenderProcessHostImpl is destroyed by something other than itself";
547 #endif
549 // Make sure to clean up the in-process renderer before the channel, otherwise
550 // it may still run and have its IPCs fail, causing asserts.
551 in_process_renderer_.reset();
553 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
555 if (gpu_observer_registered_) {
556 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
557 gpu_observer_registered_ = false;
560 // We may have some unsent messages at this point, but that's OK.
561 channel_.reset();
562 while (!queued_messages_.empty()) {
563 delete queued_messages_.front();
564 queued_messages_.pop();
567 UnregisterHost(GetID());
569 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
570 switches::kDisableGpuShaderDiskCache)) {
571 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
572 base::Bind(&RemoveShaderInfo, GetID()));
576 void RenderProcessHostImpl::EnableSendQueue() {
577 is_initialized_ = false;
580 bool RenderProcessHostImpl::Init() {
581 // calling Init() more than once does nothing, this makes it more convenient
582 // for the view host which may not be sure in some cases
583 if (channel_)
584 return true;
586 base::CommandLine::StringType renderer_prefix;
587 // A command prefix is something prepended to the command line of the spawned
588 // process.
589 const base::CommandLine& browser_command_line =
590 *base::CommandLine::ForCurrentProcess();
591 renderer_prefix =
592 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
594 #if defined(OS_LINUX)
595 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
596 ChildProcessHost::CHILD_NORMAL;
597 #else
598 int flags = ChildProcessHost::CHILD_NORMAL;
599 #endif
601 // Find the renderer before creating the channel so if this fails early we
602 // return without creating the channel.
603 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
604 if (renderer_path.empty())
605 return false;
607 // Setup the IPC channel.
608 const std::string channel_id =
609 IPC::Channel::GenerateVerifiedChannelID(std::string());
610 channel_ = CreateChannelProxy(channel_id);
612 // Setup the Mojo channel.
613 mojo_application_host_->Init();
615 // Call the embedder first so that their IPC filters have priority.
616 GetContentClient()->browser()->RenderProcessWillLaunch(this);
618 CreateMessageFilters();
619 RegisterMojoServices();
621 if (run_renderer_in_process()) {
622 DCHECK(g_renderer_main_thread_factory);
623 // Crank up a thread and run the initialization there. With the way that
624 // messages flow between the browser and renderer, this thread is required
625 // to prevent a deadlock in single-process mode. Since the primordial
626 // thread in the renderer process runs the WebKit code and can sometimes
627 // make blocking calls to the UI thread (i.e. this thread), they need to run
628 // on separate threads.
629 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
631 base::Thread::Options options;
632 #if defined(OS_WIN) && !defined(OS_MACOSX)
633 // In-process plugins require this to be a UI message loop.
634 options.message_loop_type = base::MessageLoop::TYPE_UI;
635 #else
636 // We can't have multiple UI loops on Linux and Android, so we don't support
637 // in-process plugins.
638 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
639 #endif
640 in_process_renderer_->StartWithOptions(options);
642 g_in_process_thread = in_process_renderer_->message_loop();
644 OnProcessLaunched(); // Fake a callback that the process is ready.
645 } else {
646 // Build command line for renderer. We call AppendRendererCommandLine()
647 // first so the process type argument will appear first.
648 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
649 if (!renderer_prefix.empty())
650 cmd_line->PrependWrapper(renderer_prefix);
651 AppendRendererCommandLine(cmd_line);
652 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
654 // Spawn the child process asynchronously to avoid blocking the UI thread.
655 // As long as there's no renderer prefix, we can use the zygote process
656 // at this stage.
657 child_process_launcher_.reset(new ChildProcessLauncher(
658 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
659 cmd_line,
660 GetID(),
661 this));
663 fast_shutdown_started_ = false;
666 if (!gpu_observer_registered_) {
667 gpu_observer_registered_ = true;
668 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
671 power_monitor_broadcaster_.Init();
673 is_initialized_ = true;
674 init_time_ = base::TimeTicks::Now();
675 return true;
678 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
679 const std::string& channel_id) {
680 scoped_refptr<base::SingleThreadTaskRunner> runner =
681 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
682 if (ShouldUseMojoChannel()) {
683 VLOG(1) << "Mojo Channel is enabled on host";
684 scoped_refptr<base::SequencedTaskRunner> io_task_runner =
685 BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO)
686 ->task_runner();
687 if (!channel_mojo_host_) {
688 channel_mojo_host_.reset(new IPC::ChannelMojoHost(io_task_runner));
691 if (run_renderer_in_process()) {
692 ChannelInit::SetSingleProcessIOTaskRunner(io_task_runner);
695 return IPC::ChannelProxy::Create(
696 IPC::ChannelMojo::CreateServerFactory(
697 channel_mojo_host_->channel_delegate(), channel_id),
698 this,
699 runner.get());
702 return IPC::ChannelProxy::Create(
703 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
706 void RenderProcessHostImpl::CreateMessageFilters() {
707 DCHECK_CURRENTLY_ON(BrowserThread::UI);
708 const base::CommandLine& browser_command_line =
709 *base::CommandLine::ForCurrentProcess();
710 AddFilter(new ResourceSchedulerFilter(GetID()));
711 MediaInternals* media_internals = MediaInternals::GetInstance();
712 media::AudioManager* audio_manager =
713 BrowserMainLoop::GetInstance()->audio_manager();
714 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
715 // from guests.
716 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
717 new BrowserPluginMessageFilter(GetID()));
718 AddFilter(bp_message_filter.get());
720 scoped_refptr<RenderMessageFilter> render_message_filter(
721 new RenderMessageFilter(
722 GetID(),
723 #if defined(ENABLE_PLUGINS)
724 PluginServiceImpl::GetInstance(),
725 #else
726 NULL,
727 #endif
728 GetBrowserContext(),
729 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
730 widget_helper_.get(),
731 audio_manager,
732 media_internals,
733 storage_partition_impl_->GetDOMStorageContext()));
734 AddFilter(render_message_filter.get());
735 AddFilter(
736 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
737 BrowserContext* browser_context = GetBrowserContext();
738 ResourceContext* resource_context = browser_context->GetResourceContext();
740 scoped_refptr<net::URLRequestContextGetter> request_context(
741 browser_context->GetRequestContextForRenderProcess(GetID()));
742 scoped_refptr<net::URLRequestContextGetter> media_request_context(
743 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
745 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
746 base::Bind(&GetContexts, browser_context->GetResourceContext(),
747 request_context, media_request_context));
749 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
750 GetID(), PROCESS_TYPE_RENDERER,
751 storage_partition_impl_->GetAppCacheService(),
752 ChromeBlobStorageContext::GetFor(browser_context),
753 storage_partition_impl_->GetFileSystemContext(),
754 storage_partition_impl_->GetServiceWorkerContext(),
755 storage_partition_impl_->GetHostZoomLevelContext(),
756 get_contexts_callback);
758 AddFilter(resource_message_filter);
759 MediaStreamManager* media_stream_manager =
760 BrowserMainLoop::GetInstance()->media_stream_manager();
761 AddFilter(new AudioInputRendererHost(
762 audio_manager,
763 media_stream_manager,
764 AudioMirroringManager::GetInstance(),
765 BrowserMainLoop::GetInstance()->user_input_monitor()));
766 // The AudioRendererHost needs to be available for lookup, so it's
767 // stashed in a member variable.
768 audio_renderer_host_ = new AudioRendererHost(
769 GetID(),
770 audio_manager,
771 AudioMirroringManager::GetInstance(),
772 media_internals,
773 media_stream_manager);
774 AddFilter(audio_renderer_host_.get());
775 AddFilter(
776 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
777 AddFilter(new VideoCaptureHost(media_stream_manager));
778 AddFilter(new AppCacheDispatcherHost(
779 storage_partition_impl_->GetAppCacheService(),
780 GetID()));
781 AddFilter(new ClipboardMessageFilter);
782 AddFilter(new DOMStorageMessageFilter(
783 storage_partition_impl_->GetDOMStorageContext()));
784 AddFilter(new IndexedDBDispatcherHost(
785 GetID(),
786 storage_partition_impl_->GetURLRequestContext(),
787 storage_partition_impl_->GetIndexedDBContext(),
788 ChromeBlobStorageContext::GetFor(browser_context)));
790 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
791 AddFilter(gpu_message_filter_);
792 #if defined(ENABLE_WEBRTC)
793 AddFilter(new WebRTCIdentityServiceHost(
794 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
795 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
796 AddFilter(peer_connection_tracker_host_.get());
797 AddFilter(new MediaStreamDispatcherHost(
798 GetID(),
799 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
800 media_stream_manager));
801 AddFilter(new MediaStreamTrackMetricsHost());
802 #endif
803 #if defined(ENABLE_PLUGINS)
804 AddFilter(new PepperRendererConnection(GetID()));
805 #endif
806 AddFilter(new SpeechRecognitionDispatcherHost(
807 GetID(), storage_partition_impl_->GetURLRequestContext()));
808 AddFilter(new FileAPIMessageFilter(
809 GetID(),
810 storage_partition_impl_->GetURLRequestContext(),
811 storage_partition_impl_->GetFileSystemContext(),
812 ChromeBlobStorageContext::GetFor(browser_context),
813 StreamContext::GetFor(browser_context)));
814 AddFilter(new FileUtilitiesMessageFilter(GetID()));
815 AddFilter(new MimeRegistryMessageFilter());
816 AddFilter(new DatabaseMessageFilter(
817 storage_partition_impl_->GetDatabaseTracker()));
818 #if defined(OS_MACOSX)
819 AddFilter(new TextInputClientMessageFilter(GetID()));
820 #elif defined(OS_WIN)
821 // The FontCacheDispatcher is required only when we're using GDI rendering.
822 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
823 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
824 // should eventually be if (!ShouldUseDirectWrite()) guarded.
825 channel_->AddFilter(new FontCacheDispatcher());
826 #elif defined(OS_ANDROID)
827 browser_demuxer_android_ = new BrowserDemuxerAndroid();
828 AddFilter(browser_demuxer_android_.get());
829 #endif
830 #if defined(ENABLE_BROWSER_CDMS)
831 browser_cdm_manager_ = new BrowserCdmManager(GetID(), NULL);
832 AddFilter(browser_cdm_manager_.get());
833 #endif
835 WebSocketDispatcherHost::GetRequestContextCallback
836 websocket_request_context_callback(
837 base::Bind(&GetRequestContext, request_context,
838 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
840 AddFilter(
841 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
843 message_port_message_filter_ = new MessagePortMessageFilter(
844 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
845 base::Unretained(widget_helper_.get())));
846 AddFilter(message_port_message_filter_.get());
848 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
849 new ServiceWorkerDispatcherHost(
850 GetID(), message_port_message_filter_.get(), resource_context);
851 service_worker_filter->Init(
852 storage_partition_impl_->GetServiceWorkerContext());
853 AddFilter(service_worker_filter.get());
855 AddFilter(new SharedWorkerMessageFilter(
856 GetID(),
857 resource_context,
858 WorkerStoragePartition(
859 storage_partition_impl_->GetURLRequestContext(),
860 storage_partition_impl_->GetMediaURLRequestContext(),
861 storage_partition_impl_->GetAppCacheService(),
862 storage_partition_impl_->GetQuotaManager(),
863 storage_partition_impl_->GetFileSystemContext(),
864 storage_partition_impl_->GetDatabaseTracker(),
865 storage_partition_impl_->GetIndexedDBContext(),
866 storage_partition_impl_->GetServiceWorkerContext()),
867 message_port_message_filter_.get()));
869 #if defined(ENABLE_WEBRTC)
870 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
871 resource_context,
872 browser_context->GetRequestContextForRenderProcess(GetID()));
873 AddFilter(p2p_socket_dispatcher_host_.get());
874 #endif
876 AddFilter(new TraceMessageFilter());
877 AddFilter(new ResolveProxyMsgHelper(
878 browser_context->GetRequestContextForRenderProcess(GetID())));
879 AddFilter(new QuotaDispatcherHost(
880 GetID(),
881 storage_partition_impl_->GetQuotaManager(),
882 GetContentClient()->browser()->CreateQuotaPermissionContext()));
884 notification_message_filter_ = new NotificationMessageFilter(
885 GetID(),
886 resource_context,
887 browser_context);
888 AddFilter(notification_message_filter_.get());
890 AddFilter(new GamepadBrowserMessageFilter());
891 AddFilter(new DeviceLightMessageFilter());
892 AddFilter(new DeviceMotionMessageFilter());
893 AddFilter(new DeviceOrientationMessageFilter());
894 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
895 AddFilter(new HistogramMessageFilter());
896 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
897 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
898 AddFilter(new MemoryBenchmarkMessageFilter());
899 #endif
900 AddFilter(new PushMessagingMessageFilter(
901 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
902 #if defined(OS_ANDROID)
903 AddFilter(new ScreenOrientationMessageFilterAndroid());
904 #endif
905 AddFilter(new GeofencingDispatcherHost(
906 storage_partition_impl_->GetGeofencingManager()));
907 AddFilter(new NavigatorConnectDispatcherHost(
908 storage_partition_impl_->GetNavigatorConnectContext(),
909 message_port_message_filter_.get()));
910 if (browser_command_line.HasSwitch(
911 switches::kEnableExperimentalWebPlatformFeatures)) {
912 scoped_refptr<BluetoothDispatcherHost> bluetooth_dispatcher_host(
913 BluetoothDispatcherHost::Create());
914 AddFilter(bluetooth_dispatcher_host.get());
918 void RenderProcessHostImpl::RegisterMojoServices() {
919 mojo_application_host_->service_registry()->AddService(
920 base::Bind(&device::BatteryMonitorImpl::Create));
922 mojo_application_host_->service_registry()->AddService(
923 base::Bind(&device::VibrationManagerImpl::Create));
925 mojo_application_host_->service_registry()->AddService(
926 base::Bind(&PermissionServiceContext::CreateService,
927 base::Unretained(permission_service_context_.get())));
929 #if defined(OS_ANDROID)
930 ServiceRegistrarAndroid::RegisterProcessHostServices(
931 mojo_application_host_->service_registry_android());
932 #endif
934 GetContentClient()->browser()->OverrideRenderProcessMojoServices(
935 mojo_application_host_->service_registry());
938 int RenderProcessHostImpl::GetNextRoutingID() {
939 return widget_helper_->GetNextRoutingID();
942 void RenderProcessHostImpl::ResumeDeferredNavigation(
943 const GlobalRequestID& request_id) {
944 widget_helper_->ResumeDeferredNavigation(request_id);
947 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
948 const GlobalRequestID& request_id) {
949 widget_helper_->ResumeResponseDeferredAtStart(request_id);
952 void RenderProcessHostImpl::NotifyTimezoneChange() {
953 Send(new ViewMsg_TimezoneChange());
956 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
957 DCHECK(mojo_application_host_);
958 return mojo_application_host_->service_registry();
961 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
962 const {
963 return init_time_;
966 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
967 return subscribe_uniform_enabled_;
970 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
971 DCHECK(subscribe_uniform_enabled_);
972 subscription_set_.insert(target);
973 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
974 if (state) {
975 SendUpdateValueState(target, *state);
979 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
980 DCHECK(subscribe_uniform_enabled_);
981 subscription_set_.erase(target);
984 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
985 const gpu::ValueState& state) {
986 DCHECK(subscribe_uniform_enabled_);
987 if (subscription_set_.find(target) != subscription_set_.end()) {
988 GpuProcessHost::SendOnIO(
989 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
990 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
991 new GpuMsg_UpdateValueState(id_, target, state));
992 } else {
993 // Store the ValueState locally in case a Valuebuffer subscribes to it later
994 pending_valuebuffer_state_->UpdateState(target, state);
998 #if defined(ENABLE_BROWSER_CDMS)
999 media::BrowserCdm* RenderProcessHostImpl::GetBrowserCdm(int render_frame_id,
1000 int cdm_id) const {
1001 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1002 return browser_cdm_manager_->GetCdm(render_frame_id, cdm_id);
1004 #endif
1006 void RenderProcessHostImpl::AddRoute(
1007 int32 routing_id,
1008 IPC::Listener* listener) {
1009 CHECK(!listeners_.Lookup(routing_id))
1010 << "Found Routing ID Conflict: " << routing_id;
1011 listeners_.AddWithID(listener, routing_id);
1014 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
1015 DCHECK(listeners_.Lookup(routing_id) != NULL);
1016 listeners_.Remove(routing_id);
1018 #if defined(OS_WIN)
1019 // Dump the handle table if handle auditing is enabled.
1020 const base::CommandLine& browser_command_line =
1021 *base::CommandLine::ForCurrentProcess();
1022 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
1023 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
1024 DumpHandles();
1026 // We wait to close the channels until the child process has finished
1027 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
1028 return;
1030 #endif
1031 // Keep the one renderer thread around forever in single process mode.
1032 if (!run_renderer_in_process())
1033 Cleanup();
1036 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1037 observers_.AddObserver(observer);
1040 void RenderProcessHostImpl::RemoveObserver(
1041 RenderProcessHostObserver* observer) {
1042 observers_.RemoveObserver(observer);
1045 void RenderProcessHostImpl::ReceivedBadMessage() {
1046 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1047 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1048 return;
1050 if (run_renderer_in_process()) {
1051 // In single process mode it is better if we don't suicide but just
1052 // crash.
1053 CHECK(false);
1055 // We kill the renderer but don't include a NOTREACHED, because we want the
1056 // browser to try to survive when it gets illegal messages from the renderer.
1057 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1060 void RenderProcessHostImpl::WidgetRestored() {
1061 // Verify we were properly backgrounded.
1062 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1063 visible_widgets_++;
1064 SetBackgrounded(false);
1067 void RenderProcessHostImpl::WidgetHidden() {
1068 // On startup, the browser will call Hide
1069 if (backgrounded_)
1070 return;
1072 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1073 visible_widgets_--;
1074 DCHECK_GE(visible_widgets_, 0);
1075 if (visible_widgets_ == 0) {
1076 DCHECK(!backgrounded_);
1077 SetBackgrounded(true);
1081 int RenderProcessHostImpl::VisibleWidgetCount() const {
1082 return visible_widgets_;
1085 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1086 return is_isolated_guest_;
1089 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1090 return storage_partition_impl_;
1093 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1094 if (IsPinchVirtualViewportEnabled())
1095 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
1097 if (IsPropertyTreeVerificationEnabled())
1098 command_line->AppendSwitch(cc::switches::kEnablePropertyTreeVerification);
1100 if (IsDelegatedRendererEnabled())
1101 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1103 if (IsImplSidePaintingEnabled()) {
1104 command_line->AppendSwitchASCII(
1105 switches::kNumRasterThreads,
1106 base::IntToString(NumberOfRendererRasterThreads()));
1107 } else {
1108 command_line->AppendSwitch(switches::kDisableImplSidePainting);
1111 if (IsGpuRasterizationEnabled())
1112 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1114 if (IsThreadedGpuRasterizationEnabled())
1115 command_line->AppendSwitch(switches::kEnableThreadedGpuRasterization);
1117 int msaa_sample_count = GpuRasterizationMSAASampleCount();
1118 if (msaa_sample_count > 0) {
1119 command_line->AppendSwitchASCII(
1120 switches::kGpuRasterizationMSAASampleCount,
1121 base::IntToString(msaa_sample_count));
1124 DCHECK_IMPLIES(IsZeroCopyUploadEnabled(), !IsOneCopyUploadEnabled());
1125 DCHECK_IMPLIES(IsOneCopyUploadEnabled(), !IsZeroCopyUploadEnabled());
1126 if (IsZeroCopyUploadEnabled())
1127 command_line->AppendSwitch(switches::kEnableZeroCopy);
1128 if (!IsOneCopyUploadEnabled())
1129 command_line->AppendSwitch(switches::kDisableOneCopy);
1131 if (IsForceGpuRasterizationEnabled())
1132 command_line->AppendSwitch(switches::kForceGpuRasterization);
1134 command_line->AppendSwitchASCII(
1135 switches::kUseImageTextureTarget,
1136 base::UintToString(
1137 BrowserGpuChannelHostFactory::GetImageTextureTarget()));
1139 // Appending disable-gpu-feature switches due to software rendering list.
1140 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1141 DCHECK(gpu_data_manager);
1142 gpu_data_manager->AppendRendererCommandLine(command_line);
1145 void RenderProcessHostImpl::AppendRendererCommandLine(
1146 base::CommandLine* command_line) const {
1147 // Pass the process type first, so it shows first in process listings.
1148 command_line->AppendSwitchASCII(switches::kProcessType,
1149 switches::kRendererProcess);
1151 // Now send any options from our own command line we want to propagate.
1152 const base::CommandLine& browser_command_line =
1153 *base::CommandLine::ForCurrentProcess();
1154 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1156 // Pass on the browser locale.
1157 const std::string locale =
1158 GetContentClient()->browser()->GetApplicationLocale();
1159 command_line->AppendSwitchASCII(switches::kLang, locale);
1161 // If we run base::FieldTrials, we want to pass to their state to the
1162 // renderer so that it can act in accordance with each state, or record
1163 // histograms relating to the base::FieldTrial states.
1164 std::string field_trial_states;
1165 base::FieldTrialList::AllStatesToString(&field_trial_states);
1166 if (!field_trial_states.empty()) {
1167 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1168 field_trial_states);
1171 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1172 command_line, GetID());
1174 if (IsPinchToZoomEnabled())
1175 command_line->AppendSwitch(switches::kEnablePinch);
1177 #if defined(OS_WIN)
1178 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1179 base::DoubleToString(gfx::GetDPIScale()));
1180 command_line->AppendSwitchASCII(
1181 switches::kFontCacheSharedMemSuffix,
1182 base::UintToString(base::GetCurrentProcId()));
1183 #endif
1185 AppendCompositorCommandLineFlags(command_line);
1188 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1189 const base::CommandLine& browser_cmd,
1190 base::CommandLine* renderer_cmd) const {
1191 // Propagate the following switches to the renderer command line (along
1192 // with any associated values) if present in the browser command line.
1193 static const char* const kSwitchNames[] = {
1194 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1195 switches::kAllowLoopbackInPeerConnection,
1196 switches::kAudioBufferSize,
1197 switches::kAuditAllHandles,
1198 switches::kAuditHandles,
1199 switches::kBlinkPlatformLogChannels,
1200 switches::kBlockCrossSiteDocuments,
1201 switches::kDefaultTileWidth,
1202 switches::kDefaultTileHeight,
1203 switches::kDisable3DAPIs,
1204 switches::kDisableAcceleratedJpegDecoding,
1205 switches::kDisableAcceleratedVideoDecode,
1206 switches::kDisableBlinkScheduler,
1207 switches::kDisableBlinkFeatures,
1208 switches::kDisableBreakpad,
1209 switches::kDisablePreferCompositingToLCDText,
1210 switches::kDisableDatabases,
1211 switches::kDisableDirectNPAPIRequests,
1212 switches::kDisableDisplayList2dCanvas,
1213 switches::kDisableDistanceFieldText,
1214 switches::kDisableEncryptedMedia,
1215 switches::kDisableFileSystem,
1216 switches::kDisableGpuCompositing,
1217 switches::kDisableGpuVsync,
1218 switches::kDisableLowResTiling,
1219 switches::kDisableHistogramCustomizer,
1220 switches::kDisableLCDText,
1221 switches::kDisableLocalStorage,
1222 switches::kDisableLogging,
1223 switches::kDisableMediaSource,
1224 switches::kDisableMojoChannel,
1225 switches::kDisableNotifications,
1226 switches::kDisableOverlayScrollbar,
1227 switches::kDisablePinch,
1228 switches::kDisablePrefixedEncryptedMedia,
1229 switches::kDisableSeccompFilterSandbox,
1230 switches::kDisableSharedWorkers,
1231 switches::kDisableSVG1DOM,
1232 switches::kDisableThreadedCompositing,
1233 switches::kDisableThreadedScrolling,
1234 switches::kDisableTouchAdjustment,
1235 switches::kDisableTouchDragDrop,
1236 switches::kDisableTouchEditing,
1237 switches::kDisableV8IdleTasks,
1238 switches::kDomAutomationController,
1239 switches::kEnableBeginFrameScheduling,
1240 switches::kEnableBleedingEdgeRenderingFastPaths,
1241 switches::kEnableBlinkFeatures,
1242 switches::kEnableBrowserSideNavigation,
1243 switches::kEnablePreferCompositingToLCDText,
1244 switches::kEnableCredentialManagerAPI,
1245 switches::kEnableDeferredImageDecoding,
1246 switches::kEnableDelayAgnosticAec,
1247 switches::kEnableDisplayList2dCanvas,
1248 switches::kEnableDistanceFieldText,
1249 switches::kEnableExperimentalCanvasFeatures,
1250 switches::kEnableExperimentalWebPlatformFeatures,
1251 switches::kEnableGPUClientLogging,
1252 switches::kEnableGpuClientTracing,
1253 switches::kEnableGPUServiceLogging,
1254 switches::kEnableLinkDisambiguationPopup,
1255 switches::kEnableLowResTiling,
1256 switches::kEnableInbandTextTracks,
1257 switches::kEnableLCDText,
1258 switches::kEnableLogging,
1259 switches::kEnableMemoryBenchmarking,
1260 switches::kEnableNetworkInformation,
1261 switches::kEnableOverlayFullscreenVideo,
1262 switches::kEnableOverlayScrollbar,
1263 switches::kEnablePinch,
1264 switches::kEnablePreciseMemoryInfo,
1265 switches::kEnablePushMessagePayload,
1266 switches::kEnablePushMessagingHasPermission,
1267 switches::kEnableRendererMojoChannel,
1268 switches::kEnableSeccompFilterSandbox,
1269 switches::kEnableSkiaBenchmarking,
1270 switches::kEnableSlimmingPaint,
1271 switches::kEnableSmoothScrolling,
1272 switches::kEnableStatsTable,
1273 switches::kEnableStrictSiteIsolation,
1274 switches::kEnableThreadedCompositing,
1275 switches::kEnableTouchDragDrop,
1276 switches::kEnableTouchEditing,
1277 switches::kEnableUnsafeES3APIs,
1278 switches::kEnableViewport,
1279 switches::kEnableViewportMeta,
1280 switches::kEnableVtune,
1281 switches::kEnableWebGLDraftExtensions,
1282 switches::kEnableWebGLImageChromium,
1283 switches::kEnableWebMIDI,
1284 switches::kForceDeviceScaleFactor,
1285 switches::kForceDisplayList2dCanvas,
1286 switches::kFullMemoryCrashReport,
1287 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
1288 switches::kIPCConnectionTimeout,
1289 switches::kJavaScriptFlags,
1290 switches::kLoggingLevel,
1291 switches::kMainFrameResizesAreOrientationChanges,
1292 switches::kMaxUntiledLayerWidth,
1293 switches::kMaxUntiledLayerHeight,
1294 switches::kMemoryMetrics,
1295 switches::kNoReferrers,
1296 switches::kNoSandbox,
1297 switches::kPpapiInProcess,
1298 switches::kProfilerTiming,
1299 switches::kReducedReferrerGranularity,
1300 switches::kReduceSecurityForTesting,
1301 switches::kRegisterPepperPlugins,
1302 switches::kRendererStartupDialog,
1303 switches::kRootLayerScrolls,
1304 switches::kShowPaintRects,
1305 switches::kSitePerProcess,
1306 switches::kStatsCollectionController,
1307 switches::kTestType,
1308 switches::kTouchEvents,
1309 switches::kTraceToConsole,
1310 switches::kUseDiscardableMemory,
1311 // This flag needs to be propagated to the renderer process for
1312 // --in-process-webgl.
1313 switches::kUseGL,
1314 switches::kUseMobileUserAgent,
1315 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1316 switches::kV,
1317 switches::kVideoThreads,
1318 switches::kVModule,
1319 // Please keep these in alphabetical order. Compositor switches here should
1320 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1321 cc::switches::kCompositeToMailbox,
1322 cc::switches::kDisableCompositedAntialiasing,
1323 cc::switches::kDisableMainFrameBeforeActivation,
1324 cc::switches::kDisableThreadedAnimation,
1325 cc::switches::kEnableGpuBenchmarking,
1326 cc::switches::kEnableMainFrameBeforeActivation,
1327 cc::switches::kMaxTilesForInterestArea,
1328 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1329 cc::switches::kShowCompositedLayerBorders,
1330 cc::switches::kShowFPSCounter,
1331 cc::switches::kShowLayerAnimationBounds,
1332 cc::switches::kShowPropertyChangedRects,
1333 cc::switches::kShowReplicaScreenSpaceRects,
1334 cc::switches::kShowScreenSpaceRects,
1335 cc::switches::kShowSurfaceDamageRects,
1336 cc::switches::kSlowDownRasterScaleFactor,
1337 cc::switches::kStrictLayerPropertyChangeChecking,
1338 cc::switches::kTopControlsHideThreshold,
1339 cc::switches::kTopControlsShowThreshold,
1340 #if defined(ENABLE_PLUGINS)
1341 switches::kEnablePepperTesting,
1342 switches::kEnablePluginPowerSaver,
1343 #endif
1344 #if defined(ENABLE_WEBRTC)
1345 switches::kDisableWebRtcHWDecoding,
1346 switches::kDisableWebRtcHWEncoding,
1347 switches::kEnableWebRtcHWH264Encoding,
1348 switches::kWebRtcMaxCaptureFramerate,
1349 #endif
1350 switches::kEnableLowEndDeviceMode,
1351 switches::kDisableLowEndDeviceMode,
1352 #if defined(OS_ANDROID)
1353 switches::kDisableGestureRequirementForMediaPlayback,
1354 switches::kDisableWebRTC,
1355 switches::kMediaDrmEnableNonCompositing,
1356 switches::kNetworkCountryIso,
1357 switches::kDisableWebAudio,
1358 switches::kRendererWaitForJavaDebugger,
1359 #endif
1360 #if defined(OS_MACOSX)
1361 // Allow this to be set when invoking the browser and relayed along.
1362 switches::kEnableSandboxLogging,
1363 #endif
1364 #if defined(OS_MACOSX) && !defined(OS_IOS)
1365 switches::kDisableThreadedEventHandlingMac,
1366 #endif
1367 #if defined(OS_WIN)
1368 switches::kDisableDirectWrite,
1369 switches::kEnableWin32kRendererLockDown,
1370 switches::kDisableWin32kRendererLockDown,
1371 #endif
1372 #if defined(OS_CHROMEOS)
1373 switches::kDisableVaapiAcceleratedVideoEncode,
1374 #endif
1376 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1377 arraysize(kSwitchNames));
1379 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1380 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1381 // Pass kTraceStartup switch to renderer only if startup tracing has not
1382 // finished.
1383 renderer_cmd->AppendSwitchASCII(
1384 switches::kTraceStartup,
1385 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1388 // Disable databases in incognito mode.
1389 if (GetBrowserContext()->IsOffTheRecord() &&
1390 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1391 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1394 // Enforce the extra command line flags for impl-side painting.
1395 if (IsImplSidePaintingEnabled() &&
1396 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1397 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1399 // Add kWaitForDebugger to let renderer process wait for a debugger.
1400 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1401 // Look to pass-on the kWaitForDebugger flag.
1402 std::string value =
1403 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1404 if (value.empty() || value == switches::kRendererProcess) {
1405 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1410 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1411 if (run_renderer_in_process())
1412 return base::GetCurrentProcessHandle();
1414 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1415 return base::kNullProcessHandle;
1417 return child_process_launcher_->GetProcess().Handle();
1420 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1421 if (run_renderer_in_process())
1422 return false; // Single process mode never shuts down the renderer.
1424 #if defined(OS_ANDROID)
1425 // Android requires a different approach for killing.
1426 StopChildProcess(GetHandle());
1427 return true;
1428 #else
1429 return base::KillProcess(GetHandle(), exit_code, wait);
1430 #endif
1433 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1434 if (run_renderer_in_process())
1435 return false; // Single process mode never shuts down the renderer.
1437 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1438 return false;
1440 if (!child_process_launcher_.get() ||
1441 child_process_launcher_->IsStarting() ||
1442 !GetHandle())
1443 return false; // Render process hasn't started or is probably crashed.
1445 // Test if there's an unload listener.
1446 // NOTE: It's possible that an onunload listener may be installed
1447 // while we're shutting down, so there's a small race here. Given that
1448 // the window is small, it's unlikely that the web page has much
1449 // state that will be lost by not calling its unload handlers properly.
1450 if (!SuddenTerminationAllowed())
1451 return false;
1453 if (worker_ref_count_ != 0) {
1454 if (survive_for_worker_start_time_.is_null())
1455 survive_for_worker_start_time_ = base::TimeTicks::Now();
1456 return false;
1459 // Set this before ProcessDied() so observers can tell if the render process
1460 // died due to fast shutdown versus another cause.
1461 fast_shutdown_started_ = true;
1463 ProcessDied(false /* already_dead */, nullptr);
1464 return true;
1467 void RenderProcessHostImpl::DumpHandles() {
1468 #if defined(OS_WIN)
1469 Send(new ChildProcessMsg_DumpHandles());
1470 #else
1471 NOTIMPLEMENTED();
1472 #endif
1475 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1476 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1477 if (!channel_) {
1478 if (!is_initialized_) {
1479 queued_messages_.push(msg);
1480 return true;
1481 } else {
1482 delete msg;
1483 return false;
1487 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1488 queued_messages_.push(msg);
1489 return true;
1492 return channel_->Send(msg);
1495 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1496 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1497 // we ignore incoming messages.
1499 if (deleting_soon_ || fast_shutdown_started_)
1500 return false;
1502 mark_child_process_activity_time();
1503 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1504 // Dispatch control messages.
1505 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1506 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1507 OnShutdownRequest)
1508 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1509 OnDumpHandlesDone)
1510 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1511 OnSuddenTerminationChanged)
1512 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1513 OnUserMetricsRecordAction)
1514 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1515 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1516 #if defined(ENABLE_WEBRTC)
1517 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1518 OnRegisterAecDumpConsumer)
1519 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1520 OnUnregisterAecDumpConsumer)
1521 #endif
1522 // Adding single handlers for your service here is fine, but once your
1523 // service needs more than one handler, please extract them into a new
1524 // message filter and add that filter to CreateMessageFilters().
1525 IPC_END_MESSAGE_MAP()
1527 return true;
1530 // Dispatch incoming messages to the appropriate IPC::Listener.
1531 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1532 if (!listener) {
1533 if (msg.is_sync()) {
1534 // The listener has gone away, so we must respond or else the caller will
1535 // hang waiting for a reply.
1536 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1537 reply->set_reply_error();
1538 Send(reply);
1540 return true;
1542 return listener->OnMessageReceived(msg);
1545 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1546 #if defined(IPC_MESSAGE_LOG_ENABLED)
1547 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1548 IPC::Logging::GetInstance()->Enabled()));
1549 #endif
1551 tracked_objects::ThreadData::Status status =
1552 tracked_objects::ThreadData::status();
1553 Send(new ChildProcessMsg_SetProfilerStatus(status));
1556 void RenderProcessHostImpl::OnChannelError() {
1557 ProcessDied(true /* already_dead */, nullptr);
1560 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1561 // Message de-serialization failed. We consider this a capital crime. Kill the
1562 // renderer if we have one.
1563 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1564 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1565 PROCESS_TYPE_RENDERER);
1566 ReceivedBadMessage();
1569 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1570 return browser_context_;
1573 bool RenderProcessHostImpl::InSameStoragePartition(
1574 StoragePartition* partition) const {
1575 return storage_partition_impl_ == partition;
1578 int RenderProcessHostImpl::GetID() const {
1579 return id_;
1582 bool RenderProcessHostImpl::HasConnection() const {
1583 return channel_.get() != NULL;
1586 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1587 ignore_input_events_ = ignore_input_events;
1590 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1591 return ignore_input_events_;
1594 void RenderProcessHostImpl::Cleanup() {
1595 // If within_process_died_observer_ is true, one of our observers performed an
1596 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1597 // delay the destruction until all of the observer callbacks have been made,
1598 // and guarantee that the RenderProcessHostDestroyed observer callback is
1599 // always the last callback fired.
1600 if (within_process_died_observer_) {
1601 delayed_cleanup_needed_ = true;
1602 return;
1604 delayed_cleanup_needed_ = false;
1606 // Records the time when the process starts surviving for workers for UMA.
1607 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1608 survive_for_worker_start_time_.is_null()) {
1609 survive_for_worker_start_time_ = base::TimeTicks::Now();
1612 // When there are no other owners of this object, we can delete ourselves.
1613 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1614 if (!survive_for_worker_start_time_.is_null()) {
1615 UMA_HISTOGRAM_LONG_TIMES(
1616 "SharedWorker.RendererSurviveForWorkerTime",
1617 base::TimeTicks::Now() - survive_for_worker_start_time_);
1620 if (max_worker_count_ > 0) {
1621 // Record the max number of workers (SharedWorker or ServiceWorker)
1622 // that are simultaneously hosted in this renderer process.
1623 UMA_HISTOGRAM_COUNTS("Render.Workers.MaxWorkerCountInRendererProcess",
1624 max_worker_count_);
1627 // We cannot clean up twice; if this fails, there is an issue with our
1628 // control flow.
1629 DCHECK(!deleting_soon_);
1631 DCHECK_EQ(0, pending_views_);
1632 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1633 observers_,
1634 RenderProcessHostDestroyed(this));
1635 NotificationService::current()->Notify(
1636 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1637 Source<RenderProcessHost>(this),
1638 NotificationService::NoDetails());
1640 #ifndef NDEBUG
1641 is_self_deleted_ = true;
1642 #endif
1643 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1644 deleting_soon_ = true;
1645 // It's important not to wait for the DeleteTask to delete the channel
1646 // proxy. Kill it off now. That way, in case the profile is going away, the
1647 // rest of the objects attached to this RenderProcessHost start going
1648 // away first, since deleting the channel proxy will post a
1649 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1650 channel_.reset();
1652 // The following members should be cleared in ProcessDied() as well!
1653 gpu_message_filter_ = NULL;
1654 message_port_message_filter_ = NULL;
1655 #if defined(ENABLE_BROWSER_CDMS)
1656 browser_cdm_manager_ = NULL;
1657 #endif
1659 RemoveUserData(kSessionStorageHolderKey);
1661 // Remove ourself from the list of renderer processes so that we can't be
1662 // reused in between now and when the Delete task runs.
1663 UnregisterHost(GetID());
1667 void RenderProcessHostImpl::AddPendingView() {
1668 pending_views_++;
1671 void RenderProcessHostImpl::RemovePendingView() {
1672 DCHECK(pending_views_);
1673 pending_views_--;
1676 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1677 return sudden_termination_allowed_;
1680 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1681 return base::TimeTicks::Now() - child_process_activity_time_;
1684 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1685 widget_helper_->ResumeRequestsForView(route_id);
1688 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1689 FilterURL(this, empty_allowed, url);
1692 #if defined(ENABLE_WEBRTC)
1693 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1694 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1695 // Enable AEC dump for each registered consumer.
1696 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1697 it != aec_dump_consumers_.end(); ++it) {
1698 EnableAecDumpForId(file, *it);
1702 void RenderProcessHostImpl::DisableAecDump() {
1703 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1704 // Posting on the FILE thread and then replying back on the UI thread is only
1705 // for avoiding races between enable and disable. Nothing is done on the FILE
1706 // thread.
1707 BrowserThread::PostTaskAndReply(
1708 BrowserThread::FILE, FROM_HERE,
1709 base::Bind(&DisableAecDumpOnFileThread),
1710 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1711 weak_factory_.GetWeakPtr()));
1714 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1715 base::Callback<void(const std::string&)> callback) {
1716 webrtc_log_message_callback_ = callback;
1719 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1720 RenderProcessHostImpl::StartRtpDump(
1721 bool incoming,
1722 bool outgoing,
1723 const WebRtcRtpPacketCallback& packet_callback) {
1724 if (!p2p_socket_dispatcher_host_.get())
1725 return WebRtcStopRtpDumpCallback();
1727 BrowserThread::PostTask(BrowserThread::IO,
1728 FROM_HERE,
1729 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1730 p2p_socket_dispatcher_host_,
1731 incoming,
1732 outgoing,
1733 packet_callback));
1735 if (stop_rtp_dump_callback_.is_null()) {
1736 stop_rtp_dump_callback_ =
1737 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1738 p2p_socket_dispatcher_host_);
1740 return stop_rtp_dump_callback_;
1742 #endif
1744 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1745 return channel_.get();
1748 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1749 channel_->AddFilter(filter->GetFilter());
1752 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1753 if (static_cast<size_t>(GetActiveViewCount()) == count)
1754 return FastShutdownIfPossible();
1755 return false;
1758 bool RenderProcessHostImpl::FastShutdownStarted() const {
1759 return fast_shutdown_started_;
1762 // static
1763 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1764 g_all_hosts.Get().AddWithID(host, host_id);
1767 // static
1768 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1769 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1770 if (!host)
1771 return;
1773 g_all_hosts.Get().Remove(host_id);
1775 // Look up the map of site to process for the given browser_context,
1776 // in case we need to remove this process from it. It will be registered
1777 // under any sites it rendered that use process-per-site mode.
1778 SiteProcessMap* map =
1779 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1780 map->RemoveProcess(host);
1783 // static
1784 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1785 bool empty_allowed,
1786 GURL* url) {
1787 ChildProcessSecurityPolicyImpl* policy =
1788 ChildProcessSecurityPolicyImpl::GetInstance();
1790 if (empty_allowed && url->is_empty())
1791 return;
1793 // The browser process should never hear the swappedout:// URL from any
1794 // of the renderer's messages. Check for this in debug builds, but don't
1795 // let it crash a release browser.
1796 DCHECK(GURL(kSwappedOutURL) != *url);
1798 if (!url->is_valid()) {
1799 // Have to use about:blank for the denied case, instead of an empty GURL.
1800 // This is because the browser treats navigation to an empty GURL as a
1801 // navigation to the home page. This is often a privileged page
1802 // (chrome://newtab/) which is exactly what we don't want.
1803 *url = GURL(url::kAboutBlankURL);
1804 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1805 return;
1808 if (url->SchemeIs(url::kAboutScheme)) {
1809 // The renderer treats all URLs in the about: scheme as being about:blank.
1810 // Canonicalize about: URLs to about:blank.
1811 *url = GURL(url::kAboutBlankURL);
1812 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1815 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1816 // cannot swap processes or grant bindings.
1817 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1818 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1820 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1821 // If this renderer is not permitted to request this URL, we invalidate the
1822 // URL. This prevents us from storing the blocked URL and becoming confused
1823 // later.
1824 VLOG(1) << "Blocked URL " << url->spec();
1825 *url = GURL(url::kAboutBlankURL);
1826 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1830 // static
1831 bool RenderProcessHostImpl::IsSuitableHost(
1832 RenderProcessHost* host,
1833 BrowserContext* browser_context,
1834 const GURL& site_url) {
1835 if (run_renderer_in_process())
1836 return true;
1838 if (host->GetBrowserContext() != browser_context)
1839 return false;
1841 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1842 // and non-guest storage gets mixed. In the future, we might consider enabling
1843 // the sharing of guests, in this case this check should be removed and
1844 // InSameStoragePartition should handle the possible sharing.
1845 if (host->IsIsolatedGuest())
1846 return false;
1848 // Check whether the given host and the intended site_url will be using the
1849 // same StoragePartition, since a RenderProcessHost can only support a single
1850 // StoragePartition. This is relevant for packaged apps and isolated sites.
1851 StoragePartition* dest_partition =
1852 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1853 if (!host->InSameStoragePartition(dest_partition))
1854 return false;
1856 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1857 host->GetID()) !=
1858 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1859 browser_context, site_url)) {
1860 return false;
1863 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1866 // static
1867 bool RenderProcessHost::run_renderer_in_process() {
1868 return g_run_renderer_in_process_;
1871 // static
1872 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1873 g_run_renderer_in_process_ = value;
1875 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1876 if (value) {
1877 if (!command_line->HasSwitch(switches::kLang)) {
1878 // Modify the current process' command line to include the browser locale,
1879 // as the renderer expects this flag to be set.
1880 const std::string locale =
1881 GetContentClient()->browser()->GetApplicationLocale();
1882 command_line->AppendSwitchASCII(switches::kLang, locale);
1884 // TODO(piman): we should really send configuration through bools rather
1885 // than by parsing strings, i.e. sending an IPC rather than command line
1886 // args. crbug.com/314909
1887 AppendCompositorCommandLineFlags(command_line);
1891 // static
1892 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1893 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1894 return iterator(g_all_hosts.Pointer());
1897 // static
1898 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1899 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1900 return g_all_hosts.Get().Lookup(render_process_id);
1903 // static
1904 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1905 BrowserContext* browser_context, const GURL& url) {
1906 // Experimental:
1907 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1908 // try to reuse renderer processes when over the limit. (We could allow pages
1909 // from the same site to share, if we knew what the given process was
1910 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1911 // resource exhaustion issues if too many sites are open at once.
1912 const base::CommandLine& command_line =
1913 *base::CommandLine::ForCurrentProcess();
1914 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1915 command_line.HasSwitch(switches::kSitePerProcess))
1916 return false;
1918 if (run_renderer_in_process())
1919 return true;
1921 // NOTE: Sometimes it's necessary to create more render processes than
1922 // GetMaxRendererProcessCount(), for instance when we want to create
1923 // a renderer process for a browser context that has no existing
1924 // renderers. This is OK in moderation, since the
1925 // GetMaxRendererProcessCount() is conservative.
1926 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1927 return true;
1929 return GetContentClient()->browser()->
1930 ShouldTryToUseExistingProcessHost(browser_context, url);
1933 // static
1934 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1935 BrowserContext* browser_context,
1936 const GURL& site_url) {
1937 // First figure out which existing renderers we can use.
1938 std::vector<RenderProcessHost*> suitable_renderers;
1939 suitable_renderers.reserve(g_all_hosts.Get().size());
1941 iterator iter(AllHostsIterator());
1942 while (!iter.IsAtEnd()) {
1943 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1944 RenderProcessHostImpl::IsSuitableHost(
1945 iter.GetCurrentValue(),
1946 browser_context, site_url)) {
1947 suitable_renderers.push_back(iter.GetCurrentValue());
1949 iter.Advance();
1952 // Now pick a random suitable renderer, if we have any.
1953 if (!suitable_renderers.empty()) {
1954 int suitable_count = static_cast<int>(suitable_renderers.size());
1955 int random_index = base::RandInt(0, suitable_count - 1);
1956 return suitable_renderers[random_index];
1959 return NULL;
1962 // static
1963 bool RenderProcessHost::ShouldUseProcessPerSite(
1964 BrowserContext* browser_context,
1965 const GURL& url) {
1966 // Returns true if we should use the process-per-site model. This will be
1967 // the case if the --process-per-site switch is specified, or in
1968 // process-per-site-instance for particular sites (e.g., WebUI).
1969 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1970 const base::CommandLine& command_line =
1971 *base::CommandLine::ForCurrentProcess();
1972 if (command_line.HasSwitch(switches::kProcessPerSite))
1973 return true;
1975 // We want to consolidate particular sites like WebUI even when we are using
1976 // the process-per-tab or process-per-site-instance models.
1977 // Note: DevTools pages have WebUI type but should not reuse the same host.
1978 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1979 browser_context, url) &&
1980 !url.SchemeIs(kChromeDevToolsScheme)) {
1981 return true;
1984 // Otherwise let the content client decide, defaulting to false.
1985 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1986 url);
1989 // static
1990 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1991 BrowserContext* browser_context,
1992 const GURL& url) {
1993 // Look up the map of site to process for the given browser_context.
1994 SiteProcessMap* map =
1995 GetSiteProcessMapForBrowserContext(browser_context);
1997 // See if we have an existing process with appropriate bindings for this site.
1998 // If not, the caller should create a new process and register it.
1999 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2000 .possibly_invalid_spec();
2001 RenderProcessHost* host = map->FindProcess(site);
2002 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
2003 !IsSuitableHost(host, browser_context, url))) {
2004 // The registered process does not have an appropriate set of bindings for
2005 // the url. Remove it from the map so we can register a better one.
2006 RecordAction(
2007 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
2008 map->RemoveProcess(host);
2009 host = NULL;
2012 return host;
2015 void RenderProcessHostImpl::RegisterProcessHostForSite(
2016 BrowserContext* browser_context,
2017 RenderProcessHost* process,
2018 const GURL& url) {
2019 // Look up the map of site to process for the given browser_context.
2020 SiteProcessMap* map =
2021 GetSiteProcessMapForBrowserContext(browser_context);
2023 // Only register valid, non-empty sites. Empty or invalid sites will not
2024 // use process-per-site mode. We cannot check whether the process has
2025 // appropriate bindings here, because the bindings have not yet been granted.
2026 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2027 .possibly_invalid_spec();
2028 if (!site.empty())
2029 map->RegisterProcess(site, process);
2032 void RenderProcessHostImpl::ProcessDied(bool already_dead,
2033 RendererClosedDetails* known_details) {
2034 // Our child process has died. If we didn't expect it, it's a crash.
2035 // In any case, we need to let everyone know it's gone.
2036 // The OnChannelError notification can fire multiple times due to nested sync
2037 // calls to a renderer. If we don't have a valid channel here it means we
2038 // already handled the error.
2040 // It should not be possible for us to be called re-entrantly.
2041 DCHECK(!within_process_died_observer_);
2043 // It should not be possible for a process death notification to come in while
2044 // we are dying.
2045 DCHECK(!deleting_soon_);
2047 // child_process_launcher_ can be NULL in single process mode or if fast
2048 // termination happened.
2049 base::TerminationStatus status = base::TERMINATION_STATUS_NORMAL_TERMINATION;
2050 int exit_code = 0;
2051 if (known_details) {
2052 status = known_details->status;
2053 exit_code = known_details->exit_code;
2054 } else if (child_process_launcher_.get()) {
2055 status = child_process_launcher_->GetChildTerminationStatus(already_dead,
2056 &exit_code);
2059 RendererClosedDetails details(status, exit_code);
2060 mojo_application_host_->WillDestroySoon();
2062 child_process_launcher_.reset();
2063 channel_.reset();
2065 within_process_died_observer_ = true;
2066 NotificationService::current()->Notify(
2067 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2068 Source<RenderProcessHost>(this),
2069 Details<RendererClosedDetails>(&details));
2070 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2071 observers_,
2072 RenderProcessExited(this, status, exit_code));
2073 within_process_died_observer_ = false;
2075 gpu_message_filter_ = NULL;
2076 message_port_message_filter_ = NULL;
2077 #if defined(ENABLE_BROWSER_CDMS)
2078 browser_cdm_manager_ = NULL;
2079 #endif
2080 RemoveUserData(kSessionStorageHolderKey);
2082 IDMap<IPC::Listener>::iterator iter(&listeners_);
2083 while (!iter.IsAtEnd()) {
2084 iter.GetCurrentValue()->OnMessageReceived(
2085 FrameHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2086 static_cast<int>(status),
2087 exit_code));
2088 iter.Advance();
2091 mojo_application_host_.reset(new MojoApplicationHost);
2093 // It's possible that one of the calls out to the observers might have caused
2094 // this object to be no longer needed.
2095 if (delayed_cleanup_needed_)
2096 Cleanup();
2098 // This object is not deleted at this point and might be reused later.
2099 // TODO(darin): clean this up
2102 int RenderProcessHost::GetActiveViewCount() {
2103 int num_active_views = 0;
2104 scoped_ptr<RenderWidgetHostIterator> widgets(
2105 RenderWidgetHost::GetRenderWidgetHosts());
2106 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2107 // Count only RenderWidgetHosts in this process.
2108 if (widget->GetProcess()->GetID() == GetID())
2109 num_active_views++;
2111 return num_active_views;
2114 // Frame subscription API for this class is for accelerated composited path
2115 // only. These calls are redirected to GpuMessageFilter.
2116 void RenderProcessHostImpl::BeginFrameSubscription(
2117 int route_id,
2118 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2119 if (!gpu_message_filter_)
2120 return;
2121 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2122 &GpuMessageFilter::BeginFrameSubscription,
2123 gpu_message_filter_,
2124 route_id, base::Passed(&subscriber)));
2127 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2128 if (!gpu_message_filter_)
2129 return;
2130 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2131 &GpuMessageFilter::EndFrameSubscription,
2132 gpu_message_filter_,
2133 route_id));
2136 #if defined(ENABLE_WEBRTC)
2137 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2138 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2139 if (!webrtc_log_message_callback_.is_null())
2140 webrtc_log_message_callback_.Run(message);
2142 #endif
2144 void RenderProcessHostImpl::ReleaseOnCloseACK(
2145 RenderProcessHost* host,
2146 const SessionStorageNamespaceMap& sessions,
2147 int view_route_id) {
2148 DCHECK(host);
2149 if (sessions.empty())
2150 return;
2151 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2152 (host->GetUserData(kSessionStorageHolderKey));
2153 if (!holder) {
2154 holder = new SessionStorageHolder();
2155 host->SetUserData(
2156 kSessionStorageHolderKey,
2157 holder);
2159 holder->Hold(sessions, view_route_id);
2162 void RenderProcessHostImpl::OnShutdownRequest() {
2163 // Don't shut down if there are active RenderViews, or if there are pending
2164 // RenderViews being swapped back in.
2165 // In single process mode, we never shutdown the renderer.
2166 int num_active_views = GetActiveViewCount();
2167 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2168 return;
2170 // Notify any contents that might have swapped out renderers from this
2171 // process. They should not attempt to swap them back in.
2172 NotificationService::current()->Notify(
2173 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2174 Source<RenderProcessHost>(this),
2175 NotificationService::NoDetails());
2177 mojo_application_host_->WillDestroySoon();
2179 Send(new ChildProcessMsg_Shutdown());
2182 void RenderProcessHostImpl::OnSuddenTerminationChanged(bool enabled) {
2183 sudden_termination_allowed_ = enabled;
2186 void RenderProcessHostImpl::OnDumpHandlesDone() {
2187 Cleanup();
2190 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2191 // Note: we always set the backgrounded_ value. If the process is NULL
2192 // (and hence hasn't been created yet), we will set the process priority
2193 // later when we create the process.
2194 backgrounded_ = backgrounded;
2195 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2196 return;
2198 // Don't background processes which have active audio streams.
2199 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2200 return;
2202 #if defined(OS_WIN)
2203 // The cbstext.dll loads as a global GetMessage hook in the browser process
2204 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2205 // background thread. If the UI thread invokes this API just when it is
2206 // intercepted the stack is messed up on return from the interceptor
2207 // which causes random crashes in the browser process. Our hack for now
2208 // is to not invoke the SetPriorityClass API if the dll is loaded.
2209 if (GetModuleHandle(L"cbstext.dll"))
2210 return;
2211 #endif // OS_WIN
2213 #if defined(OS_WIN)
2214 // Same as below, but bound to an experiment (http://crbug.com/458594)
2215 // initially on Windows. Enabled by default in the asbence of field trials to
2216 // get coverage on the perf waterfall.
2217 base::FieldTrial* trial =
2218 base::FieldTrialList::Find("BackgroundRendererProcesses");
2219 if (!trial || (trial->group_name() != "Disallow" &&
2220 trial->group_name() != "AllowBackgroundModeFromRenderer")) {
2221 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2223 #else
2224 // Control the background state from the browser process, otherwise the task
2225 // telling the renderer to "unbackground" itself may be preempted by other
2226 // tasks executing at lowered priority ahead of it or simply by not being
2227 // swiftly scheduled by the OS per the low process priority
2228 // (http://crbug.com/398103).
2229 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2230 #endif // OS_WIN
2232 // Notify the child process of background state.
2233 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2236 void RenderProcessHostImpl::OnProcessLaunched() {
2237 // No point doing anything, since this object will be destructed soon. We
2238 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2239 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2240 // properly cleanup.
2241 if (deleting_soon_)
2242 return;
2244 if (child_process_launcher_) {
2245 DCHECK(child_process_launcher_->GetProcess().IsValid());
2246 SetBackgrounded(backgrounded_);
2249 // NOTE: This needs to be before sending queued messages because
2250 // ExtensionService uses this notification to initialize the renderer process
2251 // with state that must be there before any JavaScript executes.
2253 // The queued messages contain such things as "navigate". If this notification
2254 // was after, we can end up executing JavaScript before the initialization
2255 // happens.
2256 NotificationService::current()->Notify(
2257 NOTIFICATION_RENDERER_PROCESS_CREATED,
2258 Source<RenderProcessHost>(this),
2259 NotificationService::NoDetails());
2261 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2262 // This way, Mojo can be safely used from the renderer in response to any
2263 // Chrome IPC message.
2264 mojo_application_host_->Activate(this, GetHandle());
2266 if (channel_mojo_host_)
2267 channel_mojo_host_->OnClientLaunched(GetHandle());
2269 while (!queued_messages_.empty()) {
2270 Send(queued_messages_.front());
2271 queued_messages_.pop();
2274 #if defined(ENABLE_WEBRTC)
2275 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2276 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2277 #endif
2280 void RenderProcessHostImpl::OnProcessLaunchFailed() {
2281 RendererClosedDetails details { base::TERMINATION_STATUS_PROCESS_WAS_KILLED,
2282 -1 };
2283 ProcessDied(true, &details);
2286 scoped_refptr<AudioRendererHost>
2287 RenderProcessHostImpl::audio_renderer_host() const {
2288 return audio_renderer_host_;
2291 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2292 const std::string& action) {
2293 RecordComputedAction(action);
2296 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2297 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2298 (GetUserData(kSessionStorageHolderKey));
2299 if (!holder)
2300 return;
2301 holder->Release(old_route_id);
2304 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2305 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2308 void RenderProcessHostImpl::OnGpuSwitched() {
2309 // We are updating all widgets including swapped out ones.
2310 scoped_ptr<RenderWidgetHostIterator> widgets(
2311 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2312 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2313 if (!widget->IsRenderView())
2314 continue;
2316 // Skip widgets in other processes.
2317 if (widget->GetProcess()->GetID() != GetID())
2318 continue;
2320 RenderViewHost* rvh = RenderViewHost::From(widget);
2321 rvh->OnWebkitPreferencesChanged();
2325 #if defined(ENABLE_WEBRTC)
2326 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2327 BrowserThread::PostTask(
2328 BrowserThread::UI,
2329 FROM_HERE,
2330 base::Bind(
2331 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2332 weak_factory_.GetWeakPtr(),
2333 id));
2336 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2337 BrowserThread::PostTask(
2338 BrowserThread::UI,
2339 FROM_HERE,
2340 base::Bind(
2341 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2342 weak_factory_.GetWeakPtr(),
2343 id));
2346 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2347 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2348 aec_dump_consumers_.push_back(id);
2349 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2350 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2351 id);
2355 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2356 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2357 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2358 it != aec_dump_consumers_.end(); ++it) {
2359 if (*it == id) {
2360 aec_dump_consumers_.erase(it);
2361 break;
2366 #if defined(OS_WIN)
2367 #define IntToStringType base::IntToString16
2368 #else
2369 #define IntToStringType base::IntToString
2370 #endif
2372 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2373 int id) {
2374 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2375 base::FilePath unique_file =
2376 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2377 .AddExtension(IntToStringType(id));
2378 BrowserThread::PostTaskAndReplyWithResult(
2379 BrowserThread::FILE, FROM_HERE,
2380 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2381 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2382 weak_factory_.GetWeakPtr(),
2383 id));
2386 #undef IntToStringType
2388 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2389 int id,
2390 IPC::PlatformFileForTransit file_for_transit) {
2391 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2392 return;
2393 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2396 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2397 Send(new AecDumpMsg_DisableAecDump());
2399 #endif
2401 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2402 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2403 ++worker_ref_count_;
2404 if (worker_ref_count_ > max_worker_count_)
2405 max_worker_count_ = worker_ref_count_;
2408 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2409 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2410 DCHECK_GT(worker_ref_count_, 0);
2411 --worker_ref_count_;
2412 if (worker_ref_count_ == 0)
2413 Cleanup();
2416 void RenderProcessHostImpl::GetAudioOutputControllers(
2417 const GetAudioOutputControllersCallback& callback) const {
2418 audio_renderer_host()->GetOutputControllers(callback);
2421 } // namespace content