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