Implement HasPermission() method in PermissionService.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
bloba32b4d79b9cfc74de5b412a83ea4f11a682e15ba
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/notifications/notification_message_filter.h"
71 #include "content/browser/permissions/permission_service_context.h"
72 #include "content/browser/permissions/permission_service_impl.h"
73 #include "content/browser/profiler_message_filter.h"
74 #include "content/browser/push_messaging/push_messaging_message_filter.h"
75 #include "content/browser/quota_dispatcher_host.h"
76 #include "content/browser/renderer_host/clipboard_message_filter.h"
77 #include "content/browser/renderer_host/database_message_filter.h"
78 #include "content/browser/renderer_host/file_utilities_message_filter.h"
79 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
80 #include "content/browser/renderer_host/gpu_message_filter.h"
81 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
82 #include "content/browser/renderer_host/media/audio_renderer_host.h"
83 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
84 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
85 #include "content/browser/renderer_host/media/video_capture_host.h"
86 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
87 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
88 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
89 #include "content/browser/renderer_host/render_message_filter.h"
90 #include "content/browser/renderer_host/render_view_host_delegate.h"
91 #include "content/browser/renderer_host/render_view_host_impl.h"
92 #include "content/browser/renderer_host/render_widget_helper.h"
93 #include "content/browser/renderer_host/render_widget_host_impl.h"
94 #include "content/browser/renderer_host/text_input_client_message_filter.h"
95 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
96 #include "content/browser/resolve_proxy_msg_helper.h"
97 #include "content/browser/service_worker/service_worker_context_wrapper.h"
98 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
99 #include "content/browser/shared_worker/shared_worker_message_filter.h"
100 #include "content/browser/shared_worker/worker_storage_partition.h"
101 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
102 #include "content/browser/storage_partition_impl.h"
103 #include "content/browser/streams/stream_context.h"
104 #include "content/browser/tracing/trace_message_filter.h"
105 #include "content/browser/webui/web_ui_controller_factory_registry.h"
106 #include "content/common/child_process_host_impl.h"
107 #include "content/common/child_process_messages.h"
108 #include "content/common/content_switches_internal.h"
109 #include "content/common/gpu/gpu_memory_buffer_factory.h"
110 #include "content/common/gpu/gpu_messages.h"
111 #include "content/common/mojo/mojo_messages.h"
112 #include "content/common/resource_messages.h"
113 #include "content/common/view_messages.h"
114 #include "content/public/browser/browser_context.h"
115 #include "content/public/browser/content_browser_client.h"
116 #include "content/public/browser/notification_service.h"
117 #include "content/public/browser/notification_types.h"
118 #include "content/public/browser/render_process_host_factory.h"
119 #include "content/public/browser/render_process_host_observer.h"
120 #include "content/public/browser/render_widget_host.h"
121 #include "content/public/browser/render_widget_host_iterator.h"
122 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
123 #include "content/public/browser/resource_context.h"
124 #include "content/public/browser/user_metrics.h"
125 #include "content/public/browser/worker_service.h"
126 #include "content/public/common/content_constants.h"
127 #include "content/public/common/content_switches.h"
128 #include "content/public/common/process_type.h"
129 #include "content/public/common/resource_type.h"
130 #include "content/public/common/result_codes.h"
131 #include "content/public/common/sandboxed_process_launcher_delegate.h"
132 #include "content/public/common/url_constants.h"
133 #include "device/battery/battery_monitor_impl.h"
134 #include "device/vibration/vibration_manager_impl.h"
135 #include "gpu/GLES2/gl2extchromium.h"
136 #include "gpu/command_buffer/client/gpu_switches.h"
137 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
138 #include "gpu/command_buffer/service/gpu_switches.h"
139 #include "ipc/ipc_channel.h"
140 #include "ipc/ipc_logging.h"
141 #include "ipc/ipc_switches.h"
142 #include "ipc/mojo/ipc_channel_mojo.h"
143 #include "ipc/mojo/ipc_channel_mojo_host.h"
144 #include "media/base/media_switches.h"
145 #include "net/url_request/url_request_context_getter.h"
146 #include "ppapi/shared_impl/ppapi_switches.h"
147 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
148 #include "third_party/skia/include/core/SkBitmap.h"
149 #include "ui/base/ui_base_switches.h"
150 #include "ui/events/event_switches.h"
151 #include "ui/gfx/switches.h"
152 #include "ui/gl/gl_switches.h"
153 #include "ui/gl/gpu_switching_manager.h"
154 #include "ui/native_theme/native_theme_switches.h"
156 #if defined(OS_ANDROID)
157 #include "content/browser/android/child_process_launcher_android.h"
158 #include "content/browser/media/android/browser_demuxer_android.h"
159 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
160 #endif
162 #if defined(OS_WIN)
163 #include "base/win/scoped_com_initializer.h"
164 #include "content/common/font_cache_dispatcher_win.h"
165 #include "content/common/sandbox_win.h"
166 #include "ui/gfx/win/dpi.h"
167 #endif
169 #if defined(ENABLE_BROWSER_CDMS)
170 #include "content/browser/media/cdm/browser_cdm_manager.h"
171 #endif
173 #if defined(ENABLE_PLUGINS)
174 #include "content/browser/plugin_service_impl.h"
175 #endif
177 #if defined(ENABLE_WEBRTC)
178 #include "content/browser/media/webrtc_internals.h"
179 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
180 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
181 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
182 #include "content/common/media/aec_dump_messages.h"
183 #include "content/common/media/media_stream_messages.h"
184 #endif
186 extern bool g_exited_main_message_loop;
188 namespace content {
189 namespace {
191 const char kSiteProcessMapKeyName[] = "content_site_process_map";
193 void CacheShaderInfo(int32 id, base::FilePath path) {
194 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
197 void RemoveShaderInfo(int32 id) {
198 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
201 net::URLRequestContext* GetRequestContext(
202 scoped_refptr<net::URLRequestContextGetter> request_context,
203 scoped_refptr<net::URLRequestContextGetter> media_request_context,
204 ResourceType resource_type) {
205 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
206 // context specific to media for handling it because these resources have
207 // specific needs for caching.
208 if (resource_type == RESOURCE_TYPE_MEDIA)
209 return media_request_context->GetURLRequestContext();
210 return request_context->GetURLRequestContext();
213 void GetContexts(
214 ResourceContext* resource_context,
215 scoped_refptr<net::URLRequestContextGetter> request_context,
216 scoped_refptr<net::URLRequestContextGetter> media_request_context,
217 const ResourceHostMsg_Request& request,
218 ResourceContext** resource_context_out,
219 net::URLRequestContext** request_context_out) {
220 *resource_context_out = resource_context;
221 *request_context_out =
222 GetRequestContext(request_context, media_request_context,
223 request.resource_type);
226 #if defined(ENABLE_WEBRTC)
227 // Creates a file used for diagnostic echo canceller recordings for handing
228 // over to the renderer.
229 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
230 base::FilePath file_path,
231 base::ProcessHandle process) {
232 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
233 base::File dump_file(file_path,
234 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
235 if (!dump_file.IsValid()) {
236 VLOG(1) << "Could not open AEC dump file, error=" <<
237 dump_file.error_details();
238 return IPC::InvalidPlatformFileForTransit();
240 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
243 // Does nothing. Just to avoid races between enable and disable.
244 void DisableAecDumpOnFileThread() {
245 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
247 #endif
249 // the global list of all renderer processes
250 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
251 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
253 // Map of site to process, to ensure we only have one RenderProcessHost per
254 // site in process-per-site mode. Each map is specific to a BrowserContext.
255 class SiteProcessMap : public base::SupportsUserData::Data {
256 public:
257 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
258 SiteProcessMap() {}
260 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
261 map_[site] = process;
264 RenderProcessHost* FindProcess(const std::string& site) {
265 SiteToProcessMap::iterator i = map_.find(site);
266 if (i != map_.end())
267 return i->second;
268 return NULL;
271 void RemoveProcess(RenderProcessHost* host) {
272 // Find all instances of this process in the map, then separately remove
273 // them.
274 std::set<std::string> sites;
275 for (SiteToProcessMap::const_iterator i = map_.begin();
276 i != map_.end();
277 i++) {
278 if (i->second == host)
279 sites.insert(i->first);
281 for (std::set<std::string>::iterator i = sites.begin();
282 i != sites.end();
283 i++) {
284 SiteToProcessMap::iterator iter = map_.find(*i);
285 if (iter != map_.end()) {
286 DCHECK_EQ(iter->second, host);
287 map_.erase(iter);
292 private:
293 SiteToProcessMap map_;
296 // Find the SiteProcessMap specific to the given context.
297 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
298 DCHECK(context);
299 SiteProcessMap* map = static_cast<SiteProcessMap*>(
300 context->GetUserData(kSiteProcessMapKeyName));
301 if (!map) {
302 map = new SiteProcessMap();
303 context->SetUserData(kSiteProcessMapKeyName, map);
305 return map;
308 // NOTE: changes to this class need to be reviewed by the security team.
309 class RendererSandboxedProcessLauncherDelegate
310 : public SandboxedProcessLauncherDelegate {
311 public:
312 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
313 #if defined(OS_POSIX)
314 : ipc_fd_(channel->TakeClientFileDescriptor())
315 #endif // OS_POSIX
318 ~RendererSandboxedProcessLauncherDelegate() override {}
320 #if defined(OS_WIN)
321 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
322 bool* success) {
323 AddBaseHandleClosePolicy(policy);
324 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
327 #elif defined(OS_POSIX)
328 bool ShouldUseZygote() override {
329 const base::CommandLine& browser_command_line =
330 *base::CommandLine::ForCurrentProcess();
331 base::CommandLine::StringType renderer_prefix =
332 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
333 return renderer_prefix.empty();
335 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
336 #endif // OS_WIN
338 private:
339 #if defined(OS_POSIX)
340 base::ScopedFD ipc_fd_;
341 #endif // OS_POSIX
344 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
346 class SessionStorageHolder : public base::SupportsUserData::Data {
347 public:
348 SessionStorageHolder() {}
349 ~SessionStorageHolder() override {}
351 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
352 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
355 void Release(int old_route_id) {
356 session_storage_namespaces_awaiting_close_.erase(old_route_id);
359 private:
360 std::map<int, SessionStorageNamespaceMap >
361 session_storage_namespaces_awaiting_close_;
362 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
365 } // namespace
367 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
369 base::MessageLoop* g_in_process_thread;
371 base::MessageLoop*
372 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
373 return g_in_process_thread;
376 // Stores the maximum number of renderer processes the content module can
377 // create.
378 static size_t g_max_renderer_count_override = 0;
380 // static
381 size_t RenderProcessHost::GetMaxRendererProcessCount() {
382 if (g_max_renderer_count_override)
383 return g_max_renderer_count_override;
385 #if defined(OS_ANDROID)
386 // On Android we don't maintain a limit of renderer process hosts - we are
387 // happy with keeping a lot of these, as long as the number of live renderer
388 // processes remains reasonable, and on Android the OS takes care of that.
389 return std::numeric_limits<size_t>::max();
390 #endif
392 // On other platforms, we calculate the maximum number of renderer process
393 // hosts according to the amount of installed memory as reported by the OS.
394 // The calculation assumes that you want the renderers to use half of the
395 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
396 // this assumption, you need to adjust the ThirtyFourTabs test to match the
397 // expected number of processes.
399 // With the given amounts of installed memory below on a 32-bit CPU, the
400 // maximum renderer count will roughly be as follows:
402 // 128 MB -> 3
403 // 512 MB -> 6
404 // 1024 MB -> 12
405 // 4096 MB -> 51
406 // 16384 MB -> 82 (kMaxRendererProcessCount)
408 static size_t max_count = 0;
409 if (!max_count) {
410 const size_t kEstimatedWebContentsMemoryUsage =
411 #if defined(ARCH_CPU_64_BITS)
412 60; // In MB
413 #else
414 40; // In MB
415 #endif
416 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
417 max_count /= kEstimatedWebContentsMemoryUsage;
419 const size_t kMinRendererProcessCount = 3;
420 max_count = std::max(max_count, kMinRendererProcessCount);
421 max_count = std::min(max_count, kMaxRendererProcessCount);
423 return max_count;
426 // static
427 bool g_run_renderer_in_process_ = false;
429 // static
430 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
431 g_max_renderer_count_override = count;
434 RenderProcessHostImpl::RenderProcessHostImpl(
435 BrowserContext* browser_context,
436 StoragePartitionImpl* storage_partition_impl,
437 bool is_isolated_guest)
438 : fast_shutdown_started_(false),
439 deleting_soon_(false),
440 #ifndef NDEBUG
441 is_self_deleted_(false),
442 #endif
443 pending_views_(0),
444 mojo_application_host_(new MojoApplicationHost),
445 visible_widgets_(0),
446 backgrounded_(true),
447 is_initialized_(false),
448 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
449 browser_context_(browser_context),
450 storage_partition_impl_(storage_partition_impl),
451 sudden_termination_allowed_(true),
452 ignore_input_events_(false),
453 is_isolated_guest_(is_isolated_guest),
454 gpu_observer_registered_(false),
455 delayed_cleanup_needed_(false),
456 within_process_died_observer_(false),
457 power_monitor_broadcaster_(this),
458 worker_ref_count_(0),
459 permission_service_context_(new PermissionServiceContext(this)),
460 weak_factory_(this) {
461 widget_helper_ = new RenderWidgetHelper();
463 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
465 CHECK(!g_exited_main_message_loop);
466 RegisterHost(GetID(), this);
467 g_all_hosts.Get().set_check_on_null_data(true);
468 // Initialize |child_process_activity_time_| to a reasonable value.
469 mark_child_process_activity_time();
471 if (!GetBrowserContext()->IsOffTheRecord() &&
472 !base::CommandLine::ForCurrentProcess()->HasSwitch(
473 switches::kDisableGpuShaderDiskCache)) {
474 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
475 base::Bind(&CacheShaderInfo, GetID(),
476 storage_partition_impl_->GetPath()));
479 // Note: When we create the RenderProcessHostImpl, it's technically
480 // backgrounded, because it has no visible listeners. But the process
481 // doesn't actually exist yet, so we'll Background it later, after
482 // creation.
485 // static
486 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
487 DCHECK(g_run_renderer_in_process_);
489 switch (g_all_hosts.Pointer()->size()) {
490 case 0:
491 return;
492 case 1: {
493 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
494 AllHostsIterator().GetCurrentValue());
495 FOR_EACH_OBSERVER(RenderProcessHostObserver,
496 host->observers_,
497 RenderProcessHostDestroyed(host));
498 #ifndef NDEBUG
499 host->is_self_deleted_ = true;
500 #endif
501 delete host;
502 return;
504 default:
505 NOTREACHED() << "There should be only one RenderProcessHost when running "
506 << "in-process.";
510 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
511 RendererMainThreadFactoryFunction create) {
512 g_renderer_main_thread_factory = create;
515 RenderProcessHostImpl::~RenderProcessHostImpl() {
516 #ifndef NDEBUG
517 DCHECK(is_self_deleted_)
518 << "RenderProcessHostImpl is destroyed by something other than itself";
519 #endif
521 // Make sure to clean up the in-process renderer before the channel, otherwise
522 // it may still run and have its IPCs fail, causing asserts.
523 in_process_renderer_.reset();
525 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
527 if (gpu_observer_registered_) {
528 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
529 gpu_observer_registered_ = false;
532 // We may have some unsent messages at this point, but that's OK.
533 channel_.reset();
534 while (!queued_messages_.empty()) {
535 delete queued_messages_.front();
536 queued_messages_.pop();
539 UnregisterHost(GetID());
541 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
542 switches::kDisableGpuShaderDiskCache)) {
543 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
544 base::Bind(&RemoveShaderInfo, GetID()));
548 void RenderProcessHostImpl::EnableSendQueue() {
549 is_initialized_ = false;
552 bool RenderProcessHostImpl::Init() {
553 // calling Init() more than once does nothing, this makes it more convenient
554 // for the view host which may not be sure in some cases
555 if (channel_)
556 return true;
558 base::CommandLine::StringType renderer_prefix;
559 #if defined(OS_POSIX)
560 // A command prefix is something prepended to the command line of the spawned
561 // process. It is supported only on POSIX systems.
562 const base::CommandLine& browser_command_line =
563 *base::CommandLine::ForCurrentProcess();
564 renderer_prefix =
565 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
566 #endif // defined(OS_POSIX)
568 #if defined(OS_LINUX)
569 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
570 ChildProcessHost::CHILD_NORMAL;
571 #else
572 int flags = ChildProcessHost::CHILD_NORMAL;
573 #endif
575 // Find the renderer before creating the channel so if this fails early we
576 // return without creating the channel.
577 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
578 if (renderer_path.empty())
579 return false;
581 // Setup the IPC channel.
582 const std::string channel_id =
583 IPC::Channel::GenerateVerifiedChannelID(std::string());
584 channel_ = CreateChannelProxy(channel_id);
586 // Setup the Mojo channel.
587 mojo_application_host_->Init();
589 // Call the embedder first so that their IPC filters have priority.
590 GetContentClient()->browser()->RenderProcessWillLaunch(this);
592 CreateMessageFilters();
593 RegisterMojoServices();
595 if (run_renderer_in_process()) {
596 DCHECK(g_renderer_main_thread_factory);
597 // Crank up a thread and run the initialization there. With the way that
598 // messages flow between the browser and renderer, this thread is required
599 // to prevent a deadlock in single-process mode. Since the primordial
600 // thread in the renderer process runs the WebKit code and can sometimes
601 // make blocking calls to the UI thread (i.e. this thread), they need to run
602 // on separate threads.
603 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
605 base::Thread::Options options;
606 #if defined(OS_WIN) && !defined(OS_MACOSX)
607 // In-process plugins require this to be a UI message loop.
608 options.message_loop_type = base::MessageLoop::TYPE_UI;
609 #else
610 // We can't have multiple UI loops on Linux and Android, so we don't support
611 // in-process plugins.
612 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
613 #endif
614 in_process_renderer_->StartWithOptions(options);
616 g_in_process_thread = in_process_renderer_->message_loop();
618 OnProcessLaunched(); // Fake a callback that the process is ready.
619 } else {
620 // Build command line for renderer. We call AppendRendererCommandLine()
621 // first so the process type argument will appear first.
622 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
623 if (!renderer_prefix.empty())
624 cmd_line->PrependWrapper(renderer_prefix);
625 AppendRendererCommandLine(cmd_line);
626 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
628 // Spawn the child process asynchronously to avoid blocking the UI thread.
629 // As long as there's no renderer prefix, we can use the zygote process
630 // at this stage.
631 child_process_launcher_.reset(new ChildProcessLauncher(
632 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
633 cmd_line,
634 GetID(),
635 this));
637 fast_shutdown_started_ = false;
640 if (!gpu_observer_registered_) {
641 gpu_observer_registered_ = true;
642 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
645 power_monitor_broadcaster_.Init();
647 is_initialized_ = true;
648 init_time_ = base::TimeTicks::Now();
649 return true;
652 bool RenderProcessHostImpl::ShouldUseMojoChannel() const {
653 const base::CommandLine& command_line =
654 *base::CommandLine::ForCurrentProcess();
655 return command_line.HasSwitch(switches::kEnableRendererMojoChannel) ||
656 IPC::ChannelMojo::ShouldBeUsed();
659 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
660 const std::string& channel_id) {
661 scoped_refptr<base::SingleThreadTaskRunner> runner =
662 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
663 if (ShouldUseMojoChannel()) {
664 VLOG(1) << "Mojo Channel is enabled on host";
665 if (!channel_mojo_host_) {
666 channel_mojo_host_.reset(new IPC::ChannelMojoHost(
667 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
670 return IPC::ChannelProxy::Create(
671 IPC::ChannelMojo::CreateServerFactory(
672 channel_mojo_host_->channel_delegate(), channel_id),
673 this,
674 runner.get());
677 return IPC::ChannelProxy::Create(
678 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
681 void RenderProcessHostImpl::CreateMessageFilters() {
682 DCHECK_CURRENTLY_ON(BrowserThread::UI);
683 const base::CommandLine& browser_command_line =
684 *base::CommandLine::ForCurrentProcess();
685 AddFilter(new ResourceSchedulerFilter(GetID()));
686 MediaInternals* media_internals = MediaInternals::GetInstance();
687 media::AudioManager* audio_manager =
688 BrowserMainLoop::GetInstance()->audio_manager();
689 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
690 // from guests.
691 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
692 new BrowserPluginMessageFilter(GetID()));
693 AddFilter(bp_message_filter.get());
695 scoped_refptr<RenderMessageFilter> render_message_filter(
696 new RenderMessageFilter(
697 GetID(),
698 #if defined(ENABLE_PLUGINS)
699 PluginServiceImpl::GetInstance(),
700 #else
701 NULL,
702 #endif
703 GetBrowserContext(),
704 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
705 widget_helper_.get(),
706 audio_manager,
707 media_internals,
708 storage_partition_impl_->GetDOMStorageContext()));
709 AddFilter(render_message_filter.get());
710 AddFilter(
711 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
712 BrowserContext* browser_context = GetBrowserContext();
713 ResourceContext* resource_context = browser_context->GetResourceContext();
715 scoped_refptr<net::URLRequestContextGetter> request_context(
716 browser_context->GetRequestContextForRenderProcess(GetID()));
717 scoped_refptr<net::URLRequestContextGetter> media_request_context(
718 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
720 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
721 base::Bind(&GetContexts, browser_context->GetResourceContext(),
722 request_context, media_request_context));
724 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
725 GetID(), PROCESS_TYPE_RENDERER,
726 storage_partition_impl_->GetAppCacheService(),
727 ChromeBlobStorageContext::GetFor(browser_context),
728 storage_partition_impl_->GetFileSystemContext(),
729 storage_partition_impl_->GetServiceWorkerContext(),
730 storage_partition_impl_->GetHostZoomLevelContext(),
731 get_contexts_callback);
733 AddFilter(resource_message_filter);
734 MediaStreamManager* media_stream_manager =
735 BrowserMainLoop::GetInstance()->media_stream_manager();
736 AddFilter(new AudioInputRendererHost(
737 audio_manager,
738 media_stream_manager,
739 AudioMirroringManager::GetInstance(),
740 BrowserMainLoop::GetInstance()->user_input_monitor()));
741 // The AudioRendererHost needs to be available for lookup, so it's
742 // stashed in a member variable.
743 audio_renderer_host_ = new AudioRendererHost(
744 GetID(),
745 audio_manager,
746 AudioMirroringManager::GetInstance(),
747 media_internals,
748 media_stream_manager);
749 AddFilter(audio_renderer_host_.get());
750 AddFilter(
751 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
752 AddFilter(new VideoCaptureHost(media_stream_manager));
753 AddFilter(new AppCacheDispatcherHost(
754 storage_partition_impl_->GetAppCacheService(),
755 GetID()));
756 AddFilter(new ClipboardMessageFilter);
757 AddFilter(new DOMStorageMessageFilter(
758 GetID(),
759 storage_partition_impl_->GetDOMStorageContext()));
760 AddFilter(new IndexedDBDispatcherHost(
761 GetID(),
762 storage_partition_impl_->GetURLRequestContext(),
763 storage_partition_impl_->GetIndexedDBContext(),
764 ChromeBlobStorageContext::GetFor(browser_context)));
766 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
767 AddFilter(gpu_message_filter_);
768 #if defined(ENABLE_WEBRTC)
769 AddFilter(new WebRTCIdentityServiceHost(
770 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
771 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
772 AddFilter(peer_connection_tracker_host_.get());
773 AddFilter(new MediaStreamDispatcherHost(
774 GetID(),
775 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
776 media_stream_manager));
777 AddFilter(new MediaStreamTrackMetricsHost());
778 #endif
779 #if defined(ENABLE_PLUGINS)
780 AddFilter(new PepperRendererConnection(GetID()));
781 #endif
782 AddFilter(new SpeechRecognitionDispatcherHost(
783 GetID(), storage_partition_impl_->GetURLRequestContext()));
784 AddFilter(new FileAPIMessageFilter(
785 GetID(),
786 storage_partition_impl_->GetURLRequestContext(),
787 storage_partition_impl_->GetFileSystemContext(),
788 ChromeBlobStorageContext::GetFor(browser_context),
789 StreamContext::GetFor(browser_context)));
790 AddFilter(new FileUtilitiesMessageFilter(GetID()));
791 AddFilter(new MimeRegistryMessageFilter());
792 AddFilter(new DatabaseMessageFilter(
793 storage_partition_impl_->GetDatabaseTracker()));
794 #if defined(OS_MACOSX)
795 AddFilter(new TextInputClientMessageFilter(GetID()));
796 #elif defined(OS_WIN)
797 // The FontCacheDispatcher is required only when we're using GDI rendering.
798 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
799 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
800 // should eventually be if (!ShouldUseDirectWrite()) guarded.
801 channel_->AddFilter(new FontCacheDispatcher());
802 #elif defined(OS_ANDROID)
803 browser_demuxer_android_ = new BrowserDemuxerAndroid();
804 AddFilter(browser_demuxer_android_.get());
805 #endif
806 #if defined(ENABLE_BROWSER_CDMS)
807 browser_cdm_manager_ = new BrowserCdmManager(GetID(), NULL);
808 AddFilter(browser_cdm_manager_.get());
809 #endif
811 WebSocketDispatcherHost::GetRequestContextCallback
812 websocket_request_context_callback(
813 base::Bind(&GetRequestContext, request_context,
814 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
816 AddFilter(
817 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
819 message_port_message_filter_ = new MessagePortMessageFilter(
820 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
821 base::Unretained(widget_helper_.get())));
822 AddFilter(message_port_message_filter_.get());
824 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
825 new ServiceWorkerDispatcherHost(
826 GetID(), message_port_message_filter_.get(), resource_context);
827 service_worker_filter->Init(
828 storage_partition_impl_->GetServiceWorkerContext());
829 AddFilter(service_worker_filter.get());
831 AddFilter(new SharedWorkerMessageFilter(
832 GetID(),
833 resource_context,
834 WorkerStoragePartition(
835 storage_partition_impl_->GetURLRequestContext(),
836 storage_partition_impl_->GetMediaURLRequestContext(),
837 storage_partition_impl_->GetAppCacheService(),
838 storage_partition_impl_->GetQuotaManager(),
839 storage_partition_impl_->GetFileSystemContext(),
840 storage_partition_impl_->GetDatabaseTracker(),
841 storage_partition_impl_->GetIndexedDBContext(),
842 storage_partition_impl_->GetServiceWorkerContext()),
843 message_port_message_filter_.get()));
845 #if defined(ENABLE_WEBRTC)
846 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
847 resource_context,
848 browser_context->GetRequestContextForRenderProcess(GetID()));
849 AddFilter(p2p_socket_dispatcher_host_.get());
850 #endif
852 AddFilter(new TraceMessageFilter());
853 AddFilter(new ResolveProxyMsgHelper(
854 browser_context->GetRequestContextForRenderProcess(GetID())));
855 AddFilter(new QuotaDispatcherHost(
856 GetID(),
857 storage_partition_impl_->GetQuotaManager(),
858 GetContentClient()->browser()->CreateQuotaPermissionContext()));
860 notification_message_filter_ = new NotificationMessageFilter(
861 GetID(),
862 resource_context,
863 browser_context);
864 AddFilter(notification_message_filter_.get());
866 AddFilter(new GamepadBrowserMessageFilter());
867 AddFilter(new DeviceLightMessageFilter());
868 AddFilter(new DeviceMotionMessageFilter());
869 AddFilter(new DeviceOrientationMessageFilter());
870 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
871 AddFilter(new HistogramMessageFilter());
872 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
873 if (browser_command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
874 AddFilter(new MemoryBenchmarkMessageFilter());
875 #endif
876 AddFilter(new PushMessagingMessageFilter(
877 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
878 #if defined(OS_ANDROID)
879 AddFilter(new ScreenOrientationMessageFilterAndroid());
880 #endif
881 AddFilter(new GeofencingDispatcherHost(
882 storage_partition_impl_->GetGeofencingManager()));
883 if (browser_command_line.HasSwitch(
884 switches::kEnableExperimentalWebPlatformFeatures))
885 AddFilter(new BluetoothDispatcherHost());
888 void RenderProcessHostImpl::RegisterMojoServices() {
889 mojo_application_host_->service_registry()->AddService(
890 base::Bind(&device::BatteryMonitorImpl::Create));
892 mojo_application_host_->service_registry()->AddService(
893 base::Bind(&device::VibrationManagerImpl::Create));
895 mojo_application_host_->service_registry()->AddService(
896 base::Bind(&PermissionServiceContext::CreateService,
897 base::Unretained(permission_service_context_.get())));
899 GetContentClient()->browser()->OverrideRenderProcessMojoServices(
900 mojo_application_host_->service_registry());
903 int RenderProcessHostImpl::GetNextRoutingID() {
904 return widget_helper_->GetNextRoutingID();
907 void RenderProcessHostImpl::ResumeDeferredNavigation(
908 const GlobalRequestID& request_id) {
909 widget_helper_->ResumeDeferredNavigation(request_id);
912 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
913 const GlobalRequestID& request_id) {
914 widget_helper_->ResumeResponseDeferredAtStart(request_id);
917 void RenderProcessHostImpl::NotifyTimezoneChange() {
918 Send(new ViewMsg_TimezoneChange());
921 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
922 DCHECK(mojo_application_host_);
923 return mojo_application_host_->service_registry();
926 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
927 const {
928 return init_time_;
931 void RenderProcessHostImpl::AddRoute(
932 int32 routing_id,
933 IPC::Listener* listener) {
934 CHECK(!listeners_.Lookup(routing_id))
935 << "Found Routing ID Conflict: " << routing_id;
936 listeners_.AddWithID(listener, routing_id);
939 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
940 DCHECK(listeners_.Lookup(routing_id) != NULL);
941 listeners_.Remove(routing_id);
943 #if defined(OS_WIN)
944 // Dump the handle table if handle auditing is enabled.
945 const base::CommandLine& browser_command_line =
946 *base::CommandLine::ForCurrentProcess();
947 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
948 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
949 DumpHandles();
951 // We wait to close the channels until the child process has finished
952 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
953 return;
955 #endif
956 // Keep the one renderer thread around forever in single process mode.
957 if (!run_renderer_in_process())
958 Cleanup();
961 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
962 observers_.AddObserver(observer);
965 void RenderProcessHostImpl::RemoveObserver(
966 RenderProcessHostObserver* observer) {
967 observers_.RemoveObserver(observer);
970 void RenderProcessHostImpl::ReceivedBadMessage() {
971 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
972 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
973 return;
975 if (run_renderer_in_process()) {
976 // In single process mode it is better if we don't suicide but just
977 // crash.
978 CHECK(false);
980 // We kill the renderer but don't include a NOTREACHED, because we want the
981 // browser to try to survive when it gets illegal messages from the renderer.
982 Shutdown(RESULT_CODE_KILLED_BAD_MESSAGE, false);
985 void RenderProcessHostImpl::WidgetRestored() {
986 // Verify we were properly backgrounded.
987 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
988 visible_widgets_++;
989 SetBackgrounded(false);
992 void RenderProcessHostImpl::WidgetHidden() {
993 // On startup, the browser will call Hide
994 if (backgrounded_)
995 return;
997 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
998 visible_widgets_--;
999 DCHECK_GE(visible_widgets_, 0);
1000 if (visible_widgets_ == 0) {
1001 DCHECK(!backgrounded_);
1002 SetBackgrounded(true);
1006 int RenderProcessHostImpl::VisibleWidgetCount() const {
1007 return visible_widgets_;
1010 bool RenderProcessHostImpl::IsIsolatedGuest() const {
1011 return is_isolated_guest_;
1014 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
1015 return storage_partition_impl_;
1018 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
1019 if (IsPinchVirtualViewportEnabled())
1020 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
1022 if (IsDelegatedRendererEnabled())
1023 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1025 if (IsImplSidePaintingEnabled()) {
1026 command_line->AppendSwitch(switches::kEnableImplSidePainting);
1027 command_line->AppendSwitchASCII(
1028 switches::kNumRasterThreads,
1029 base::IntToString(NumberOfRendererRasterThreads()));
1032 if (IsGpuRasterizationEnabled())
1033 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1035 if (IsForceGpuRasterizationEnabled())
1036 command_line->AppendSwitch(switches::kForceGpuRasterization);
1038 if (BrowserGpuChannelHostFactory::IsGpuMemoryBufferFactoryUsageEnabled(
1039 gfx::GpuMemoryBuffer::MAP)) {
1040 std::vector<gfx::GpuMemoryBufferType> supported_types;
1041 GpuMemoryBufferFactory::GetSupportedTypes(&supported_types);
1042 DCHECK(!supported_types.empty());
1044 // The GPU service will always use the preferred type.
1045 gfx::GpuMemoryBufferType type = supported_types[0];
1047 switch (type) {
1048 case gfx::SURFACE_TEXTURE_BUFFER:
1049 // Surface texture backed GPU memory buffers require
1050 // TEXTURE_EXTERNAL_OES.
1051 command_line->AppendSwitchASCII(
1052 switches::kUseImageTextureTarget,
1053 gpu::gles2::GLES2Util::GetStringEnum(GL_TEXTURE_EXTERNAL_OES));
1054 break;
1055 case gfx::IO_SURFACE_BUFFER:
1056 // IOSurface backed images require GL_TEXTURE_RECTANGLE_ARB.
1057 command_line->AppendSwitchASCII(
1058 switches::kUseImageTextureTarget,
1059 gpu::gles2::GLES2Util::GetStringEnum(GL_TEXTURE_RECTANGLE_ARB));
1060 break;
1061 default:
1062 break;
1066 // Appending disable-gpu-feature switches due to software rendering list.
1067 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1068 DCHECK(gpu_data_manager);
1069 gpu_data_manager->AppendRendererCommandLine(command_line);
1072 void RenderProcessHostImpl::AppendRendererCommandLine(
1073 base::CommandLine* command_line) const {
1074 // Pass the process type first, so it shows first in process listings.
1075 command_line->AppendSwitchASCII(switches::kProcessType,
1076 switches::kRendererProcess);
1078 // Now send any options from our own command line we want to propagate.
1079 const base::CommandLine& browser_command_line =
1080 *base::CommandLine::ForCurrentProcess();
1081 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1083 // Pass on the browser locale.
1084 const std::string locale =
1085 GetContentClient()->browser()->GetApplicationLocale();
1086 command_line->AppendSwitchASCII(switches::kLang, locale);
1088 // If we run base::FieldTrials, we want to pass to their state to the
1089 // renderer so that it can act in accordance with each state, or record
1090 // histograms relating to the base::FieldTrial states.
1091 std::string field_trial_states;
1092 base::FieldTrialList::StatesToString(&field_trial_states);
1093 if (!field_trial_states.empty()) {
1094 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1095 field_trial_states);
1098 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1099 command_line, GetID());
1101 if (IsPinchToZoomEnabled())
1102 command_line->AppendSwitch(switches::kEnablePinch);
1104 #if defined(OS_WIN)
1105 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1106 base::DoubleToString(gfx::GetDPIScale()));
1107 command_line->AppendSwitchASCII(
1108 switches::kFontCacheSharedMemSuffix,
1109 base::UintToString(base::GetCurrentProcId()));
1110 #endif
1112 AppendCompositorCommandLineFlags(command_line);
1115 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1116 const base::CommandLine& browser_cmd,
1117 base::CommandLine* renderer_cmd) const {
1118 // Propagate the following switches to the renderer command line (along
1119 // with any associated values) if present in the browser command line.
1120 static const char* const kSwitchNames[] = {
1121 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1122 switches::kAllowLoopbackInPeerConnection,
1123 switches::kAudioBufferSize,
1124 switches::kAuditAllHandles,
1125 switches::kAuditHandles,
1126 switches::kBlinkPlatformLogChannels,
1127 switches::kBlockCrossSiteDocuments,
1128 switches::kDefaultTileWidth,
1129 switches::kDefaultTileHeight,
1130 switches::kDisable3DAPIs,
1131 switches::kDisableAcceleratedVideoDecode,
1132 switches::kDisableApplicationCache,
1133 switches::kDisableBlinkScheduler,
1134 switches::kDisableBreakpad,
1135 switches::kDisablePreferCompositingToLCDText,
1136 switches::kDisableCompositingForTransition,
1137 switches::kDisableDatabases,
1138 switches::kDisableDirectNPAPIRequests,
1139 switches::kDisableDisplayList2dCanvas,
1140 switches::kDisableDistanceFieldText,
1141 switches::kDisableFileSystem,
1142 switches::kDisableGpuCompositing,
1143 switches::kDisableGpuVsync,
1144 switches::kDisableLowResTiling,
1145 switches::kDisableHistogramCustomizer,
1146 switches::kDisableLCDText,
1147 switches::kDisableLayerSquashing,
1148 switches::kDisableLocalStorage,
1149 switches::kDisableLogging,
1150 switches::kDisableMediaSource,
1151 switches::kDisableOneCopy,
1152 switches::kDisableOverlayScrollbar,
1153 switches::kDisablePinch,
1154 switches::kDisablePrefixedEncryptedMedia,
1155 switches::kDisableSeccompFilterSandbox,
1156 switches::kDisableSessionStorage,
1157 switches::kDisableSharedWorkers,
1158 switches::kDisableSVG1DOM,
1159 switches::kDisableThreadedCompositing,
1160 switches::kDisableThreadedScrolling,
1161 switches::kDisableTouchAdjustment,
1162 switches::kDisableTouchDragDrop,
1163 switches::kDisableTouchEditing,
1164 switches::kDisableV8IdleNotificationAfterCommit,
1165 switches::kDomAutomationController,
1166 switches::kEnableAcceleratedJpegDecoding,
1167 switches::kEnableBeginFrameScheduling,
1168 switches::kEnableBleedingEdgeRenderingFastPaths,
1169 switches::kEnableBrowserSideNavigation,
1170 switches::kEnablePreferCompositingToLCDText,
1171 switches::kEnableCompositingForTransition,
1172 switches::kEnableCredentialManagerAPI,
1173 switches::kEnableDeferredImageDecoding,
1174 switches::kEnableDisplayList2dCanvas,
1175 switches::kEnableDistanceFieldText,
1176 switches::kEnableEncryptedMedia,
1177 switches::kEnableExperimentalCanvasFeatures,
1178 switches::kEnableExperimentalWebPlatformFeatures,
1179 switches::kEnableGPUClientLogging,
1180 switches::kEnableGpuClientTracing,
1181 switches::kEnableGPUServiceLogging,
1182 switches::kEnableLinkDisambiguationPopup,
1183 switches::kEnableLowResTiling,
1184 switches::kEnableInbandTextTracks,
1185 switches::kEnableLCDText,
1186 switches::kEnableLayerSquashing,
1187 switches::kEnableLogging,
1188 switches::kEnableMemoryBenchmarking,
1189 switches::kEnableNetworkInformation,
1190 switches::kEnableOneCopy,
1191 switches::kEnableOverlayFullscreenVideo,
1192 switches::kEnableOverlayScrollbar,
1193 switches::kEnablePinch,
1194 switches::kEnablePreciseMemoryInfo,
1195 switches::kEnableRendererMojoChannel,
1196 switches::kEnableSeccompFilterSandbox,
1197 switches::kEnableSkiaBenchmarking,
1198 switches::kEnableSlimmingPaint,
1199 switches::kEnableSmoothScrolling,
1200 switches::kEnableStatsTable,
1201 switches::kEnableStrictSiteIsolation,
1202 switches::kEnableThreadedCompositing,
1203 switches::kEnableTouchDragDrop,
1204 switches::kEnableTouchEditing,
1205 switches::kEnableV8IdleNotificationAfterCommit,
1206 switches::kEnableViewport,
1207 switches::kEnableViewportMeta,
1208 switches::kEnableVtune,
1209 switches::kEnableWebGLDraftExtensions,
1210 switches::kEnableWebGLImageChromium,
1211 switches::kEnableWebMIDI,
1212 switches::kEnableZeroCopy,
1213 switches::kForceDeviceScaleFactor,
1214 switches::kForceDisplayList2dCanvas,
1215 switches::kFullMemoryCrashReport,
1216 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
1217 switches::kIPCConnectionTimeout,
1218 switches::kJavaScriptFlags,
1219 switches::kLoggingLevel,
1220 switches::kMainFrameResizesAreOrientationChanges,
1221 switches::kMaxUntiledLayerWidth,
1222 switches::kMaxUntiledLayerHeight,
1223 switches::kMemoryMetrics,
1224 switches::kNoReferrers,
1225 switches::kNoSandbox,
1226 switches::kPpapiInProcess,
1227 switches::kProfilerTiming,
1228 switches::kReducedReferrerGranularity,
1229 switches::kReduceSecurityForTesting,
1230 switches::kRegisterPepperPlugins,
1231 switches::kRendererAssertTest,
1232 switches::kRendererStartupDialog,
1233 switches::kRootLayerScrolls,
1234 switches::kShowPaintRects,
1235 switches::kSitePerProcess,
1236 switches::kStatsCollectionController,
1237 switches::kTestType,
1238 switches::kTouchEvents,
1239 switches::kTraceToConsole,
1240 switches::kUseDiscardableMemory,
1241 // This flag needs to be propagated to the renderer process for
1242 // --in-process-webgl.
1243 switches::kUseGL,
1244 switches::kUseMobileUserAgent,
1245 switches::kV,
1246 switches::kVideoThreads,
1247 switches::kVModule,
1248 // Please keep these in alphabetical order. Compositor switches here should
1249 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1250 cc::switches::kCompositeToMailbox,
1251 cc::switches::kDisableCompositedAntialiasing,
1252 cc::switches::kDisableMainFrameBeforeActivation,
1253 cc::switches::kDisableThreadedAnimation,
1254 cc::switches::kEnableGpuBenchmarking,
1255 cc::switches::kEnableMainFrameBeforeActivation,
1256 cc::switches::kEnableTopControlsPositionCalculation,
1257 cc::switches::kMaxTilesForInterestArea,
1258 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1259 cc::switches::kShowCompositedLayerBorders,
1260 cc::switches::kShowFPSCounter,
1261 cc::switches::kShowLayerAnimationBounds,
1262 cc::switches::kShowNonOccludingRects,
1263 cc::switches::kShowOccludingRects,
1264 cc::switches::kShowPropertyChangedRects,
1265 cc::switches::kShowReplicaScreenSpaceRects,
1266 cc::switches::kShowScreenSpaceRects,
1267 cc::switches::kShowSurfaceDamageRects,
1268 cc::switches::kSlowDownRasterScaleFactor,
1269 cc::switches::kStrictLayerPropertyChangeChecking,
1270 cc::switches::kTopControlsHideThreshold,
1271 cc::switches::kTopControlsShowThreshold,
1272 #if defined(ENABLE_PLUGINS)
1273 switches::kEnablePepperTesting,
1274 switches::kEnablePluginPowerSaver,
1275 #endif
1276 #if defined(ENABLE_WEBRTC)
1277 switches::kDisableWebRtcHWDecoding,
1278 switches::kDisableWebRtcHWEncoding,
1279 switches::kEnableWebRtcHWVp8Encoding,
1280 switches::kEnableWebRtcHWH264Encoding,
1281 switches::kWebRtcMaxCaptureFramerate,
1282 #endif
1283 switches::kLowEndDeviceMode,
1284 #if defined(OS_ANDROID)
1285 switches::kDisableGestureRequirementForMediaPlayback,
1286 switches::kDisableWebRTC,
1287 switches::kEnableSpeechRecognition,
1288 switches::kMediaDrmEnableNonCompositing,
1289 switches::kNetworkCountryIso,
1290 switches::kDisableWebAudio,
1291 switches::kRendererWaitForJavaDebugger,
1292 #endif
1293 #if defined(OS_MACOSX)
1294 // Allow this to be set when invoking the browser and relayed along.
1295 switches::kEnableSandboxLogging,
1296 #endif
1297 #if defined(OS_MACOSX) && !defined(OS_IOS)
1298 switches::kEnableThreadedEventHandlingMac,
1299 #endif
1300 #if defined(OS_WIN)
1301 switches::kDisableDirectWrite,
1302 switches::kEnableWin32kRendererLockDown,
1303 #endif
1304 #if defined(OS_CHROMEOS)
1305 switches::kDisableVaapiAcceleratedVideoEncode,
1306 #endif
1308 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1309 arraysize(kSwitchNames));
1311 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1312 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1313 // Pass kTraceStartup switch to renderer only if startup tracing has not
1314 // finished.
1315 renderer_cmd->AppendSwitchASCII(
1316 switches::kTraceStartup,
1317 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1320 // Disable databases in incognito mode.
1321 if (GetBrowserContext()->IsOffTheRecord() &&
1322 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1323 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1326 // Enforce the extra command line flags for impl-side painting.
1327 if (IsImplSidePaintingEnabled() &&
1328 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1329 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1331 // Add kWaitForDebugger to let renderer process wait for a debugger.
1332 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1333 // Look to pass-on the kWaitForDebugger flag.
1334 std::string value =
1335 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1336 if (value.empty() || value == switches::kRendererProcess) {
1337 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1342 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1343 if (run_renderer_in_process())
1344 return base::GetCurrentProcessHandle();
1346 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1347 return base::kNullProcessHandle;
1349 return child_process_launcher_->GetProcess().Handle();
1352 bool RenderProcessHostImpl::Shutdown(int exit_code, bool wait) {
1353 if (run_renderer_in_process())
1354 return false; // Single process mode never shuts down the renderer.
1356 #if defined(OS_ANDROID)
1357 // Android requires a different approach for killing.
1358 StopChildProcess(GetHandle());
1359 return true;
1360 #else
1361 return base::KillProcess(GetHandle(), exit_code, wait);
1362 #endif
1365 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1366 if (run_renderer_in_process())
1367 return false; // Single process mode never shuts down the renderer.
1369 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1370 return false;
1372 if (!child_process_launcher_.get() ||
1373 child_process_launcher_->IsStarting() ||
1374 !GetHandle())
1375 return false; // Render process hasn't started or is probably crashed.
1377 // Test if there's an unload listener.
1378 // NOTE: It's possible that an onunload listener may be installed
1379 // while we're shutting down, so there's a small race here. Given that
1380 // the window is small, it's unlikely that the web page has much
1381 // state that will be lost by not calling its unload handlers properly.
1382 if (!SuddenTerminationAllowed())
1383 return false;
1385 if (worker_ref_count_ != 0) {
1386 if (survive_for_worker_start_time_.is_null())
1387 survive_for_worker_start_time_ = base::TimeTicks::Now();
1388 return false;
1391 // Set this before ProcessDied() so observers can tell if the render process
1392 // died due to fast shutdown versus another cause.
1393 fast_shutdown_started_ = true;
1395 ProcessDied(false /* already_dead */);
1396 return true;
1399 void RenderProcessHostImpl::DumpHandles() {
1400 #if defined(OS_WIN)
1401 Send(new ChildProcessMsg_DumpHandles());
1402 #else
1403 NOTIMPLEMENTED();
1404 #endif
1407 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1408 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1409 if (!channel_) {
1410 if (!is_initialized_) {
1411 queued_messages_.push(msg);
1412 return true;
1413 } else {
1414 delete msg;
1415 return false;
1419 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1420 queued_messages_.push(msg);
1421 return true;
1424 return channel_->Send(msg);
1427 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1428 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1429 // we ignore incoming messages.
1431 if (deleting_soon_ || fast_shutdown_started_)
1432 return false;
1434 mark_child_process_activity_time();
1435 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1436 // Dispatch control messages.
1437 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1438 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1439 OnShutdownRequest)
1440 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1441 OnDumpHandlesDone)
1442 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1443 SuddenTerminationChanged)
1444 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1445 OnUserMetricsRecordAction)
1446 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1447 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1448 #if defined(ENABLE_WEBRTC)
1449 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1450 OnRegisterAecDumpConsumer)
1451 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1452 OnUnregisterAecDumpConsumer)
1453 #endif
1454 // Adding single handlers for your service here is fine, but once your
1455 // service needs more than one handler, please extract them into a new
1456 // message filter and add that filter to CreateMessageFilters().
1457 IPC_END_MESSAGE_MAP()
1459 return true;
1462 // Dispatch incoming messages to the appropriate IPC::Listener.
1463 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1464 if (!listener) {
1465 if (msg.is_sync()) {
1466 // The listener has gone away, so we must respond or else the caller will
1467 // hang waiting for a reply.
1468 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1469 reply->set_reply_error();
1470 Send(reply);
1472 return true;
1474 return listener->OnMessageReceived(msg);
1477 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1478 #if defined(IPC_MESSAGE_LOG_ENABLED)
1479 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1480 IPC::Logging::GetInstance()->Enabled()));
1481 #endif
1483 tracked_objects::ThreadData::Status status =
1484 tracked_objects::ThreadData::status();
1485 Send(new ChildProcessMsg_SetProfilerStatus(status));
1488 void RenderProcessHostImpl::OnChannelError() {
1489 ProcessDied(true /* already_dead */);
1492 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1493 // Message de-serialization failed. We consider this a capital crime. Kill the
1494 // renderer if we have one.
1495 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1496 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1497 PROCESS_TYPE_RENDERER);
1498 ReceivedBadMessage();
1501 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1502 return browser_context_;
1505 bool RenderProcessHostImpl::InSameStoragePartition(
1506 StoragePartition* partition) const {
1507 return storage_partition_impl_ == partition;
1510 int RenderProcessHostImpl::GetID() const {
1511 return id_;
1514 bool RenderProcessHostImpl::HasConnection() const {
1515 return channel_.get() != NULL;
1518 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1519 ignore_input_events_ = ignore_input_events;
1522 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1523 return ignore_input_events_;
1526 void RenderProcessHostImpl::Cleanup() {
1527 // If within_process_died_observer_ is true, one of our observers performed an
1528 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1529 // delay the destruction until all of the observer callbacks have been made,
1530 // and guarantee that the RenderProcessHostDestroyed observer callback is
1531 // always the last callback fired.
1532 if (within_process_died_observer_) {
1533 delayed_cleanup_needed_ = true;
1534 return;
1536 delayed_cleanup_needed_ = false;
1538 // Records the time when the process starts surviving for workers for UMA.
1539 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1540 survive_for_worker_start_time_.is_null()) {
1541 survive_for_worker_start_time_ = base::TimeTicks::Now();
1544 // When there are no other owners of this object, we can delete ourselves.
1545 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1546 if (!survive_for_worker_start_time_.is_null()) {
1547 UMA_HISTOGRAM_LONG_TIMES(
1548 "SharedWorker.RendererSurviveForWorkerTime",
1549 base::TimeTicks::Now() - survive_for_worker_start_time_);
1551 // We cannot clean up twice; if this fails, there is an issue with our
1552 // control flow.
1553 DCHECK(!deleting_soon_);
1555 DCHECK_EQ(0, pending_views_);
1556 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1557 observers_,
1558 RenderProcessHostDestroyed(this));
1559 NotificationService::current()->Notify(
1560 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1561 Source<RenderProcessHost>(this),
1562 NotificationService::NoDetails());
1564 #ifndef NDEBUG
1565 is_self_deleted_ = true;
1566 #endif
1567 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1568 deleting_soon_ = true;
1569 // It's important not to wait for the DeleteTask to delete the channel
1570 // proxy. Kill it off now. That way, in case the profile is going away, the
1571 // rest of the objects attached to this RenderProcessHost start going
1572 // away first, since deleting the channel proxy will post a
1573 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1574 channel_.reset();
1576 // The following members should be cleared in ProcessDied() as well!
1577 gpu_message_filter_ = NULL;
1578 message_port_message_filter_ = NULL;
1579 #if defined(ENABLE_BROWSER_CDMS)
1580 browser_cdm_manager_ = NULL;
1581 #endif
1583 RemoveUserData(kSessionStorageHolderKey);
1585 // Remove ourself from the list of renderer processes so that we can't be
1586 // reused in between now and when the Delete task runs.
1587 UnregisterHost(GetID());
1591 void RenderProcessHostImpl::AddPendingView() {
1592 pending_views_++;
1595 void RenderProcessHostImpl::RemovePendingView() {
1596 DCHECK(pending_views_);
1597 pending_views_--;
1600 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1601 sudden_termination_allowed_ = enabled;
1604 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1605 return sudden_termination_allowed_;
1608 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1609 return base::TimeTicks::Now() - child_process_activity_time_;
1612 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1613 widget_helper_->ResumeRequestsForView(route_id);
1616 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1617 FilterURL(this, empty_allowed, url);
1620 #if defined(ENABLE_WEBRTC)
1621 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1622 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1623 // Enable AEC dump for each registered consumer.
1624 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1625 it != aec_dump_consumers_.end(); ++it) {
1626 EnableAecDumpForId(file, *it);
1630 void RenderProcessHostImpl::DisableAecDump() {
1631 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1632 // Posting on the FILE thread and then replying back on the UI thread is only
1633 // for avoiding races between enable and disable. Nothing is done on the FILE
1634 // thread.
1635 BrowserThread::PostTaskAndReply(
1636 BrowserThread::FILE, FROM_HERE,
1637 base::Bind(&DisableAecDumpOnFileThread),
1638 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1639 weak_factory_.GetWeakPtr()));
1642 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1643 base::Callback<void(const std::string&)> callback) {
1644 webrtc_log_message_callback_ = callback;
1647 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1648 RenderProcessHostImpl::StartRtpDump(
1649 bool incoming,
1650 bool outgoing,
1651 const WebRtcRtpPacketCallback& packet_callback) {
1652 if (!p2p_socket_dispatcher_host_.get())
1653 return WebRtcStopRtpDumpCallback();
1655 BrowserThread::PostTask(BrowserThread::IO,
1656 FROM_HERE,
1657 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1658 p2p_socket_dispatcher_host_,
1659 incoming,
1660 outgoing,
1661 packet_callback));
1663 if (stop_rtp_dump_callback_.is_null()) {
1664 stop_rtp_dump_callback_ =
1665 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1666 p2p_socket_dispatcher_host_);
1668 return stop_rtp_dump_callback_;
1670 #endif
1672 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1673 return channel_.get();
1676 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1677 channel_->AddFilter(filter->GetFilter());
1680 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1681 if (static_cast<size_t>(GetActiveViewCount()) == count)
1682 return FastShutdownIfPossible();
1683 return false;
1686 bool RenderProcessHostImpl::FastShutdownStarted() const {
1687 return fast_shutdown_started_;
1690 // static
1691 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1692 g_all_hosts.Get().AddWithID(host, host_id);
1695 // static
1696 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1697 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1698 if (!host)
1699 return;
1701 g_all_hosts.Get().Remove(host_id);
1703 // Look up the map of site to process for the given browser_context,
1704 // in case we need to remove this process from it. It will be registered
1705 // under any sites it rendered that use process-per-site mode.
1706 SiteProcessMap* map =
1707 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1708 map->RemoveProcess(host);
1711 // static
1712 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1713 bool empty_allowed,
1714 GURL* url) {
1715 ChildProcessSecurityPolicyImpl* policy =
1716 ChildProcessSecurityPolicyImpl::GetInstance();
1718 if (empty_allowed && url->is_empty())
1719 return;
1721 // The browser process should never hear the swappedout:// URL from any
1722 // of the renderer's messages. Check for this in debug builds, but don't
1723 // let it crash a release browser.
1724 DCHECK(GURL(kSwappedOutURL) != *url);
1726 if (!url->is_valid()) {
1727 // Have to use about:blank for the denied case, instead of an empty GURL.
1728 // This is because the browser treats navigation to an empty GURL as a
1729 // navigation to the home page. This is often a privileged page
1730 // (chrome://newtab/) which is exactly what we don't want.
1731 *url = GURL(url::kAboutBlankURL);
1732 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1733 return;
1736 if (url->SchemeIs(url::kAboutScheme)) {
1737 // The renderer treats all URLs in the about: scheme as being about:blank.
1738 // Canonicalize about: URLs to about:blank.
1739 *url = GURL(url::kAboutBlankURL);
1740 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1743 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1744 // cannot swap processes or grant bindings.
1745 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1746 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1748 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1749 // If this renderer is not permitted to request this URL, we invalidate the
1750 // URL. This prevents us from storing the blocked URL and becoming confused
1751 // later.
1752 VLOG(1) << "Blocked URL " << url->spec();
1753 *url = GURL(url::kAboutBlankURL);
1754 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1758 // static
1759 bool RenderProcessHostImpl::IsSuitableHost(
1760 RenderProcessHost* host,
1761 BrowserContext* browser_context,
1762 const GURL& site_url) {
1763 if (run_renderer_in_process())
1764 return true;
1766 if (host->GetBrowserContext() != browser_context)
1767 return false;
1769 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1770 // and non-guest storage gets mixed. In the future, we might consider enabling
1771 // the sharing of guests, in this case this check should be removed and
1772 // InSameStoragePartition should handle the possible sharing.
1773 if (host->IsIsolatedGuest())
1774 return false;
1776 // Check whether the given host and the intended site_url will be using the
1777 // same StoragePartition, since a RenderProcessHost can only support a single
1778 // StoragePartition. This is relevant for packaged apps and isolated sites.
1779 StoragePartition* dest_partition =
1780 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1781 if (!host->InSameStoragePartition(dest_partition))
1782 return false;
1784 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1785 host->GetID()) !=
1786 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1787 browser_context, site_url)) {
1788 return false;
1791 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1794 // static
1795 bool RenderProcessHost::run_renderer_in_process() {
1796 return g_run_renderer_in_process_;
1799 // static
1800 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1801 g_run_renderer_in_process_ = value;
1803 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1804 if (value) {
1805 if (!command_line->HasSwitch(switches::kLang)) {
1806 // Modify the current process' command line to include the browser locale,
1807 // as the renderer expects this flag to be set.
1808 const std::string locale =
1809 GetContentClient()->browser()->GetApplicationLocale();
1810 command_line->AppendSwitchASCII(switches::kLang, locale);
1812 // TODO(piman): we should really send configuration through bools rather
1813 // than by parsing strings, i.e. sending an IPC rather than command line
1814 // args. crbug.com/314909
1815 AppendCompositorCommandLineFlags(command_line);
1819 // static
1820 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1821 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1822 return iterator(g_all_hosts.Pointer());
1825 // static
1826 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1827 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1828 return g_all_hosts.Get().Lookup(render_process_id);
1831 // static
1832 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1833 BrowserContext* browser_context, const GURL& url) {
1834 // Experimental:
1835 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1836 // try to reuse renderer processes when over the limit. (We could allow pages
1837 // from the same site to share, if we knew what the given process was
1838 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1839 // resource exhaustion issues if too many sites are open at once.
1840 const base::CommandLine& command_line =
1841 *base::CommandLine::ForCurrentProcess();
1842 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1843 command_line.HasSwitch(switches::kSitePerProcess))
1844 return false;
1846 if (run_renderer_in_process())
1847 return true;
1849 // NOTE: Sometimes it's necessary to create more render processes than
1850 // GetMaxRendererProcessCount(), for instance when we want to create
1851 // a renderer process for a browser context that has no existing
1852 // renderers. This is OK in moderation, since the
1853 // GetMaxRendererProcessCount() is conservative.
1854 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1855 return true;
1857 return GetContentClient()->browser()->
1858 ShouldTryToUseExistingProcessHost(browser_context, url);
1861 // static
1862 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1863 BrowserContext* browser_context,
1864 const GURL& site_url) {
1865 // First figure out which existing renderers we can use.
1866 std::vector<RenderProcessHost*> suitable_renderers;
1867 suitable_renderers.reserve(g_all_hosts.Get().size());
1869 iterator iter(AllHostsIterator());
1870 while (!iter.IsAtEnd()) {
1871 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1872 RenderProcessHostImpl::IsSuitableHost(
1873 iter.GetCurrentValue(),
1874 browser_context, site_url)) {
1875 suitable_renderers.push_back(iter.GetCurrentValue());
1877 iter.Advance();
1880 // Now pick a random suitable renderer, if we have any.
1881 if (!suitable_renderers.empty()) {
1882 int suitable_count = static_cast<int>(suitable_renderers.size());
1883 int random_index = base::RandInt(0, suitable_count - 1);
1884 return suitable_renderers[random_index];
1887 return NULL;
1890 // static
1891 bool RenderProcessHost::ShouldUseProcessPerSite(
1892 BrowserContext* browser_context,
1893 const GURL& url) {
1894 // Returns true if we should use the process-per-site model. This will be
1895 // the case if the --process-per-site switch is specified, or in
1896 // process-per-site-instance for particular sites (e.g., WebUI).
1897 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1898 const base::CommandLine& command_line =
1899 *base::CommandLine::ForCurrentProcess();
1900 if (command_line.HasSwitch(switches::kProcessPerSite))
1901 return true;
1903 // We want to consolidate particular sites like WebUI even when we are using
1904 // the process-per-tab or process-per-site-instance models.
1905 // Note: DevTools pages have WebUI type but should not reuse the same host.
1906 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1907 browser_context, url) &&
1908 !url.SchemeIs(kChromeDevToolsScheme)) {
1909 return true;
1912 // Otherwise let the content client decide, defaulting to false.
1913 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1914 url);
1917 // static
1918 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1919 BrowserContext* browser_context,
1920 const GURL& url) {
1921 // Look up the map of site to process for the given browser_context.
1922 SiteProcessMap* map =
1923 GetSiteProcessMapForBrowserContext(browser_context);
1925 // See if we have an existing process with appropriate bindings for this site.
1926 // If not, the caller should create a new process and register it.
1927 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1928 .possibly_invalid_spec();
1929 RenderProcessHost* host = map->FindProcess(site);
1930 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
1931 !IsSuitableHost(host, browser_context, url))) {
1932 // The registered process does not have an appropriate set of bindings for
1933 // the url. Remove it from the map so we can register a better one.
1934 RecordAction(
1935 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1936 map->RemoveProcess(host);
1937 host = NULL;
1940 return host;
1943 void RenderProcessHostImpl::RegisterProcessHostForSite(
1944 BrowserContext* browser_context,
1945 RenderProcessHost* process,
1946 const GURL& url) {
1947 // Look up the map of site to process for the given browser_context.
1948 SiteProcessMap* map =
1949 GetSiteProcessMapForBrowserContext(browser_context);
1951 // Only register valid, non-empty sites. Empty or invalid sites will not
1952 // use process-per-site mode. We cannot check whether the process has
1953 // appropriate bindings here, because the bindings have not yet been granted.
1954 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1955 .possibly_invalid_spec();
1956 if (!site.empty())
1957 map->RegisterProcess(site, process);
1960 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1961 // Our child process has died. If we didn't expect it, it's a crash.
1962 // In any case, we need to let everyone know it's gone.
1963 // The OnChannelError notification can fire multiple times due to nested sync
1964 // calls to a renderer. If we don't have a valid channel here it means we
1965 // already handled the error.
1967 // It should not be possible for us to be called re-entrantly.
1968 DCHECK(!within_process_died_observer_);
1970 // It should not be possible for a process death notification to come in while
1971 // we are dying.
1972 DCHECK(!deleting_soon_);
1974 // child_process_launcher_ can be NULL in single process mode or if fast
1975 // termination happened.
1976 int exit_code = 0;
1977 base::TerminationStatus status =
1978 child_process_launcher_.get() ?
1979 child_process_launcher_->GetChildTerminationStatus(already_dead,
1980 &exit_code) :
1981 base::TERMINATION_STATUS_NORMAL_TERMINATION;
1983 RendererClosedDetails details(status, exit_code);
1984 mojo_application_host_->WillDestroySoon();
1986 child_process_launcher_.reset();
1987 channel_.reset();
1989 within_process_died_observer_ = true;
1990 NotificationService::current()->Notify(
1991 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1992 Source<RenderProcessHost>(this),
1993 Details<RendererClosedDetails>(&details));
1994 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1995 observers_,
1996 RenderProcessExited(this, status, exit_code));
1997 within_process_died_observer_ = false;
1999 gpu_message_filter_ = NULL;
2000 message_port_message_filter_ = NULL;
2001 #if defined(ENABLE_BROWSER_CDMS)
2002 browser_cdm_manager_ = NULL;
2003 #endif
2004 RemoveUserData(kSessionStorageHolderKey);
2006 IDMap<IPC::Listener>::iterator iter(&listeners_);
2007 while (!iter.IsAtEnd()) {
2008 iter.GetCurrentValue()->OnMessageReceived(
2009 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
2010 static_cast<int>(status),
2011 exit_code));
2012 iter.Advance();
2015 mojo_application_host_.reset(new MojoApplicationHost);
2017 // It's possible that one of the calls out to the observers might have caused
2018 // this object to be no longer needed.
2019 if (delayed_cleanup_needed_)
2020 Cleanup();
2022 // This object is not deleted at this point and might be reused later.
2023 // TODO(darin): clean this up
2026 int RenderProcessHostImpl::GetActiveViewCount() {
2027 int num_active_views = 0;
2028 scoped_ptr<RenderWidgetHostIterator> widgets(
2029 RenderWidgetHost::GetRenderWidgetHosts());
2030 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2031 // Count only RenderWidgetHosts in this process.
2032 if (widget->GetProcess()->GetID() == GetID())
2033 num_active_views++;
2035 return num_active_views;
2038 // Frame subscription API for this class is for accelerated composited path
2039 // only. These calls are redirected to GpuMessageFilter.
2040 void RenderProcessHostImpl::BeginFrameSubscription(
2041 int route_id,
2042 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
2043 if (!gpu_message_filter_)
2044 return;
2045 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2046 &GpuMessageFilter::BeginFrameSubscription,
2047 gpu_message_filter_,
2048 route_id, base::Passed(&subscriber)));
2051 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
2052 if (!gpu_message_filter_)
2053 return;
2054 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
2055 &GpuMessageFilter::EndFrameSubscription,
2056 gpu_message_filter_,
2057 route_id));
2060 #if defined(ENABLE_WEBRTC)
2061 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
2062 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2063 if (!webrtc_log_message_callback_.is_null())
2064 webrtc_log_message_callback_.Run(message);
2066 #endif
2068 void RenderProcessHostImpl::ReleaseOnCloseACK(
2069 RenderProcessHost* host,
2070 const SessionStorageNamespaceMap& sessions,
2071 int view_route_id) {
2072 DCHECK(host);
2073 if (sessions.empty())
2074 return;
2075 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2076 (host->GetUserData(kSessionStorageHolderKey));
2077 if (!holder) {
2078 holder = new SessionStorageHolder();
2079 host->SetUserData(
2080 kSessionStorageHolderKey,
2081 holder);
2083 holder->Hold(sessions, view_route_id);
2086 void RenderProcessHostImpl::OnShutdownRequest() {
2087 // Don't shut down if there are active RenderViews, or if there are pending
2088 // RenderViews being swapped back in.
2089 // In single process mode, we never shutdown the renderer.
2090 int num_active_views = GetActiveViewCount();
2091 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2092 return;
2094 // Notify any contents that might have swapped out renderers from this
2095 // process. They should not attempt to swap them back in.
2096 NotificationService::current()->Notify(
2097 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2098 Source<RenderProcessHost>(this),
2099 NotificationService::NoDetails());
2101 mojo_application_host_->WillDestroySoon();
2103 Send(new ChildProcessMsg_Shutdown());
2106 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2107 SetSuddenTerminationAllowed(enabled);
2110 void RenderProcessHostImpl::OnDumpHandlesDone() {
2111 Cleanup();
2114 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2115 // Note: we always set the backgrounded_ value. If the process is NULL
2116 // (and hence hasn't been created yet), we will set the process priority
2117 // later when we create the process.
2118 backgrounded_ = backgrounded;
2119 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2120 return;
2122 // Don't background processes which have active audio streams.
2123 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2124 return;
2126 #if defined(OS_WIN)
2127 // The cbstext.dll loads as a global GetMessage hook in the browser process
2128 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2129 // background thread. If the UI thread invokes this API just when it is
2130 // intercepted the stack is messed up on return from the interceptor
2131 // which causes random crashes in the browser process. Our hack for now
2132 // is to not invoke the SetPriorityClass API if the dll is loaded.
2133 if (GetModuleHandle(L"cbstext.dll"))
2134 return;
2135 #endif // OS_WIN
2137 // Notify the child process of background state.
2138 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2140 #if !defined(OS_WIN)
2141 // Backgrounding may require elevated privileges not available to renderer
2142 // processes, so control backgrounding from the process host.
2144 // Windows Vista+ has a fancy process backgrounding mode that can only be set
2145 // from within the process.
2146 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2147 #endif // !OS_WIN
2150 void RenderProcessHostImpl::OnProcessLaunched() {
2151 // No point doing anything, since this object will be destructed soon. We
2152 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2153 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2154 // properly cleanup.
2155 if (deleting_soon_)
2156 return;
2158 if (child_process_launcher_) {
2159 DCHECK(child_process_launcher_->GetProcess().IsValid());
2160 SetBackgrounded(backgrounded_);
2163 // NOTE: This needs to be before sending queued messages because
2164 // ExtensionService uses this notification to initialize the renderer process
2165 // with state that must be there before any JavaScript executes.
2167 // The queued messages contain such things as "navigate". If this notification
2168 // was after, we can end up executing JavaScript before the initialization
2169 // happens.
2170 NotificationService::current()->Notify(
2171 NOTIFICATION_RENDERER_PROCESS_CREATED,
2172 Source<RenderProcessHost>(this),
2173 NotificationService::NoDetails());
2175 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2176 // This way, Mojo can be safely used from the renderer in response to any
2177 // Chrome IPC message.
2178 mojo_application_host_->Activate(this, GetHandle());
2180 if (channel_mojo_host_)
2181 channel_mojo_host_->OnClientLaunched(GetHandle());
2183 while (!queued_messages_.empty()) {
2184 Send(queued_messages_.front());
2185 queued_messages_.pop();
2188 #if defined(ENABLE_WEBRTC)
2189 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2190 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2191 #endif
2194 scoped_refptr<AudioRendererHost>
2195 RenderProcessHostImpl::audio_renderer_host() const {
2196 return audio_renderer_host_;
2199 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2200 const std::string& action) {
2201 RecordComputedAction(action);
2204 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2205 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2206 (GetUserData(kSessionStorageHolderKey));
2207 if (!holder)
2208 return;
2209 holder->Release(old_route_id);
2212 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2213 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2216 void RenderProcessHostImpl::OnGpuSwitched() {
2217 // We are updating all widgets including swapped out ones.
2218 scoped_ptr<RenderWidgetHostIterator> widgets(
2219 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2220 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2221 if (!widget->IsRenderView())
2222 continue;
2224 // Skip widgets in other processes.
2225 if (widget->GetProcess()->GetID() != GetID())
2226 continue;
2228 RenderViewHost* rvh = RenderViewHost::From(widget);
2229 rvh->OnWebkitPreferencesChanged();
2233 #if defined(ENABLE_WEBRTC)
2234 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2235 BrowserThread::PostTask(
2236 BrowserThread::UI,
2237 FROM_HERE,
2238 base::Bind(
2239 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2240 weak_factory_.GetWeakPtr(),
2241 id));
2244 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2245 BrowserThread::PostTask(
2246 BrowserThread::UI,
2247 FROM_HERE,
2248 base::Bind(
2249 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2250 weak_factory_.GetWeakPtr(),
2251 id));
2254 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2255 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2256 aec_dump_consumers_.push_back(id);
2257 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2258 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2259 id);
2263 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2264 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2265 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2266 it != aec_dump_consumers_.end(); ++it) {
2267 if (*it == id) {
2268 aec_dump_consumers_.erase(it);
2269 break;
2274 #if defined(OS_WIN)
2275 #define IntToStringType base::IntToString16
2276 #else
2277 #define IntToStringType base::IntToString
2278 #endif
2280 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2281 int id) {
2282 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2283 base::FilePath unique_file =
2284 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2285 .AddExtension(IntToStringType(id));
2286 BrowserThread::PostTaskAndReplyWithResult(
2287 BrowserThread::FILE, FROM_HERE,
2288 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2289 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2290 weak_factory_.GetWeakPtr(),
2291 id));
2294 #undef IntToStringType
2296 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2297 int id,
2298 IPC::PlatformFileForTransit file_for_transit) {
2299 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2300 return;
2301 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2304 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2305 Send(new AecDumpMsg_DisableAecDump());
2307 #endif
2309 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2310 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2311 ++worker_ref_count_;
2314 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2315 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2316 DCHECK_GT(worker_ref_count_, 0);
2317 --worker_ref_count_;
2318 if (worker_ref_count_ == 0)
2319 Cleanup();
2322 } // namespace content