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