Add command line flag to force raster worker threads to normal priority.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobc724d161ce2702e537be1d5fb2d67b8a87214ff4
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Represents the browser side of the browser <--> renderer communication
6 // channel. There will be one RenderProcessHost per renderer process.
8 #include "content/browser/renderer_host/render_process_host_impl.h"
10 #include <algorithm>
11 #include <limits>
12 #include <vector>
14 #include "base/base_switches.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/callback.h"
18 #include "base/command_line.h"
19 #include "base/debug/trace_event.h"
20 #include "base/files/file.h"
21 #include "base/lazy_instance.h"
22 #include "base/logging.h"
23 #include "base/metrics/field_trial.h"
24 #include "base/metrics/histogram.h"
25 #include "base/process/process_handle.h"
26 #include "base/rand_util.h"
27 #include "base/stl_util.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_util.h"
30 #include "base/supports_user_data.h"
31 #include "base/sys_info.h"
32 #include "base/threading/thread.h"
33 #include "base/threading/thread_restrictions.h"
34 #include "base/tracked_objects.h"
35 #include "cc/base/switches.h"
36 #include "content/browser/appcache/appcache_dispatcher_host.h"
37 #include "content/browser/appcache/chrome_appcache_service.h"
38 #include "content/browser/bluetooth/bluetooth_dispatcher_host.h"
39 #include "content/browser/browser_child_process_host_impl.h"
40 #include "content/browser/browser_main.h"
41 #include "content/browser/browser_main_loop.h"
42 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
43 #include "content/browser/child_process_security_policy_impl.h"
44 #include "content/browser/device_sensors/device_light_message_filter.h"
45 #include "content/browser/device_sensors/device_motion_message_filter.h"
46 #include "content/browser/device_sensors/device_orientation_message_filter.h"
47 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
48 #include "content/browser/dom_storage/dom_storage_message_filter.h"
49 #include "content/browser/download/mhtml_generation_manager.h"
50 #include "content/browser/fileapi/chrome_blob_storage_context.h"
51 #include "content/browser/fileapi/fileapi_message_filter.h"
52 #include "content/browser/frame_host/render_frame_message_filter.h"
53 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
54 #include "content/browser/gpu/browser_gpu_channel_host_factory.h"
55 #include "content/browser/gpu/compositor_util.h"
56 #include "content/browser/gpu/gpu_data_manager_impl.h"
57 #include "content/browser/gpu/gpu_process_host.h"
58 #include "content/browser/gpu/shader_disk_cache.h"
59 #include "content/browser/histogram_message_filter.h"
60 #include "content/browser/indexed_db/indexed_db_context_impl.h"
61 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
62 #include "content/browser/loader/resource_message_filter.h"
63 #include "content/browser/loader/resource_scheduler_filter.h"
64 #include "content/browser/media/capture/audio_mirroring_manager.h"
65 #include "content/browser/media/media_internals.h"
66 #include "content/browser/media/midi_host.h"
67 #include "content/browser/message_port_message_filter.h"
68 #include "content/browser/mime_registry_message_filter.h"
69 #include "content/browser/mojo/mojo_application_host.h"
70 #include "content/browser/navigator_connect/navigator_connect_dispatcher_host.h"
71 #include "content/browser/notifications/notification_message_filter.h"
72 #include "content/browser/permissions/permission_service_context.h"
73 #include "content/browser/permissions/permission_service_impl.h"
74 #include "content/browser/profiler_message_filter.h"
75 #include "content/browser/push_messaging/push_messaging_message_filter.h"
76 #include "content/browser/quota_dispatcher_host.h"
77 #include "content/browser/renderer_host/clipboard_message_filter.h"
78 #include "content/browser/renderer_host/database_message_filter.h"
79 #include "content/browser/renderer_host/file_utilities_message_filter.h"
80 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
81 #include "content/browser/renderer_host/gpu_message_filter.h"
82 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
83 #include "content/browser/renderer_host/media/audio_renderer_host.h"
84 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
85 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
86 #include "content/browser/renderer_host/media/video_capture_host.h"
87 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
88 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
89 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
90 #include "content/browser/renderer_host/render_message_filter.h"
91 #include "content/browser/renderer_host/render_view_host_delegate.h"
92 #include "content/browser/renderer_host/render_view_host_impl.h"
93 #include "content/browser/renderer_host/render_widget_helper.h"
94 #include "content/browser/renderer_host/render_widget_host_impl.h"
95 #include "content/browser/renderer_host/text_input_client_message_filter.h"
96 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
97 #include "content/browser/resolve_proxy_msg_helper.h"
98 #include "content/browser/service_worker/service_worker_context_wrapper.h"
99 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
100 #include "content/browser/shared_worker/shared_worker_message_filter.h"
101 #include "content/browser/shared_worker/worker_storage_partition.h"
102 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
103 #include "content/browser/storage_partition_impl.h"
104 #include "content/browser/streams/stream_context.h"
105 #include "content/browser/tracing/trace_message_filter.h"
106 #include "content/browser/webui/web_ui_controller_factory_registry.h"
107 #include "content/common/child_process_host_impl.h"
108 #include "content/common/child_process_messages.h"
109 #include "content/common/content_switches_internal.h"
110 #include "content/common/gpu/gpu_memory_buffer_factory.h"
111 #include "content/common/gpu/gpu_messages.h"
112 #include "content/common/mojo/mojo_messages.h"
113 #include "content/common/resource_messages.h"
114 #include "content/common/view_messages.h"
115 #include "content/public/browser/browser_context.h"
116 #include "content/public/browser/content_browser_client.h"
117 #include "content/public/browser/notification_service.h"
118 #include "content/public/browser/notification_types.h"
119 #include "content/public/browser/render_process_host_factory.h"
120 #include "content/public/browser/render_process_host_observer.h"
121 #include "content/public/browser/render_widget_host.h"
122 #include "content/public/browser/render_widget_host_iterator.h"
123 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
124 #include "content/public/browser/resource_context.h"
125 #include "content/public/browser/user_metrics.h"
126 #include "content/public/browser/worker_service.h"
127 #include "content/public/common/content_constants.h"
128 #include "content/public/common/content_switches.h"
129 #include "content/public/common/process_type.h"
130 #include "content/public/common/resource_type.h"
131 #include "content/public/common/result_codes.h"
132 #include "content/public/common/sandboxed_process_launcher_delegate.h"
133 #include "content/public/common/url_constants.h"
134 #include "device/battery/battery_monitor_impl.h"
135 #include "device/vibration/vibration_manager_impl.h"
136 #include "gpu/GLES2/gl2extchromium.h"
137 #include "gpu/command_buffer/client/gpu_switches.h"
138 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
139 #include "gpu/command_buffer/service/gpu_switches.h"
140 #include "ipc/ipc_channel.h"
141 #include "ipc/ipc_logging.h"
142 #include "ipc/ipc_switches.h"
143 #include "ipc/mojo/ipc_channel_mojo.h"
144 #include "ipc/mojo/ipc_channel_mojo_host.h"
145 #include "media/base/media_switches.h"
146 #include "net/url_request/url_request_context_getter.h"
147 #include "ppapi/shared_impl/ppapi_switches.h"
148 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
149 #include "third_party/skia/include/core/SkBitmap.h"
150 #include "ui/base/ui_base_switches.h"
151 #include "ui/events/event_switches.h"
152 #include "ui/gfx/switches.h"
153 #include "ui/gl/gl_switches.h"
154 #include "ui/gl/gpu_switching_manager.h"
155 #include "ui/native_theme/native_theme_switches.h"
157 #if defined(OS_ANDROID)
158 #include "content/browser/android/child_process_launcher_android.h"
159 #include "content/browser/media/android/browser_demuxer_android.h"
160 #include "content/browser/mojo/service_registrar_android.h"
161 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
162 #endif
164 #if defined(OS_WIN)
165 #include "base/win/scoped_com_initializer.h"
166 #include "content/common/font_cache_dispatcher_win.h"
167 #include "content/common/sandbox_win.h"
168 #include "ui/gfx/win/dpi.h"
169 #endif
171 #if defined(ENABLE_BROWSER_CDMS)
172 #include "content/browser/media/cdm/browser_cdm_manager.h"
173 #endif
175 #if defined(ENABLE_PLUGINS)
176 #include "content/browser/plugin_service_impl.h"
177 #endif
179 #if defined(ENABLE_WEBRTC)
180 #include "content/browser/media/webrtc_internals.h"
181 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
182 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
183 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
184 #include "content/common/media/aec_dump_messages.h"
185 #include "content/common/media/media_stream_messages.h"
186 #endif
188 extern bool g_exited_main_message_loop;
190 namespace content {
191 namespace {
193 const char kSiteProcessMapKeyName[] = "content_site_process_map";
195 void CacheShaderInfo(int32 id, base::FilePath path) {
196 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
199 void RemoveShaderInfo(int32 id) {
200 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
203 net::URLRequestContext* GetRequestContext(
204 scoped_refptr<net::URLRequestContextGetter> request_context,
205 scoped_refptr<net::URLRequestContextGetter> media_request_context,
206 ResourceType resource_type) {
207 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
208 // context specific to media for handling it because these resources have
209 // specific needs for caching.
210 if (resource_type == RESOURCE_TYPE_MEDIA)
211 return media_request_context->GetURLRequestContext();
212 return request_context->GetURLRequestContext();
215 void GetContexts(
216 ResourceContext* resource_context,
217 scoped_refptr<net::URLRequestContextGetter> request_context,
218 scoped_refptr<net::URLRequestContextGetter> media_request_context,
219 const ResourceHostMsg_Request& request,
220 ResourceContext** resource_context_out,
221 net::URLRequestContext** request_context_out) {
222 *resource_context_out = resource_context;
223 *request_context_out =
224 GetRequestContext(request_context, media_request_context,
225 request.resource_type);
228 #if defined(ENABLE_WEBRTC)
229 // Creates a file used for diagnostic echo canceller recordings for handing
230 // over to the renderer.
231 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
232 base::FilePath file_path,
233 base::ProcessHandle process) {
234 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
235 base::File dump_file(file_path,
236 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
237 if (!dump_file.IsValid()) {
238 VLOG(1) << "Could not open AEC dump file, error=" <<
239 dump_file.error_details();
240 return IPC::InvalidPlatformFileForTransit();
242 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
245 // Does nothing. Just to avoid races between enable and disable.
246 void DisableAecDumpOnFileThread() {
247 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
249 #endif
251 // the global list of all renderer processes
252 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
253 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
255 // Map of site to process, to ensure we only have one RenderProcessHost per
256 // site in process-per-site mode. Each map is specific to a BrowserContext.
257 class SiteProcessMap : public base::SupportsUserData::Data {
258 public:
259 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
260 SiteProcessMap() {}
262 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
263 map_[site] = process;
266 RenderProcessHost* FindProcess(const std::string& site) {
267 SiteToProcessMap::iterator i = map_.find(site);
268 if (i != map_.end())
269 return i->second;
270 return NULL;
273 void RemoveProcess(RenderProcessHost* host) {
274 // Find all instances of this process in the map, then separately remove
275 // them.
276 std::set<std::string> sites;
277 for (SiteToProcessMap::const_iterator i = map_.begin();
278 i != map_.end();
279 i++) {
280 if (i->second == host)
281 sites.insert(i->first);
283 for (std::set<std::string>::iterator i = sites.begin();
284 i != sites.end();
285 i++) {
286 SiteToProcessMap::iterator iter = map_.find(*i);
287 if (iter != map_.end()) {
288 DCHECK_EQ(iter->second, host);
289 map_.erase(iter);
294 private:
295 SiteToProcessMap map_;
298 // Find the SiteProcessMap specific to the given context.
299 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
300 DCHECK(context);
301 SiteProcessMap* map = static_cast<SiteProcessMap*>(
302 context->GetUserData(kSiteProcessMapKeyName));
303 if (!map) {
304 map = new SiteProcessMap();
305 context->SetUserData(kSiteProcessMapKeyName, map);
307 return map;
310 // NOTE: changes to this class need to be reviewed by the security team.
311 class RendererSandboxedProcessLauncherDelegate
312 : public SandboxedProcessLauncherDelegate {
313 public:
314 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
315 #if defined(OS_POSIX)
316 : ipc_fd_(channel->TakeClientFileDescriptor())
317 #endif // OS_POSIX
320 ~RendererSandboxedProcessLauncherDelegate() override {}
322 #if defined(OS_WIN)
323 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
324 bool* success) {
325 AddBaseHandleClosePolicy(policy);
326 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
329 #elif defined(OS_POSIX)
330 bool ShouldUseZygote() override {
331 const base::CommandLine& browser_command_line =
332 *base::CommandLine::ForCurrentProcess();
333 base::CommandLine::StringType renderer_prefix =
334 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
335 return renderer_prefix.empty();
337 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
338 #endif // OS_WIN
340 private:
341 #if defined(OS_POSIX)
342 base::ScopedFD ipc_fd_;
343 #endif // OS_POSIX
346 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
348 class SessionStorageHolder : public base::SupportsUserData::Data {
349 public:
350 SessionStorageHolder() {}
351 ~SessionStorageHolder() override {}
353 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
354 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
357 void Release(int old_route_id) {
358 session_storage_namespaces_awaiting_close_.erase(old_route_id);
361 private:
362 std::map<int, SessionStorageNamespaceMap >
363 session_storage_namespaces_awaiting_close_;
364 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
367 } // namespace
369 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
371 base::MessageLoop* g_in_process_thread;
373 base::MessageLoop*
374 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
375 return g_in_process_thread;
378 // Stores the maximum number of renderer processes the content module can
379 // create.
380 static size_t g_max_renderer_count_override = 0;
382 // static
383 size_t RenderProcessHost::GetMaxRendererProcessCount() {
384 if (g_max_renderer_count_override)
385 return g_max_renderer_count_override;
387 #if defined(OS_ANDROID)
388 // On Android we don't maintain a limit of renderer process hosts - we are
389 // happy with keeping a lot of these, as long as the number of live renderer
390 // processes remains reasonable, and on Android the OS takes care of that.
391 return std::numeric_limits<size_t>::max();
392 #endif
394 // On other platforms, we calculate the maximum number of renderer process
395 // hosts according to the amount of installed memory as reported by the OS.
396 // The calculation assumes that you want the renderers to use half of the
397 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
398 // this assumption, you need to adjust the ThirtyFourTabs test to match the
399 // expected number of processes.
401 // With the given amounts of installed memory below on a 32-bit CPU, the
402 // maximum renderer count will roughly be as follows:
404 // 128 MB -> 3
405 // 512 MB -> 6
406 // 1024 MB -> 12
407 // 4096 MB -> 51
408 // 16384 MB -> 82 (kMaxRendererProcessCount)
410 static size_t max_count = 0;
411 if (!max_count) {
412 const size_t kEstimatedWebContentsMemoryUsage =
413 #if defined(ARCH_CPU_64_BITS)
414 60; // In MB
415 #else
416 40; // In MB
417 #endif
418 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
419 max_count /= kEstimatedWebContentsMemoryUsage;
421 const size_t kMinRendererProcessCount = 3;
422 max_count = std::max(max_count, kMinRendererProcessCount);
423 max_count = std::min(max_count, kMaxRendererProcessCount);
425 return max_count;
428 // static
429 bool g_run_renderer_in_process_ = false;
431 // static
432 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
433 g_max_renderer_count_override = count;
436 RenderProcessHostImpl::RenderProcessHostImpl(
437 BrowserContext* browser_context,
438 StoragePartitionImpl* storage_partition_impl,
439 bool is_isolated_guest)
440 : fast_shutdown_started_(false),
441 deleting_soon_(false),
442 #ifndef NDEBUG
443 is_self_deleted_(false),
444 #endif
445 pending_views_(0),
446 mojo_application_host_(new MojoApplicationHost),
447 visible_widgets_(0),
448 backgrounded_(true),
449 is_initialized_(false),
450 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
451 browser_context_(browser_context),
452 storage_partition_impl_(storage_partition_impl),
453 sudden_termination_allowed_(true),
454 ignore_input_events_(false),
455 is_isolated_guest_(is_isolated_guest),
456 gpu_observer_registered_(false),
457 delayed_cleanup_needed_(false),
458 within_process_died_observer_(false),
459 power_monitor_broadcaster_(this),
460 worker_ref_count_(0),
461 permission_service_context_(new PermissionServiceContext(this)),
462 pending_valuebuffer_state_(new gpu::ValueStateMap()),
463 subscribe_uniform_enabled_(false),
464 weak_factory_(this) {
465 widget_helper_ = new RenderWidgetHelper();
467 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
469 CHECK(!g_exited_main_message_loop);
470 RegisterHost(GetID(), this);
471 g_all_hosts.Get().set_check_on_null_data(true);
472 // Initialize |child_process_activity_time_| to a reasonable value.
473 mark_child_process_activity_time();
475 if (!GetBrowserContext()->IsOffTheRecord() &&
476 !base::CommandLine::ForCurrentProcess()->HasSwitch(
477 switches::kDisableGpuShaderDiskCache)) {
478 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
479 base::Bind(&CacheShaderInfo, GetID(),
480 storage_partition_impl_->GetPath()));
482 subscribe_uniform_enabled_ =
483 base::CommandLine::ForCurrentProcess()->HasSwitch(
484 switches::kEnableSubscribeUniformExtension);
486 // Note: When we create the RenderProcessHostImpl, it's technically
487 // backgrounded, because it has no visible listeners. But the process
488 // doesn't actually exist yet, so we'll Background it later, after
489 // creation.
492 // static
493 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
494 DCHECK(g_run_renderer_in_process_);
496 switch (g_all_hosts.Pointer()->size()) {
497 case 0:
498 return;
499 case 1: {
500 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
501 AllHostsIterator().GetCurrentValue());
502 FOR_EACH_OBSERVER(RenderProcessHostObserver,
503 host->observers_,
504 RenderProcessHostDestroyed(host));
505 #ifndef NDEBUG
506 host->is_self_deleted_ = true;
507 #endif
508 delete host;
509 return;
511 default:
512 NOTREACHED() << "There should be only one RenderProcessHost when running "
513 << "in-process.";
517 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
518 RendererMainThreadFactoryFunction create) {
519 g_renderer_main_thread_factory = create;
522 RenderProcessHostImpl::~RenderProcessHostImpl() {
523 #ifndef NDEBUG
524 DCHECK(is_self_deleted_)
525 << "RenderProcessHostImpl is destroyed by something other than itself";
526 #endif
528 // Make sure to clean up the in-process renderer before the channel, otherwise
529 // it may still run and have its IPCs fail, causing asserts.
530 in_process_renderer_.reset();
532 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
534 if (gpu_observer_registered_) {
535 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
536 gpu_observer_registered_ = false;
539 // We may have some unsent messages at this point, but that's OK.
540 channel_.reset();
541 while (!queued_messages_.empty()) {
542 delete queued_messages_.front();
543 queued_messages_.pop();
546 UnregisterHost(GetID());
548 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
549 switches::kDisableGpuShaderDiskCache)) {
550 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
551 base::Bind(&RemoveShaderInfo, GetID()));
555 void RenderProcessHostImpl::EnableSendQueue() {
556 is_initialized_ = false;
559 bool RenderProcessHostImpl::Init() {
560 // calling Init() more than once does nothing, this makes it more convenient
561 // for the view host which may not be sure in some cases
562 if (channel_)
563 return true;
565 base::CommandLine::StringType renderer_prefix;
566 #if defined(OS_POSIX)
567 // A command prefix is something prepended to the command line of the spawned
568 // process. It is supported only on POSIX systems.
569 const base::CommandLine& browser_command_line =
570 *base::CommandLine::ForCurrentProcess();
571 renderer_prefix =
572 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
573 #endif // defined(OS_POSIX)
575 #if defined(OS_LINUX)
576 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
577 ChildProcessHost::CHILD_NORMAL;
578 #else
579 int flags = ChildProcessHost::CHILD_NORMAL;
580 #endif
582 // Find the renderer before creating the channel so if this fails early we
583 // return without creating the channel.
584 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
585 if (renderer_path.empty())
586 return false;
588 // Setup the IPC channel.
589 const std::string channel_id =
590 IPC::Channel::GenerateVerifiedChannelID(std::string());
591 channel_ = CreateChannelProxy(channel_id);
593 // Setup the Mojo channel.
594 mojo_application_host_->Init();
596 // Call the embedder first so that their IPC filters have priority.
597 GetContentClient()->browser()->RenderProcessWillLaunch(this);
599 CreateMessageFilters();
600 RegisterMojoServices();
602 if (run_renderer_in_process()) {
603 DCHECK(g_renderer_main_thread_factory);
604 // Crank up a thread and run the initialization there. With the way that
605 // messages flow between the browser and renderer, this thread is required
606 // to prevent a deadlock in single-process mode. Since the primordial
607 // thread in the renderer process runs the WebKit code and can sometimes
608 // make blocking calls to the UI thread (i.e. this thread), they need to run
609 // on separate threads.
610 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
612 base::Thread::Options options;
613 #if defined(OS_WIN) && !defined(OS_MACOSX)
614 // In-process plugins require this to be a UI message loop.
615 options.message_loop_type = base::MessageLoop::TYPE_UI;
616 #else
617 // We can't have multiple UI loops on Linux and Android, so we don't support
618 // in-process plugins.
619 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
620 #endif
621 in_process_renderer_->StartWithOptions(options);
623 g_in_process_thread = in_process_renderer_->message_loop();
625 OnProcessLaunched(); // Fake a callback that the process is ready.
626 } else {
627 // Build command line for renderer. We call AppendRendererCommandLine()
628 // first so the process type argument will appear first.
629 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
630 if (!renderer_prefix.empty())
631 cmd_line->PrependWrapper(renderer_prefix);
632 AppendRendererCommandLine(cmd_line);
633 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
635 // Spawn the child process asynchronously to avoid blocking the UI thread.
636 // As long as there's no renderer prefix, we can use the zygote process
637 // at this stage.
638 child_process_launcher_.reset(new ChildProcessLauncher(
639 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
640 cmd_line,
641 GetID(),
642 this));
644 fast_shutdown_started_ = false;
647 if (!gpu_observer_registered_) {
648 gpu_observer_registered_ = true;
649 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
652 power_monitor_broadcaster_.Init();
654 is_initialized_ = true;
655 init_time_ = base::TimeTicks::Now();
656 return true;
659 bool RenderProcessHostImpl::ShouldUseMojoChannel() const {
660 const base::CommandLine& command_line =
661 *base::CommandLine::ForCurrentProcess();
662 return command_line.HasSwitch(switches::kEnableRendererMojoChannel) ||
663 IPC::ChannelMojo::ShouldBeUsed();
666 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
667 const std::string& channel_id) {
668 scoped_refptr<base::SingleThreadTaskRunner> runner =
669 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
670 if (ShouldUseMojoChannel()) {
671 VLOG(1) << "Mojo Channel is enabled on host";
672 if (!channel_mojo_host_) {
673 channel_mojo_host_.reset(new IPC::ChannelMojoHost(
674 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
677 return IPC::ChannelProxy::Create(
678 IPC::ChannelMojo::CreateServerFactory(
679 channel_mojo_host_->channel_delegate(), channel_id),
680 this,
681 runner.get());
684 return IPC::ChannelProxy::Create(
685 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
688 void RenderProcessHostImpl::CreateMessageFilters() {
689 DCHECK_CURRENTLY_ON(BrowserThread::UI);
690 const base::CommandLine& browser_command_line =
691 *base::CommandLine::ForCurrentProcess();
692 AddFilter(new ResourceSchedulerFilter(GetID()));
693 MediaInternals* media_internals = MediaInternals::GetInstance();
694 media::AudioManager* audio_manager =
695 BrowserMainLoop::GetInstance()->audio_manager();
696 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
697 // from guests.
698 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
699 new BrowserPluginMessageFilter(GetID()));
700 AddFilter(bp_message_filter.get());
702 scoped_refptr<RenderMessageFilter> render_message_filter(
703 new RenderMessageFilter(
704 GetID(),
705 #if defined(ENABLE_PLUGINS)
706 PluginServiceImpl::GetInstance(),
707 #else
708 NULL,
709 #endif
710 GetBrowserContext(),
711 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
712 widget_helper_.get(),
713 audio_manager,
714 media_internals,
715 storage_partition_impl_->GetDOMStorageContext()));
716 AddFilter(render_message_filter.get());
717 AddFilter(
718 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
719 BrowserContext* browser_context = GetBrowserContext();
720 ResourceContext* resource_context = browser_context->GetResourceContext();
722 scoped_refptr<net::URLRequestContextGetter> request_context(
723 browser_context->GetRequestContextForRenderProcess(GetID()));
724 scoped_refptr<net::URLRequestContextGetter> media_request_context(
725 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
727 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
728 base::Bind(&GetContexts, browser_context->GetResourceContext(),
729 request_context, media_request_context));
731 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
732 GetID(), PROCESS_TYPE_RENDERER,
733 storage_partition_impl_->GetAppCacheService(),
734 ChromeBlobStorageContext::GetFor(browser_context),
735 storage_partition_impl_->GetFileSystemContext(),
736 storage_partition_impl_->GetServiceWorkerContext(),
737 storage_partition_impl_->GetHostZoomLevelContext(),
738 get_contexts_callback);
740 AddFilter(resource_message_filter);
741 MediaStreamManager* media_stream_manager =
742 BrowserMainLoop::GetInstance()->media_stream_manager();
743 AddFilter(new AudioInputRendererHost(
744 audio_manager,
745 media_stream_manager,
746 AudioMirroringManager::GetInstance(),
747 BrowserMainLoop::GetInstance()->user_input_monitor()));
748 // The AudioRendererHost needs to be available for lookup, so it's
749 // stashed in a member variable.
750 audio_renderer_host_ = new AudioRendererHost(
751 GetID(),
752 audio_manager,
753 AudioMirroringManager::GetInstance(),
754 media_internals,
755 media_stream_manager);
756 AddFilter(audio_renderer_host_.get());
757 AddFilter(
758 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
759 AddFilter(new VideoCaptureHost(media_stream_manager));
760 AddFilter(new AppCacheDispatcherHost(
761 storage_partition_impl_->GetAppCacheService(),
762 GetID()));
763 AddFilter(new ClipboardMessageFilter);
764 AddFilter(new DOMStorageMessageFilter(
765 GetID(),
766 storage_partition_impl_->GetDOMStorageContext()));
767 AddFilter(new IndexedDBDispatcherHost(
768 GetID(),
769 storage_partition_impl_->GetURLRequestContext(),
770 storage_partition_impl_->GetIndexedDBContext(),
771 ChromeBlobStorageContext::GetFor(browser_context)));
773 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
774 AddFilter(gpu_message_filter_);
775 #if defined(ENABLE_WEBRTC)
776 AddFilter(new WebRTCIdentityServiceHost(
777 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
778 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
779 AddFilter(peer_connection_tracker_host_.get());
780 AddFilter(new MediaStreamDispatcherHost(
781 GetID(),
782 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
783 media_stream_manager));
784 AddFilter(new MediaStreamTrackMetricsHost());
785 #endif
786 #if defined(ENABLE_PLUGINS)
787 AddFilter(new PepperRendererConnection(GetID()));
788 #endif
789 AddFilter(new SpeechRecognitionDispatcherHost(
790 GetID(), storage_partition_impl_->GetURLRequestContext()));
791 AddFilter(new FileAPIMessageFilter(
792 GetID(),
793 storage_partition_impl_->GetURLRequestContext(),
794 storage_partition_impl_->GetFileSystemContext(),
795 ChromeBlobStorageContext::GetFor(browser_context),
796 StreamContext::GetFor(browser_context)));
797 AddFilter(new FileUtilitiesMessageFilter(GetID()));
798 AddFilter(new MimeRegistryMessageFilter());
799 AddFilter(new DatabaseMessageFilter(
800 storage_partition_impl_->GetDatabaseTracker()));
801 #if defined(OS_MACOSX)
802 AddFilter(new TextInputClientMessageFilter(GetID()));
803 #elif defined(OS_WIN)
804 // The FontCacheDispatcher is required only when we're using GDI rendering.
805 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
806 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
807 // should eventually be if (!ShouldUseDirectWrite()) guarded.
808 channel_->AddFilter(new FontCacheDispatcher());
809 #elif defined(OS_ANDROID)
810 browser_demuxer_android_ = new BrowserDemuxerAndroid();
811 AddFilter(browser_demuxer_android_.get());
812 #endif
813 #if defined(ENABLE_BROWSER_CDMS)
814 browser_cdm_manager_ = new BrowserCdmManager(GetID(), NULL);
815 AddFilter(browser_cdm_manager_.get());
816 #endif
818 WebSocketDispatcherHost::GetRequestContextCallback
819 websocket_request_context_callback(
820 base::Bind(&GetRequestContext, request_context,
821 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
823 AddFilter(
824 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
826 message_port_message_filter_ = new MessagePortMessageFilter(
827 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
828 base::Unretained(widget_helper_.get())));
829 AddFilter(message_port_message_filter_.get());
831 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
832 new ServiceWorkerDispatcherHost(
833 GetID(), message_port_message_filter_.get(), resource_context);
834 service_worker_filter->Init(
835 storage_partition_impl_->GetServiceWorkerContext());
836 AddFilter(service_worker_filter.get());
838 AddFilter(new SharedWorkerMessageFilter(
839 GetID(),
840 resource_context,
841 WorkerStoragePartition(
842 storage_partition_impl_->GetURLRequestContext(),
843 storage_partition_impl_->GetMediaURLRequestContext(),
844 storage_partition_impl_->GetAppCacheService(),
845 storage_partition_impl_->GetQuotaManager(),
846 storage_partition_impl_->GetFileSystemContext(),
847 storage_partition_impl_->GetDatabaseTracker(),
848 storage_partition_impl_->GetIndexedDBContext(),
849 storage_partition_impl_->GetServiceWorkerContext()),
850 message_port_message_filter_.get()));
852 #if defined(ENABLE_WEBRTC)
853 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
854 resource_context,
855 browser_context->GetRequestContextForRenderProcess(GetID()));
856 AddFilter(p2p_socket_dispatcher_host_.get());
857 #endif
859 AddFilter(new TraceMessageFilter());
860 AddFilter(new ResolveProxyMsgHelper(
861 browser_context->GetRequestContextForRenderProcess(GetID())));
862 AddFilter(new QuotaDispatcherHost(
863 GetID(),
864 storage_partition_impl_->GetQuotaManager(),
865 GetContentClient()->browser()->CreateQuotaPermissionContext()));
867 notification_message_filter_ = new NotificationMessageFilter(
868 GetID(),
869 resource_context,
870 browser_context);
871 AddFilter(notification_message_filter_.get());
873 AddFilter(new GamepadBrowserMessageFilter());
874 AddFilter(new DeviceLightMessageFilter());
875 AddFilter(new DeviceMotionMessageFilter());
876 AddFilter(new DeviceOrientationMessageFilter());
877 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
878 AddFilter(new HistogramMessageFilter());
879 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
880 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
881 AddFilter(new MemoryBenchmarkMessageFilter());
882 #endif
883 AddFilter(new PushMessagingMessageFilter(
884 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
885 #if defined(OS_ANDROID)
886 AddFilter(new ScreenOrientationMessageFilterAndroid());
887 #endif
888 AddFilter(new GeofencingDispatcherHost(
889 storage_partition_impl_->GetGeofencingManager()));
890 AddFilter(new NavigatorConnectDispatcherHost(
891 storage_partition_impl_->GetServiceWorkerContext()));
892 if (browser_command_line.HasSwitch(
893 switches::kEnableExperimentalWebPlatformFeatures))
894 AddFilter(new BluetoothDispatcherHost());
897 void RenderProcessHostImpl::RegisterMojoServices() {
898 mojo_application_host_->service_registry()->AddService(
899 base::Bind(&device::BatteryMonitorImpl::Create));
901 mojo_application_host_->service_registry()->AddService(
902 base::Bind(&device::VibrationManagerImpl::Create));
904 mojo_application_host_->service_registry()->AddService(
905 base::Bind(&PermissionServiceContext::CreateService,
906 base::Unretained(permission_service_context_.get())));
908 #if defined(OS_ANDROID)
909 ServiceRegistrarAndroid::RegisterProcessHostServices(
910 mojo_application_host_->service_registry_android());
911 #endif
913 GetContentClient()->browser()->OverrideRenderProcessMojoServices(
914 mojo_application_host_->service_registry());
917 int RenderProcessHostImpl::GetNextRoutingID() {
918 return widget_helper_->GetNextRoutingID();
921 void RenderProcessHostImpl::ResumeDeferredNavigation(
922 const GlobalRequestID& request_id) {
923 widget_helper_->ResumeDeferredNavigation(request_id);
926 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
927 const GlobalRequestID& request_id) {
928 widget_helper_->ResumeResponseDeferredAtStart(request_id);
931 void RenderProcessHostImpl::NotifyTimezoneChange() {
932 Send(new ViewMsg_TimezoneChange());
935 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
936 DCHECK(mojo_application_host_);
937 return mojo_application_host_->service_registry();
940 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
941 const {
942 return init_time_;
945 bool RenderProcessHostImpl::SubscribeUniformEnabled() const {
946 return subscribe_uniform_enabled_;
949 void RenderProcessHostImpl::OnAddSubscription(unsigned int target) {
950 DCHECK(subscribe_uniform_enabled_);
951 subscription_set_.insert(target);
952 const gpu::ValueState* state = pending_valuebuffer_state_->GetState(target);
953 if (state) {
954 SendUpdateValueState(target, *state);
958 void RenderProcessHostImpl::OnRemoveSubscription(unsigned int target) {
959 DCHECK(subscribe_uniform_enabled_);
960 subscription_set_.erase(target);
963 void RenderProcessHostImpl::SendUpdateValueState(unsigned int target,
964 const gpu::ValueState& state) {
965 DCHECK(subscribe_uniform_enabled_);
966 if (subscription_set_.find(target) != subscription_set_.end()) {
967 GpuProcessHost::SendOnIO(
968 GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
969 CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
970 new GpuMsg_UpdateValueState(id_, target, state));
971 } else {
972 // Store the ValueState locally in case a Valuebuffer subscribes to it later
973 pending_valuebuffer_state_->UpdateState(target, state);
977 void RenderProcessHostImpl::AddRoute(
978 int32 routing_id,
979 IPC::Listener* listener) {
980 CHECK(!listeners_.Lookup(routing_id))
981 << "Found Routing ID Conflict: " << routing_id;
982 listeners_.AddWithID(listener, routing_id);
985 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
986 DCHECK(listeners_.Lookup(routing_id) != NULL);
987 listeners_.Remove(routing_id);
989 #if defined(OS_WIN)
990 // Dump the handle table if handle auditing is enabled.
991 const base::CommandLine& browser_command_line =
992 *base::CommandLine::ForCurrentProcess();
993 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
994 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
995 DumpHandles();
997 // We wait to close the channels until the child process has finished
998 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
999 return;
1001 #endif
1002 // Keep the one renderer thread around forever in single process mode.
1003 if (!run_renderer_in_process())
1004 Cleanup();
1007 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
1008 observers_.AddObserver(observer);
1011 void RenderProcessHostImpl::RemoveObserver(
1012 RenderProcessHostObserver* observer) {
1013 observers_.RemoveObserver(observer);
1016 void RenderProcessHostImpl::ReceivedBadMessage() {
1017 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1018 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
1019 return;
1021 if (run_renderer_in_process()) {
1022 // In single process mode it is better if we don't suicide but just
1023 // crash.
1024 CHECK(false);
1026 // We kill the renderer but don't include a NOTREACHED, because we want the
1027 // browser to try to survive when it gets illegal messages from the renderer.
1028 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
1031 void RenderProcessHostImpl::WidgetRestored() {
1032 // Verify we were properly backgrounded.
1033 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1034 visible_widgets_++;
1035 SetBackgrounded(false);
1038 void RenderProcessHostImpl::WidgetHidden() {
1039 // On startup, the browser will call Hide
1040 if (backgrounded_)
1041 return;
1043 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
1044 visible_widgets_--;
1045 DCHECK_GE(visible_widgets_, 0);
1046 if (visible_widgets_ == 0) {
1047 DCHECK(!backgrounded_);
1048 SetBackgrounded(true);
1052 int RenderProcessHostImpl::VisibleWidgetCount() const {
1053 return visible_widgets_;
1056 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1057 return is_isolated_guest_;
1060 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1061 return storage_partition_impl_;
1064 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1065 if (IsPinchVirtualViewportEnabled())
1066 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
1068 if (IsDelegatedRendererEnabled())
1069 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1071 if (IsImplSidePaintingEnabled()) {
1072 command_line->AppendSwitch(switches::kEnableImplSidePainting);
1073 command_line->AppendSwitchASCII(
1074 switches::kNumRasterThreads,
1075 base::IntToString(NumberOfRendererRasterThreads()));
1078 if (IsGpuRasterizationEnabled())
1079 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1081 if (IsForceGpuRasterizationEnabled())
1082 command_line->AppendSwitch(switches::kForceGpuRasterization);
1084 if (BrowserGpuChannelHostFactory::IsGpuMemoryBufferFactoryUsageEnabled(
1085 gfx::GpuMemoryBuffer::MAP)) {
1086 std::vector<gfx::GpuMemoryBufferType> supported_types;
1087 GpuMemoryBufferFactory::GetSupportedTypes(&supported_types);
1088 DCHECK(!supported_types.empty());
1090 // The GPU service will always use the preferred type.
1091 gfx::GpuMemoryBufferType type = supported_types[0];
1093 switch (type) {
1094 case gfx::SURFACE_TEXTURE_BUFFER:
1095 // Surface texture backed GPU memory buffers require
1096 // TEXTURE_EXTERNAL_OES.
1097 command_line->AppendSwitchASCII(
1098 switches::kUseImageTextureTarget,
1099 gpu::gles2::GLES2Util::GetStringEnum(GL_TEXTURE_EXTERNAL_OES));
1100 break;
1101 case gfx::IO_SURFACE_BUFFER:
1102 // IOSurface backed images require GL_TEXTURE_RECTANGLE_ARB.
1103 command_line->AppendSwitchASCII(
1104 switches::kUseImageTextureTarget,
1105 gpu::gles2::GLES2Util::GetStringEnum(GL_TEXTURE_RECTANGLE_ARB));
1106 break;
1107 default:
1108 break;
1112 // Appending disable-gpu-feature switches due to software rendering list.
1113 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1114 DCHECK(gpu_data_manager);
1115 gpu_data_manager->AppendRendererCommandLine(command_line);
1118 void RenderProcessHostImpl::AppendRendererCommandLine(
1119 base::CommandLine* command_line) const {
1120 // Pass the process type first, so it shows first in process listings.
1121 command_line->AppendSwitchASCII(switches::kProcessType,
1122 switches::kRendererProcess);
1124 // Now send any options from our own command line we want to propagate.
1125 const base::CommandLine& browser_command_line =
1126 *base::CommandLine::ForCurrentProcess();
1127 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1129 // Pass on the browser locale.
1130 const std::string locale =
1131 GetContentClient()->browser()->GetApplicationLocale();
1132 command_line->AppendSwitchASCII(switches::kLang, locale);
1134 // If we run base::FieldTrials, we want to pass to their state to the
1135 // renderer so that it can act in accordance with each state, or record
1136 // histograms relating to the base::FieldTrial states.
1137 std::string field_trial_states;
1138 base::FieldTrialList::StatesToString(&field_trial_states);
1139 if (!field_trial_states.empty()) {
1140 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1141 field_trial_states);
1144 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1145 command_line, GetID());
1147 if (IsPinchToZoomEnabled())
1148 command_line->AppendSwitch(switches::kEnablePinch);
1150 #if defined(OS_WIN)
1151 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1152 base::DoubleToString(gfx::GetDPIScale()));
1153 command_line->AppendSwitchASCII(
1154 switches::kFontCacheSharedMemSuffix,
1155 base::UintToString(base::GetCurrentProcId()));
1156 #endif
1158 AppendCompositorCommandLineFlags(command_line);
1161 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1162 const base::CommandLine& browser_cmd,
1163 base::CommandLine* renderer_cmd) const {
1164 // Propagate the following switches to the renderer command line (along
1165 // with any associated values) if present in the browser command line.
1166 static const char* const kSwitchNames[] = {
1167 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1168 switches::kAllowLoopbackInPeerConnection,
1169 switches::kAudioBufferSize,
1170 switches::kAuditAllHandles,
1171 switches::kAuditHandles,
1172 switches::kBlinkPlatformLogChannels,
1173 switches::kBlockCrossSiteDocuments,
1174 switches::kDefaultTileWidth,
1175 switches::kDefaultTileHeight,
1176 switches::kDisable3DAPIs,
1177 switches::kDisableAcceleratedJpegDecoding,
1178 switches::kDisableAcceleratedVideoDecode,
1179 switches::kDisableApplicationCache,
1180 switches::kDisableBlinkScheduler,
1181 switches::kDisableBreakpad,
1182 switches::kDisablePreferCompositingToLCDText,
1183 switches::kDisableDatabases,
1184 switches::kDisableDirectNPAPIRequests,
1185 switches::kDisableDisplayList2dCanvas,
1186 switches::kDisableDistanceFieldText,
1187 switches::kDisableFileSystem,
1188 switches::kDisableGpuCompositing,
1189 switches::kDisableGpuVsync,
1190 switches::kDisableLowResTiling,
1191 switches::kDisableHistogramCustomizer,
1192 switches::kDisableLCDText,
1193 switches::kDisableLocalStorage,
1194 switches::kDisableLogging,
1195 switches::kDisableMediaSource,
1196 switches::kDisableOneCopy,
1197 switches::kDisableOverlayScrollbar,
1198 switches::kDisablePinch,
1199 switches::kDisablePrefixedEncryptedMedia,
1200 switches::kDisableSeccompFilterSandbox,
1201 switches::kDisableSessionStorage,
1202 switches::kDisableSharedWorkers,
1203 switches::kDisableSVG1DOM,
1204 switches::kDisableThreadedCompositing,
1205 switches::kDisableThreadedScrolling,
1206 switches::kDisableTouchAdjustment,
1207 switches::kDisableTouchDragDrop,
1208 switches::kDisableTouchEditing,
1209 switches::kDisableV8IdleNotificationAfterCommit,
1210 switches::kDomAutomationController,
1211 switches::kEnableBeginFrameScheduling,
1212 switches::kEnableBleedingEdgeRenderingFastPaths,
1213 switches::kEnableBrowserSideNavigation,
1214 switches::kEnablePreferCompositingToLCDText,
1215 switches::kEnableCredentialManagerAPI,
1216 switches::kEnableDeferredImageDecoding,
1217 switches::kEnableDisplayList2dCanvas,
1218 switches::kEnableDistanceFieldText,
1219 switches::kEnableEncryptedMedia,
1220 switches::kEnableExperimentalCanvasFeatures,
1221 switches::kEnableExperimentalWebPlatformFeatures,
1222 switches::kEnableGPUClientLogging,
1223 switches::kEnableGpuClientTracing,
1224 switches::kEnableGPUServiceLogging,
1225 switches::kEnableLinkDisambiguationPopup,
1226 switches::kEnableLowResTiling,
1227 switches::kEnableInbandTextTracks,
1228 switches::kEnableLCDText,
1229 switches::kEnableLogging,
1230 switches::kEnableMemoryBenchmarking,
1231 switches::kEnableNetworkInformation,
1232 switches::kEnableOneCopy,
1233 switches::kEnableOverlayFullscreenVideo,
1234 switches::kEnableOverlayScrollbar,
1235 switches::kEnablePinch,
1236 switches::kEnablePreciseMemoryInfo,
1237 switches::kEnableRendererMojoChannel,
1238 switches::kEnableSeccompFilterSandbox,
1239 switches::kEnableSkiaBenchmarking,
1240 switches::kEnableSlimmingPaint,
1241 switches::kEnableSmoothScrolling,
1242 switches::kEnableStatsTable,
1243 switches::kEnableStrictSiteIsolation,
1244 switches::kEnableThreadedCompositing,
1245 switches::kEnableTouchDragDrop,
1246 switches::kEnableTouchEditing,
1247 switches::kEnableV8IdleNotificationAfterCommit,
1248 switches::kEnableViewport,
1249 switches::kEnableViewportMeta,
1250 switches::kEnableVtune,
1251 switches::kEnableWebGLDraftExtensions,
1252 switches::kEnableWebGLImageChromium,
1253 switches::kEnableWebMIDI,
1254 switches::kEnableZeroCopy,
1255 switches::kForceDeviceScaleFactor,
1256 switches::kForceDisplayList2dCanvas,
1257 switches::kFullMemoryCrashReport,
1258 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
1259 switches::kIPCConnectionTimeout,
1260 switches::kJavaScriptFlags,
1261 switches::kLoggingLevel,
1262 switches::kMainFrameResizesAreOrientationChanges,
1263 switches::kMaxUntiledLayerWidth,
1264 switches::kMaxUntiledLayerHeight,
1265 switches::kMemoryMetrics,
1266 switches::kNoReferrers,
1267 switches::kNoSandbox,
1268 switches::kPpapiInProcess,
1269 switches::kProfilerTiming,
1270 switches::kReducedReferrerGranularity,
1271 switches::kReduceSecurityForTesting,
1272 switches::kRegisterPepperPlugins,
1273 switches::kRendererAssertTest,
1274 switches::kRendererStartupDialog,
1275 switches::kRootLayerScrolls,
1276 switches::kShowPaintRects,
1277 switches::kSitePerProcess,
1278 switches::kStatsCollectionController,
1279 switches::kTestType,
1280 switches::kTouchEvents,
1281 switches::kTraceToConsole,
1282 switches::kUseDiscardableMemory,
1283 // This flag needs to be propagated to the renderer process for
1284 // --in-process-webgl.
1285 switches::kUseGL,
1286 switches::kUseMobileUserAgent,
1287 switches::kUseNormalPriorityForTileTaskWorkerThreads,
1288 switches::kV,
1289 switches::kVideoThreads,
1290 switches::kVModule,
1291 // Please keep these in alphabetical order. Compositor switches here should
1292 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1293 cc::switches::kCompositeToMailbox,
1294 cc::switches::kDisableCompositedAntialiasing,
1295 cc::switches::kDisableMainFrameBeforeActivation,
1296 cc::switches::kDisableThreadedAnimation,
1297 cc::switches::kEnableGpuBenchmarking,
1298 cc::switches::kEnableMainFrameBeforeActivation,
1299 cc::switches::kEnableTopControlsPositionCalculation,
1300 cc::switches::kMaxTilesForInterestArea,
1301 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1302 cc::switches::kShowCompositedLayerBorders,
1303 cc::switches::kShowFPSCounter,
1304 cc::switches::kShowLayerAnimationBounds,
1305 cc::switches::kShowNonOccludingRects,
1306 cc::switches::kShowOccludingRects,
1307 cc::switches::kShowPropertyChangedRects,
1308 cc::switches::kShowReplicaScreenSpaceRects,
1309 cc::switches::kShowScreenSpaceRects,
1310 cc::switches::kShowSurfaceDamageRects,
1311 cc::switches::kSlowDownRasterScaleFactor,
1312 cc::switches::kStrictLayerPropertyChangeChecking,
1313 cc::switches::kTopControlsHideThreshold,
1314 cc::switches::kTopControlsShowThreshold,
1315 #if defined(ENABLE_PLUGINS)
1316 switches::kEnablePepperTesting,
1317 switches::kEnablePluginPowerSaver,
1318 #endif
1319 #if defined(ENABLE_WEBRTC)
1320 switches::kDisableWebRtcHWDecoding,
1321 switches::kDisableWebRtcHWEncoding,
1322 switches::kEnableWebRtcHWVp8Encoding,
1323 switches::kEnableWebRtcHWH264Encoding,
1324 switches::kWebRtcMaxCaptureFramerate,
1325 #endif
1326 switches::kEnableLowEndDeviceMode,
1327 switches::kDisableLowEndDeviceMode,
1328 #if defined(OS_ANDROID)
1329 switches::kDisableGestureRequirementForMediaPlayback,
1330 switches::kDisableWebRTC,
1331 switches::kEnableSpeechRecognition,
1332 switches::kMediaDrmEnableNonCompositing,
1333 switches::kNetworkCountryIso,
1334 switches::kDisableWebAudio,
1335 switches::kRendererWaitForJavaDebugger,
1336 #endif
1337 #if defined(OS_MACOSX)
1338 // Allow this to be set when invoking the browser and relayed along.
1339 switches::kEnableSandboxLogging,
1340 #endif
1341 #if defined(OS_MACOSX) && !defined(OS_IOS)
1342 switches::kEnableThreadedEventHandlingMac,
1343 #endif
1344 #if defined(OS_WIN)
1345 switches::kDisableDirectWrite,
1346 switches::kEnableWin32kRendererLockDown,
1347 switches::kDisableWin32kRendererLockDown,
1348 #endif
1349 #if defined(OS_CHROMEOS)
1350 switches::kDisableVaapiAcceleratedVideoEncode,
1351 #endif
1353 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1354 arraysize(kSwitchNames));
1356 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1357 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1358 // Pass kTraceStartup switch to renderer only if startup tracing has not
1359 // finished.
1360 renderer_cmd->AppendSwitchASCII(
1361 switches::kTraceStartup,
1362 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1365 // Disable databases in incognito mode.
1366 if (GetBrowserContext()->IsOffTheRecord() &&
1367 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1368 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1371 // Enforce the extra command line flags for impl-side painting.
1372 if (IsImplSidePaintingEnabled() &&
1373 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1374 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1376 // Add kWaitForDebugger to let renderer process wait for a debugger.
1377 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1378 // Look to pass-on the kWaitForDebugger flag.
1379 std::string value =
1380 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1381 if (value.empty() || value == switches::kRendererProcess) {
1382 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1387 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1388 if (run_renderer_in_process())
1389 return base::GetCurrentProcessHandle();
1391 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1392 return base::kNullProcessHandle;
1394 return child_process_launcher_->GetProcess().Handle();
1397 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1398 if (run_renderer_in_process())
1399 return false; // Single process mode never shuts down the renderer.
1401 #if defined(OS_ANDROID)
1402 // Android requires a different approach for killing.
1403 StopChildProcess(GetHandle());
1404 return true;
1405 #else
1406 return base::KillProcess(GetHandle(), exit_code, wait);
1407 #endif
1410 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1411 if (run_renderer_in_process())
1412 return false; // Single process mode never shuts down the renderer.
1414 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1415 return false;
1417 if (!child_process_launcher_.get() ||
1418 child_process_launcher_->IsStarting() ||
1419 !GetHandle())
1420 return false; // Render process hasn't started or is probably crashed.
1422 // Test if there's an unload listener.
1423 // NOTE: It's possible that an onunload listener may be installed
1424 // while we're shutting down, so there's a small race here. Given that
1425 // the window is small, it's unlikely that the web page has much
1426 // state that will be lost by not calling its unload handlers properly.
1427 if (!SuddenTerminationAllowed())
1428 return false;
1430 if (worker_ref_count_ != 0) {
1431 if (survive_for_worker_start_time_.is_null())
1432 survive_for_worker_start_time_ = base::TimeTicks::Now();
1433 return false;
1436 // Set this before ProcessDied() so observers can tell if the render process
1437 // died due to fast shutdown versus another cause.
1438 fast_shutdown_started_ = true;
1440 ProcessDied(false /* already_dead */);
1441 return true;
1444 void RenderProcessHostImpl::DumpHandles() {
1445 #if defined(OS_WIN)
1446 Send(new ChildProcessMsg_DumpHandles());
1447 #else
1448 NOTIMPLEMENTED();
1449 #endif
1452 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1453 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1454 if (!channel_) {
1455 if (!is_initialized_) {
1456 queued_messages_.push(msg);
1457 return true;
1458 } else {
1459 delete msg;
1460 return false;
1464 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1465 queued_messages_.push(msg);
1466 return true;
1469 return channel_->Send(msg);
1472 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1473 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1474 // we ignore incoming messages.
1476 if (deleting_soon_ || fast_shutdown_started_)
1477 return false;
1479 mark_child_process_activity_time();
1480 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1481 // Dispatch control messages.
1482 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1483 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1484 OnShutdownRequest)
1485 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1486 OnDumpHandlesDone)
1487 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1488 SuddenTerminationChanged)
1489 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1490 OnUserMetricsRecordAction)
1491 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1492 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1493 #if defined(ENABLE_WEBRTC)
1494 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1495 OnRegisterAecDumpConsumer)
1496 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1497 OnUnregisterAecDumpConsumer)
1498 #endif
1499 // Adding single handlers for your service here is fine, but once your
1500 // service needs more than one handler, please extract them into a new
1501 // message filter and add that filter to CreateMessageFilters().
1502 IPC_END_MESSAGE_MAP()
1504 return true;
1507 // Dispatch incoming messages to the appropriate IPC::Listener.
1508 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1509 if (!listener) {
1510 if (msg.is_sync()) {
1511 // The listener has gone away, so we must respond or else the caller will
1512 // hang waiting for a reply.
1513 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1514 reply->set_reply_error();
1515 Send(reply);
1517 return true;
1519 return listener->OnMessageReceived(msg);
1522 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1523 #if defined(IPC_MESSAGE_LOG_ENABLED)
1524 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1525 IPC::Logging::GetInstance()->Enabled()));
1526 #endif
1528 tracked_objects::ThreadData::Status status =
1529 tracked_objects::ThreadData::status();
1530 Send(new ChildProcessMsg_SetProfilerStatus(status));
1533 void RenderProcessHostImpl::OnChannelError() {
1534 ProcessDied(true /* already_dead */);
1537 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1538 // Message de-serialization failed. We consider this a capital crime. Kill the
1539 // renderer if we have one.
1540 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1541 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1542 PROCESS_TYPE_RENDERER);
1543 ReceivedBadMessage();
1546 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1547 return browser_context_;
1550 bool RenderProcessHostImpl::InSameStoragePartition(
1551 StoragePartition* partition) const {
1552 return storage_partition_impl_ == partition;
1555 int RenderProcessHostImpl::GetID() const {
1556 return id_;
1559 bool RenderProcessHostImpl::HasConnection() const {
1560 return channel_.get() != NULL;
1563 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1564 ignore_input_events_ = ignore_input_events;
1567 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1568 return ignore_input_events_;
1571 void RenderProcessHostImpl::Cleanup() {
1572 // If within_process_died_observer_ is true, one of our observers performed an
1573 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1574 // delay the destruction until all of the observer callbacks have been made,
1575 // and guarantee that the RenderProcessHostDestroyed observer callback is
1576 // always the last callback fired.
1577 if (within_process_died_observer_) {
1578 delayed_cleanup_needed_ = true;
1579 return;
1581 delayed_cleanup_needed_ = false;
1583 // Records the time when the process starts surviving for workers for UMA.
1584 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1585 survive_for_worker_start_time_.is_null()) {
1586 survive_for_worker_start_time_ = base::TimeTicks::Now();
1589 // When there are no other owners of this object, we can delete ourselves.
1590 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1591 if (!survive_for_worker_start_time_.is_null()) {
1592 UMA_HISTOGRAM_LONG_TIMES(
1593 "SharedWorker.RendererSurviveForWorkerTime",
1594 base::TimeTicks::Now() - survive_for_worker_start_time_);
1596 // We cannot clean up twice; if this fails, there is an issue with our
1597 // control flow.
1598 DCHECK(!deleting_soon_);
1600 DCHECK_EQ(0, pending_views_);
1601 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1602 observers_,
1603 RenderProcessHostDestroyed(this));
1604 NotificationService::current()->Notify(
1605 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1606 Source<RenderProcessHost>(this),
1607 NotificationService::NoDetails());
1609 #ifndef NDEBUG
1610 is_self_deleted_ = true;
1611 #endif
1612 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1613 deleting_soon_ = true;
1614 // It's important not to wait for the DeleteTask to delete the channel
1615 // proxy. Kill it off now. That way, in case the profile is going away, the
1616 // rest of the objects attached to this RenderProcessHost start going
1617 // away first, since deleting the channel proxy will post a
1618 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1619 channel_.reset();
1621 // The following members should be cleared in ProcessDied() as well!
1622 gpu_message_filter_ = NULL;
1623 message_port_message_filter_ = NULL;
1624 #if defined(ENABLE_BROWSER_CDMS)
1625 browser_cdm_manager_ = NULL;
1626 #endif
1628 RemoveUserData(kSessionStorageHolderKey);
1630 // Remove ourself from the list of renderer processes so that we can't be
1631 // reused in between now and when the Delete task runs.
1632 UnregisterHost(GetID());
1636 void RenderProcessHostImpl::AddPendingView() {
1637 pending_views_++;
1640 void RenderProcessHostImpl::RemovePendingView() {
1641 DCHECK(pending_views_);
1642 pending_views_--;
1645 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1646 sudden_termination_allowed_ = enabled;
1649 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1650 return sudden_termination_allowed_;
1653 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1654 return base::TimeTicks::Now() - child_process_activity_time_;
1657 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1658 widget_helper_->ResumeRequestsForView(route_id);
1661 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1662 FilterURL(this, empty_allowed, url);
1665 #if defined(ENABLE_WEBRTC)
1666 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1667 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1668 // Enable AEC dump for each registered consumer.
1669 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1670 it != aec_dump_consumers_.end(); ++it) {
1671 EnableAecDumpForId(file, *it);
1675 void RenderProcessHostImpl::DisableAecDump() {
1676 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1677 // Posting on the FILE thread and then replying back on the UI thread is only
1678 // for avoiding races between enable and disable. Nothing is done on the FILE
1679 // thread.
1680 BrowserThread::PostTaskAndReply(
1681 BrowserThread::FILE, FROM_HERE,
1682 base::Bind(&DisableAecDumpOnFileThread),
1683 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1684 weak_factory_.GetWeakPtr()));
1687 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1688 base::Callback<void(const std::string&)> callback) {
1689 webrtc_log_message_callback_ = callback;
1692 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1693 RenderProcessHostImpl::StartRtpDump(
1694 bool incoming,
1695 bool outgoing,
1696 const WebRtcRtpPacketCallback& packet_callback) {
1697 if (!p2p_socket_dispatcher_host_.get())
1698 return WebRtcStopRtpDumpCallback();
1700 BrowserThread::PostTask(BrowserThread::IO,
1701 FROM_HERE,
1702 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1703 p2p_socket_dispatcher_host_,
1704 incoming,
1705 outgoing,
1706 packet_callback));
1708 if (stop_rtp_dump_callback_.is_null()) {
1709 stop_rtp_dump_callback_ =
1710 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1711 p2p_socket_dispatcher_host_);
1713 return stop_rtp_dump_callback_;
1715 #endif
1717 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1718 return channel_.get();
1721 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1722 channel_->AddFilter(filter->GetFilter());
1725 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1726 if (static_cast<size_t>(GetActiveViewCount()) == count)
1727 return FastShutdownIfPossible();
1728 return false;
1731 bool RenderProcessHostImpl::FastShutdownStarted() const {
1732 return fast_shutdown_started_;
1735 // static
1736 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1737 g_all_hosts.Get().AddWithID(host, host_id);
1740 // static
1741 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1742 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1743 if (!host)
1744 return;
1746 g_all_hosts.Get().Remove(host_id);
1748 // Look up the map of site to process for the given browser_context,
1749 // in case we need to remove this process from it. It will be registered
1750 // under any sites it rendered that use process-per-site mode.
1751 SiteProcessMap* map =
1752 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1753 map->RemoveProcess(host);
1756 // static
1757 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1758 bool empty_allowed,
1759 GURL* url) {
1760 ChildProcessSecurityPolicyImpl* policy =
1761 ChildProcessSecurityPolicyImpl::GetInstance();
1763 if (empty_allowed && url->is_empty())
1764 return;
1766 // The browser process should never hear the swappedout:// URL from any
1767 // of the renderer's messages. Check for this in debug builds, but don't
1768 // let it crash a release browser.
1769 DCHECK(GURL(kSwappedOutURL) != *url);
1771 if (!url->is_valid()) {
1772 // Have to use about:blank for the denied case, instead of an empty GURL.
1773 // This is because the browser treats navigation to an empty GURL as a
1774 // navigation to the home page. This is often a privileged page
1775 // (chrome://newtab/) which is exactly what we don't want.
1776 *url = GURL(url::kAboutBlankURL);
1777 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1778 return;
1781 if (url->SchemeIs(url::kAboutScheme)) {
1782 // The renderer treats all URLs in the about: scheme as being about:blank.
1783 // Canonicalize about: URLs to about:blank.
1784 *url = GURL(url::kAboutBlankURL);
1785 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1788 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1789 // cannot swap processes or grant bindings.
1790 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1791 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1793 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1794 // If this renderer is not permitted to request this URL, we invalidate the
1795 // URL. This prevents us from storing the blocked URL and becoming confused
1796 // later.
1797 VLOG(1) << "Blocked URL " << url->spec();
1798 *url = GURL(url::kAboutBlankURL);
1799 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1803 // static
1804 bool RenderProcessHostImpl::IsSuitableHost(
1805 RenderProcessHost* host,
1806 BrowserContext* browser_context,
1807 const GURL& site_url) {
1808 if (run_renderer_in_process())
1809 return true;
1811 if (host->GetBrowserContext() != browser_context)
1812 return false;
1814 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1815 // and non-guest storage gets mixed. In the future, we might consider enabling
1816 // the sharing of guests, in this case this check should be removed and
1817 // InSameStoragePartition should handle the possible sharing.
1818 if (host->IsIsolatedGuest())
1819 return false;
1821 // Check whether the given host and the intended site_url will be using the
1822 // same StoragePartition, since a RenderProcessHost can only support a single
1823 // StoragePartition. This is relevant for packaged apps and isolated sites.
1824 StoragePartition* dest_partition =
1825 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1826 if (!host->InSameStoragePartition(dest_partition))
1827 return false;
1829 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1830 host->GetID()) !=
1831 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1832 browser_context, site_url)) {
1833 return false;
1836 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1839 // static
1840 bool RenderProcessHost::run_renderer_in_process() {
1841 return g_run_renderer_in_process_;
1844 // static
1845 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1846 g_run_renderer_in_process_ = value;
1848 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1849 if (value) {
1850 if (!command_line->HasSwitch(switches::kLang)) {
1851 // Modify the current process' command line to include the browser locale,
1852 // as the renderer expects this flag to be set.
1853 const std::string locale =
1854 GetContentClient()->browser()->GetApplicationLocale();
1855 command_line->AppendSwitchASCII(switches::kLang, locale);
1857 // TODO(piman): we should really send configuration through bools rather
1858 // than by parsing strings, i.e. sending an IPC rather than command line
1859 // args. crbug.com/314909
1860 AppendCompositorCommandLineFlags(command_line);
1864 // static
1865 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1866 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1867 return iterator(g_all_hosts.Pointer());
1870 // static
1871 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1872 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1873 return g_all_hosts.Get().Lookup(render_process_id);
1876 // static
1877 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1878 BrowserContext* browser_context, const GURL& url) {
1879 // Experimental:
1880 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1881 // try to reuse renderer processes when over the limit. (We could allow pages
1882 // from the same site to share, if we knew what the given process was
1883 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1884 // resource exhaustion issues if too many sites are open at once.
1885 const base::CommandLine& command_line =
1886 *base::CommandLine::ForCurrentProcess();
1887 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1888 command_line.HasSwitch(switches::kSitePerProcess))
1889 return false;
1891 if (run_renderer_in_process())
1892 return true;
1894 // NOTE: Sometimes it's necessary to create more render processes than
1895 // GetMaxRendererProcessCount(), for instance when we want to create
1896 // a renderer process for a browser context that has no existing
1897 // renderers. This is OK in moderation, since the
1898 // GetMaxRendererProcessCount() is conservative.
1899 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1900 return true;
1902 return GetContentClient()->browser()->
1903 ShouldTryToUseExistingProcessHost(browser_context, url);
1906 // static
1907 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1908 BrowserContext* browser_context,
1909 const GURL& site_url) {
1910 // First figure out which existing renderers we can use.
1911 std::vector<RenderProcessHost*> suitable_renderers;
1912 suitable_renderers.reserve(g_all_hosts.Get().size());
1914 iterator iter(AllHostsIterator());
1915 while (!iter.IsAtEnd()) {
1916 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1917 RenderProcessHostImpl::IsSuitableHost(
1918 iter.GetCurrentValue(),
1919 browser_context, site_url)) {
1920 suitable_renderers.push_back(iter.GetCurrentValue());
1922 iter.Advance();
1925 // Now pick a random suitable renderer, if we have any.
1926 if (!suitable_renderers.empty()) {
1927 int suitable_count = static_cast<int>(suitable_renderers.size());
1928 int random_index = base::RandInt(0, suitable_count - 1);
1929 return suitable_renderers[random_index];
1932 return NULL;
1935 // static
1936 bool RenderProcessHost::ShouldUseProcessPerSite(
1937 BrowserContext* browser_context,
1938 const GURL& url) {
1939 // Returns true if we should use the process-per-site model. This will be
1940 // the case if the --process-per-site switch is specified, or in
1941 // process-per-site-instance for particular sites (e.g., WebUI).
1942 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1943 const base::CommandLine& command_line =
1944 *base::CommandLine::ForCurrentProcess();
1945 if (command_line.HasSwitch(switches::kProcessPerSite))
1946 return true;
1948 // We want to consolidate particular sites like WebUI even when we are using
1949 // the process-per-tab or process-per-site-instance models.
1950 // Note: DevTools pages have WebUI type but should not reuse the same host.
1951 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1952 browser_context, url) &&
1953 !url.SchemeIs(kChromeDevToolsScheme)) {
1954 return true;
1957 // Otherwise let the content client decide, defaulting to false.
1958 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1959 url);
1962 // static
1963 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1964 BrowserContext* browser_context,
1965 const GURL& url) {
1966 // Look up the map of site to process for the given browser_context.
1967 SiteProcessMap* map =
1968 GetSiteProcessMapForBrowserContext(browser_context);
1970 // See if we have an existing process with appropriate bindings for this site.
1971 // If not, the caller should create a new process and register it.
1972 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1973 .possibly_invalid_spec();
1974 RenderProcessHost* host = map->FindProcess(site);
1975 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
1976 !IsSuitableHost(host, browser_context, url))) {
1977 // The registered process does not have an appropriate set of bindings for
1978 // the url. Remove it from the map so we can register a better one.
1979 RecordAction(
1980 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1981 map->RemoveProcess(host);
1982 host = NULL;
1985 return host;
1988 void RenderProcessHostImpl::RegisterProcessHostForSite(
1989 BrowserContext* browser_context,
1990 RenderProcessHost* process,
1991 const GURL& url) {
1992 // Look up the map of site to process for the given browser_context.
1993 SiteProcessMap* map =
1994 GetSiteProcessMapForBrowserContext(browser_context);
1996 // Only register valid, non-empty sites. Empty or invalid sites will not
1997 // use process-per-site mode. We cannot check whether the process has
1998 // appropriate bindings here, because the bindings have not yet been granted.
1999 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
2000 .possibly_invalid_spec();
2001 if (!site.empty())
2002 map->RegisterProcess(site, process);
2005 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
2006 // Our child process has died. If we didn't expect it, it's a crash.
2007 // In any case, we need to let everyone know it's gone.
2008 // The OnChannelError notification can fire multiple times due to nested sync
2009 // calls to a renderer. If we don't have a valid channel here it means we
2010 // already handled the error.
2012 // It should not be possible for us to be called re-entrantly.
2013 DCHECK(!within_process_died_observer_);
2015 // It should not be possible for a process death notification to come in while
2016 // we are dying.
2017 DCHECK(!deleting_soon_);
2019 // child_process_launcher_ can be NULL in single process mode or if fast
2020 // termination happened.
2021 int exit_code = 0;
2022 base::TerminationStatus status =
2023 child_process_launcher_.get() ?
2024 child_process_launcher_->GetChildTerminationStatus(already_dead,
2025 &exit_code) :
2026 base::TERMINATION_STATUS_NORMAL_TERMINATION;
2028 RendererClosedDetails details(status, exit_code);
2029 mojo_application_host_->WillDestroySoon();
2031 child_process_launcher_.reset();
2032 channel_.reset();
2034 within_process_died_observer_ = true;
2035 NotificationService::current()->Notify(
2036 NOTIFICATION_RENDERER_PROCESS_CLOSED,
2037 Source<RenderProcessHost>(this),
2038 Details<RendererClosedDetails>(&details));
2039 FOR_EACH_OBSERVER(RenderProcessHostObserver,
2040 observers_,
2041 RenderProcessExited(this, status, exit_code));
2042 within_process_died_observer_ = false;
2044 gpu_message_filter_ = NULL;
2045 message_port_message_filter_ = NULL;
2046 #if defined(ENABLE_BROWSER_CDMS)
2047 browser_cdm_manager_ = NULL;
2048 #endif
2049 RemoveUserData(kSessionStorageHolderKey);
2051 IDMap<IPC::Listener>::iterator iter(&listeners_);
2052 while (!iter.IsAtEnd()) {
2053 iter.GetCurrentValue()->OnMessageReceived(
2054 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2055 static_cast<int>(status),
2056 exit_code));
2057 iter.Advance();
2060 mojo_application_host_.reset(new MojoApplicationHost);
2062 // It's possible that one of the calls out to the observers might have caused
2063 // this object to be no longer needed.
2064 if (delayed_cleanup_needed_)
2065 Cleanup();
2067 // This object is not deleted at this point and might be reused later.
2068 // TODO(darin): clean this up
2071 int RenderProcessHostImpl::GetActiveViewCount() {
2072 int num_active_views = 0;
2073 scoped_ptr<RenderWidgetHostIterator> widgets(
2074 RenderWidgetHost::GetRenderWidgetHosts());
2075 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2076 // Count only RenderWidgetHosts in this process.
2077 if (widget->GetProcess()->GetID() == GetID())
2078 num_active_views++;
2080 return num_active_views;
2083 // Frame subscription API for this class is for accelerated composited path
2084 // only. These calls are redirected to GpuMessageFilter.
2085 void RenderProcessHostImpl::BeginFrameSubscription(
2086 int route_id,
2087 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2088 if (!gpu_message_filter_)
2089 return;
2090 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2091 &GpuMessageFilter::BeginFrameSubscription,
2092 gpu_message_filter_,
2093 route_id, base::Passed(&subscriber)));
2096 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2097 if (!gpu_message_filter_)
2098 return;
2099 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2100 &GpuMessageFilter::EndFrameSubscription,
2101 gpu_message_filter_,
2102 route_id));
2105 #if defined(ENABLE_WEBRTC)
2106 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2107 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2108 if (!webrtc_log_message_callback_.is_null())
2109 webrtc_log_message_callback_.Run(message);
2111 #endif
2113 void RenderProcessHostImpl::ReleaseOnCloseACK(
2114 RenderProcessHost* host,
2115 const SessionStorageNamespaceMap& sessions,
2116 int view_route_id) {
2117 DCHECK(host);
2118 if (sessions.empty())
2119 return;
2120 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2121 (host->GetUserData(kSessionStorageHolderKey));
2122 if (!holder) {
2123 holder = new SessionStorageHolder();
2124 host->SetUserData(
2125 kSessionStorageHolderKey,
2126 holder);
2128 holder->Hold(sessions, view_route_id);
2131 void RenderProcessHostImpl::OnShutdownRequest() {
2132 // Don't shut down if there are active RenderViews, or if there are pending
2133 // RenderViews being swapped back in.
2134 // In single process mode, we never shutdown the renderer.
2135 int num_active_views = GetActiveViewCount();
2136 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2137 return;
2139 // Notify any contents that might have swapped out renderers from this
2140 // process. They should not attempt to swap them back in.
2141 NotificationService::current()->Notify(
2142 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2143 Source<RenderProcessHost>(this),
2144 NotificationService::NoDetails());
2146 mojo_application_host_->WillDestroySoon();
2148 Send(new ChildProcessMsg_Shutdown());
2151 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2152 SetSuddenTerminationAllowed(enabled);
2155 void RenderProcessHostImpl::OnDumpHandlesDone() {
2156 Cleanup();
2159 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2160 // Note: we always set the backgrounded_ value. If the process is NULL
2161 // (and hence hasn't been created yet), we will set the process priority
2162 // later when we create the process.
2163 backgrounded_ = backgrounded;
2164 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2165 return;
2167 // Don't background processes which have active audio streams.
2168 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2169 return;
2171 #if defined(OS_WIN)
2172 // The cbstext.dll loads as a global GetMessage hook in the browser process
2173 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2174 // background thread. If the UI thread invokes this API just when it is
2175 // intercepted the stack is messed up on return from the interceptor
2176 // which causes random crashes in the browser process. Our hack for now
2177 // is to not invoke the SetPriorityClass API if the dll is loaded.
2178 if (GetModuleHandle(L"cbstext.dll"))
2179 return;
2180 #endif // OS_WIN
2182 // Notify the child process of background state.
2183 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2185 #if !defined(OS_WIN)
2186 // Backgrounding may require elevated privileges not available to renderer
2187 // processes, so control backgrounding from the process host.
2189 // Windows Vista+ has a fancy process backgrounding mode that can only be set
2190 // from within the process.
2191 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2192 #endif // !OS_WIN
2195 void RenderProcessHostImpl::OnProcessLaunched() {
2196 // No point doing anything, since this object will be destructed soon. We
2197 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2198 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2199 // properly cleanup.
2200 if (deleting_soon_)
2201 return;
2203 if (child_process_launcher_) {
2204 DCHECK(child_process_launcher_->GetProcess().IsValid());
2205 SetBackgrounded(backgrounded_);
2208 // NOTE: This needs to be before sending queued messages because
2209 // ExtensionService uses this notification to initialize the renderer process
2210 // with state that must be there before any JavaScript executes.
2212 // The queued messages contain such things as "navigate". If this notification
2213 // was after, we can end up executing JavaScript before the initialization
2214 // happens.
2215 NotificationService::current()->Notify(
2216 NOTIFICATION_RENDERER_PROCESS_CREATED,
2217 Source<RenderProcessHost>(this),
2218 NotificationService::NoDetails());
2220 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2221 // This way, Mojo can be safely used from the renderer in response to any
2222 // Chrome IPC message.
2223 mojo_application_host_->Activate(this, GetHandle());
2225 if (channel_mojo_host_)
2226 channel_mojo_host_->OnClientLaunched(GetHandle());
2228 while (!queued_messages_.empty()) {
2229 Send(queued_messages_.front());
2230 queued_messages_.pop();
2233 #if defined(ENABLE_WEBRTC)
2234 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2235 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2236 #endif
2239 scoped_refptr<AudioRendererHost>
2240 RenderProcessHostImpl::audio_renderer_host() const {
2241 return audio_renderer_host_;
2244 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2245 const std::string& action) {
2246 RecordComputedAction(action);
2249 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2250 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2251 (GetUserData(kSessionStorageHolderKey));
2252 if (!holder)
2253 return;
2254 holder->Release(old_route_id);
2257 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2258 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2261 void RenderProcessHostImpl::OnGpuSwitched() {
2262 // We are updating all widgets including swapped out ones.
2263 scoped_ptr<RenderWidgetHostIterator> widgets(
2264 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2265 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2266 if (!widget->IsRenderView())
2267 continue;
2269 // Skip widgets in other processes.
2270 if (widget->GetProcess()->GetID() != GetID())
2271 continue;
2273 RenderViewHost* rvh = RenderViewHost::From(widget);
2274 rvh->OnWebkitPreferencesChanged();
2278 #if defined(ENABLE_WEBRTC)
2279 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2280 BrowserThread::PostTask(
2281 BrowserThread::UI,
2282 FROM_HERE,
2283 base::Bind(
2284 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2285 weak_factory_.GetWeakPtr(),
2286 id));
2289 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2290 BrowserThread::PostTask(
2291 BrowserThread::UI,
2292 FROM_HERE,
2293 base::Bind(
2294 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2295 weak_factory_.GetWeakPtr(),
2296 id));
2299 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2300 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2301 aec_dump_consumers_.push_back(id);
2302 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2303 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2304 id);
2308 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2309 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2310 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2311 it != aec_dump_consumers_.end(); ++it) {
2312 if (*it == id) {
2313 aec_dump_consumers_.erase(it);
2314 break;
2319 #if defined(OS_WIN)
2320 #define IntToStringType base::IntToString16
2321 #else
2322 #define IntToStringType base::IntToString
2323 #endif
2325 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2326 int id) {
2327 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2328 base::FilePath unique_file =
2329 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2330 .AddExtension(IntToStringType(id));
2331 BrowserThread::PostTaskAndReplyWithResult(
2332 BrowserThread::FILE, FROM_HERE,
2333 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2334 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2335 weak_factory_.GetWeakPtr(),
2336 id));
2339 #undef IntToStringType
2341 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2342 int id,
2343 IPC::PlatformFileForTransit file_for_transit) {
2344 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2345 return;
2346 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2349 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2350 Send(new AecDumpMsg_DisableAecDump());
2352 #endif
2354 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2355 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2356 ++worker_ref_count_;
2359 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2360 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2361 DCHECK_GT(worker_ref_count_, 0);
2362 --worker_ref_count_;
2363 if (worker_ref_count_ == 0)
2364 Cleanup();
2367 } // namespace content