cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blob2b646222aa4357b80f7b39b5a698fbe1c3aeac63
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 #if defined(OS_POSIX)
15 #include <utility> // for pair<>
16 #endif
18 #include "base/base_switches.h"
19 #include "base/bind.h"
20 #include "base/bind_helpers.h"
21 #include "base/callback.h"
22 #include "base/command_line.h"
23 #include "base/debug/trace_event.h"
24 #include "base/files/file.h"
25 #include "base/lazy_instance.h"
26 #include "base/logging.h"
27 #include "base/metrics/field_trial.h"
28 #include "base/metrics/histogram.h"
29 #include "base/path_service.h"
30 #include "base/process/process_handle.h"
31 #include "base/rand_util.h"
32 #include "base/stl_util.h"
33 #include "base/strings/string_number_conversions.h"
34 #include "base/strings/string_util.h"
35 #include "base/supports_user_data.h"
36 #include "base/sys_info.h"
37 #include "base/threading/thread.h"
38 #include "base/threading/thread_restrictions.h"
39 #include "base/tracked_objects.h"
40 #include "cc/base/switches.h"
41 #include "content/browser/appcache/appcache_dispatcher_host.h"
42 #include "content/browser/appcache/chrome_appcache_service.h"
43 #include "content/browser/battery_status/battery_status_message_filter.h"
44 #include "content/browser/browser_child_process_host_impl.h"
45 #include "content/browser/browser_main.h"
46 #include "content/browser/browser_main_loop.h"
47 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
48 #include "content/browser/child_process_security_policy_impl.h"
49 #include "content/browser/device_sensors/device_light_message_filter.h"
50 #include "content/browser/device_sensors/device_motion_message_filter.h"
51 #include "content/browser/device_sensors/device_orientation_message_filter.h"
52 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
53 #include "content/browser/dom_storage/dom_storage_message_filter.h"
54 #include "content/browser/download/mhtml_generation_manager.h"
55 #include "content/browser/fileapi/chrome_blob_storage_context.h"
56 #include "content/browser/fileapi/fileapi_message_filter.h"
57 #include "content/browser/frame_host/render_frame_message_filter.h"
58 #include "content/browser/geofencing/geofencing_dispatcher_host.h"
59 #include "content/browser/gpu/compositor_util.h"
60 #include "content/browser/gpu/gpu_data_manager_impl.h"
61 #include "content/browser/gpu/gpu_process_host.h"
62 #include "content/browser/gpu/shader_disk_cache.h"
63 #include "content/browser/histogram_message_filter.h"
64 #include "content/browser/indexed_db/indexed_db_context_impl.h"
65 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
66 #include "content/browser/loader/resource_message_filter.h"
67 #include "content/browser/loader/resource_scheduler_filter.h"
68 #include "content/browser/media/capture/audio_mirroring_manager.h"
69 #include "content/browser/media/media_internals.h"
70 #include "content/browser/media/midi_host.h"
71 #include "content/browser/message_port_message_filter.h"
72 #include "content/browser/mime_registry_message_filter.h"
73 #include "content/browser/mojo/mojo_application_host.h"
74 #include "content/browser/notification_message_filter.h"
75 #include "content/browser/profiler_message_filter.h"
76 #include "content/browser/push_messaging_message_filter.h"
77 #include "content/browser/quota_dispatcher_host.h"
78 #include "content/browser/renderer_host/clipboard_message_filter.h"
79 #include "content/browser/renderer_host/database_message_filter.h"
80 #include "content/browser/renderer_host/file_utilities_message_filter.h"
81 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
82 #include "content/browser/renderer_host/gpu_message_filter.h"
83 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
84 #include "content/browser/renderer_host/media/audio_renderer_host.h"
85 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
86 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
87 #include "content/browser/renderer_host/media/video_capture_host.h"
88 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
89 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
90 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
91 #include "content/browser/renderer_host/render_message_filter.h"
92 #include "content/browser/renderer_host/render_view_host_delegate.h"
93 #include "content/browser/renderer_host/render_view_host_impl.h"
94 #include "content/browser/renderer_host/render_widget_helper.h"
95 #include "content/browser/renderer_host/render_widget_host_impl.h"
96 #include "content/browser/renderer_host/text_input_client_message_filter.h"
97 #include "content/browser/renderer_host/websocket_dispatcher_host.h"
98 #include "content/browser/resolve_proxy_msg_helper.h"
99 #include "content/browser/service_worker/service_worker_context_wrapper.h"
100 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
101 #include "content/browser/shared_worker/shared_worker_message_filter.h"
102 #include "content/browser/shared_worker/worker_storage_partition.h"
103 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
104 #include "content/browser/storage_partition_impl.h"
105 #include "content/browser/streams/stream_context.h"
106 #include "content/browser/tracing/trace_message_filter.h"
107 #include "content/browser/vibration/vibration_message_filter.h"
108 #include "content/browser/webui/web_ui_controller_factory_registry.h"
109 #include "content/common/child_process_host_impl.h"
110 #include "content/common/child_process_messages.h"
111 #include "content/common/content_switches_internal.h"
112 #include "content/common/gpu/gpu_messages.h"
113 #include "content/common/mojo/mojo_messages.h"
114 #include "content/common/resource_messages.h"
115 #include "content/common/view_messages.h"
116 #include "content/public/browser/browser_context.h"
117 #include "content/public/browser/content_browser_client.h"
118 #include "content/public/browser/notification_service.h"
119 #include "content/public/browser/notification_types.h"
120 #include "content/public/browser/render_process_host_factory.h"
121 #include "content/public/browser/render_process_host_observer.h"
122 #include "content/public/browser/render_widget_host.h"
123 #include "content/public/browser/render_widget_host_iterator.h"
124 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
125 #include "content/public/browser/resource_context.h"
126 #include "content/public/browser/user_metrics.h"
127 #include "content/public/browser/worker_service.h"
128 #include "content/public/common/content_constants.h"
129 #include "content/public/common/content_switches.h"
130 #include "content/public/common/process_type.h"
131 #include "content/public/common/resource_type.h"
132 #include "content/public/common/result_codes.h"
133 #include "content/public/common/sandboxed_process_launcher_delegate.h"
134 #include "content/public/common/url_constants.h"
135 #include "gpu/command_buffer/client/gpu_switches.h"
136 #include "gpu/command_buffer/service/gpu_switches.h"
137 #include "ipc/ipc_channel.h"
138 #include "ipc/ipc_logging.h"
139 #include "ipc/ipc_switches.h"
140 #include "ipc/mojo/ipc_channel_mojo.h"
141 #include "ipc/mojo/ipc_channel_mojo_host.h"
142 #include "media/base/media_switches.h"
143 #include "net/url_request/url_request_context_getter.h"
144 #include "ppapi/shared_impl/ppapi_switches.h"
145 #include "storage/browser/fileapi/sandbox_file_system_backend.h"
146 #include "third_party/skia/include/core/SkBitmap.h"
147 #include "ui/base/ui_base_switches.h"
148 #include "ui/events/event_switches.h"
149 #include "ui/gfx/switches.h"
150 #include "ui/gl/gl_switches.h"
151 #include "ui/gl/gpu_switching_manager.h"
152 #include "ui/native_theme/native_theme_switches.h"
154 #if defined(OS_ANDROID)
155 #include "content/browser/media/android/browser_demuxer_android.h"
156 #include "content/browser/screen_orientation/screen_orientation_message_filter_android.h"
157 #endif
159 #if defined(OS_WIN)
160 #include "base/win/scoped_com_initializer.h"
161 #include "content/common/font_cache_dispatcher_win.h"
162 #include "content/common/sandbox_win.h"
163 #include "ui/gfx/win/dpi.h"
164 #endif
166 #if defined(ENABLE_BROWSER_CDMS)
167 #include "content/browser/media/cdm/browser_cdm_manager.h"
168 #endif
170 #if defined(ENABLE_PLUGINS)
171 #include "content/browser/plugin_service_impl.h"
172 #endif
174 #if defined(ENABLE_WEBRTC)
175 #include "content/browser/media/webrtc_internals.h"
176 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
177 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
178 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
179 #include "content/common/media/aec_dump_messages.h"
180 #include "content/common/media/media_stream_messages.h"
181 #endif
183 extern bool g_exited_main_message_loop;
185 namespace content {
186 namespace {
188 const char kSiteProcessMapKeyName[] = "content_site_process_map";
190 void CacheShaderInfo(int32 id, base::FilePath path) {
191 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
194 void RemoveShaderInfo(int32 id) {
195 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
198 net::URLRequestContext* GetRequestContext(
199 scoped_refptr<net::URLRequestContextGetter> request_context,
200 scoped_refptr<net::URLRequestContextGetter> media_request_context,
201 ResourceType resource_type) {
202 // If the request has resource type of RESOURCE_TYPE_MEDIA, we use a request
203 // context specific to media for handling it because these resources have
204 // specific needs for caching.
205 if (resource_type == RESOURCE_TYPE_MEDIA)
206 return media_request_context->GetURLRequestContext();
207 return request_context->GetURLRequestContext();
210 void GetContexts(
211 ResourceContext* resource_context,
212 scoped_refptr<net::URLRequestContextGetter> request_context,
213 scoped_refptr<net::URLRequestContextGetter> media_request_context,
214 const ResourceHostMsg_Request& request,
215 ResourceContext** resource_context_out,
216 net::URLRequestContext** request_context_out) {
217 *resource_context_out = resource_context;
218 *request_context_out =
219 GetRequestContext(request_context, media_request_context,
220 request.resource_type);
223 #if defined(ENABLE_WEBRTC)
224 // Creates a file used for diagnostic echo canceller recordings for handing
225 // over to the renderer.
226 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
227 base::FilePath file_path,
228 base::ProcessHandle process) {
229 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
230 base::File dump_file(file_path,
231 base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
232 if (!dump_file.IsValid()) {
233 VLOG(1) << "Could not open AEC dump file, error=" <<
234 dump_file.error_details();
235 return IPC::InvalidPlatformFileForTransit();
237 return IPC::TakeFileHandleForProcess(dump_file.Pass(), process);
240 // Does nothing. Just to avoid races between enable and disable.
241 void DisableAecDumpOnFileThread() {
242 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
244 #endif
246 // the global list of all renderer processes
247 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
248 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
250 // Map of site to process, to ensure we only have one RenderProcessHost per
251 // site in process-per-site mode. Each map is specific to a BrowserContext.
252 class SiteProcessMap : public base::SupportsUserData::Data {
253 public:
254 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
255 SiteProcessMap() {}
257 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
258 map_[site] = process;
261 RenderProcessHost* FindProcess(const std::string& site) {
262 SiteToProcessMap::iterator i = map_.find(site);
263 if (i != map_.end())
264 return i->second;
265 return NULL;
268 void RemoveProcess(RenderProcessHost* host) {
269 // Find all instances of this process in the map, then separately remove
270 // them.
271 std::set<std::string> sites;
272 for (SiteToProcessMap::const_iterator i = map_.begin();
273 i != map_.end();
274 i++) {
275 if (i->second == host)
276 sites.insert(i->first);
278 for (std::set<std::string>::iterator i = sites.begin();
279 i != sites.end();
280 i++) {
281 SiteToProcessMap::iterator iter = map_.find(*i);
282 if (iter != map_.end()) {
283 DCHECK_EQ(iter->second, host);
284 map_.erase(iter);
289 private:
290 SiteToProcessMap map_;
293 // Find the SiteProcessMap specific to the given context.
294 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
295 DCHECK(context);
296 SiteProcessMap* map = static_cast<SiteProcessMap*>(
297 context->GetUserData(kSiteProcessMapKeyName));
298 if (!map) {
299 map = new SiteProcessMap();
300 context->SetUserData(kSiteProcessMapKeyName, map);
302 return map;
305 // NOTE: changes to this class need to be reviewed by the security team.
306 class RendererSandboxedProcessLauncherDelegate
307 : public SandboxedProcessLauncherDelegate {
308 public:
309 explicit RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
310 #if defined(OS_POSIX)
311 : ipc_fd_(channel->TakeClientFileDescriptor())
312 #endif // OS_POSIX
315 ~RendererSandboxedProcessLauncherDelegate() override {}
317 #if defined(OS_WIN)
318 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
319 bool* success) {
320 AddBaseHandleClosePolicy(policy);
321 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
324 #elif defined(OS_POSIX)
325 bool ShouldUseZygote() override {
326 const base::CommandLine& browser_command_line =
327 *base::CommandLine::ForCurrentProcess();
328 base::CommandLine::StringType renderer_prefix =
329 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
330 return renderer_prefix.empty();
332 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
333 #endif // OS_WIN
335 private:
336 #if defined(OS_POSIX)
337 base::ScopedFD ipc_fd_;
338 #endif // OS_POSIX
341 const char kSessionStorageHolderKey[] = "kSessionStorageHolderKey";
343 class SessionStorageHolder : public base::SupportsUserData::Data {
344 public:
345 SessionStorageHolder() {}
346 ~SessionStorageHolder() override {}
348 void Hold(const SessionStorageNamespaceMap& sessions, int view_route_id) {
349 session_storage_namespaces_awaiting_close_[view_route_id] = sessions;
352 void Release(int old_route_id) {
353 session_storage_namespaces_awaiting_close_.erase(old_route_id);
356 private:
357 std::map<int, SessionStorageNamespaceMap >
358 session_storage_namespaces_awaiting_close_;
359 DISALLOW_COPY_AND_ASSIGN(SessionStorageHolder);
362 } // namespace
364 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
366 base::MessageLoop* g_in_process_thread;
368 base::MessageLoop*
369 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
370 return g_in_process_thread;
373 // Stores the maximum number of renderer processes the content module can
374 // create.
375 static size_t g_max_renderer_count_override = 0;
377 // static
378 size_t RenderProcessHost::GetMaxRendererProcessCount() {
379 if (g_max_renderer_count_override)
380 return g_max_renderer_count_override;
382 #if defined(OS_ANDROID)
383 // On Android we don't maintain a limit of renderer process hosts - we are
384 // happy with keeping a lot of these, as long as the number of live renderer
385 // processes remains reasonable, and on Android the OS takes care of that.
386 return std::numeric_limits<size_t>::max();
387 #endif
389 // On other platforms, we calculate the maximum number of renderer process
390 // hosts according to the amount of installed memory as reported by the OS.
391 // The calculation assumes that you want the renderers to use half of the
392 // installed RAM and assuming that each WebContents uses ~40MB. If you modify
393 // this assumption, you need to adjust the ThirtyFourTabs test to match the
394 // expected number of processes.
396 // With the given amounts of installed memory below on a 32-bit CPU, the
397 // maximum renderer count will roughly be as follows:
399 // 128 MB -> 3
400 // 512 MB -> 6
401 // 1024 MB -> 12
402 // 4096 MB -> 51
403 // 16384 MB -> 82 (kMaxRendererProcessCount)
405 static size_t max_count = 0;
406 if (!max_count) {
407 const size_t kEstimatedWebContentsMemoryUsage =
408 #if defined(ARCH_CPU_64_BITS)
409 60; // In MB
410 #else
411 40; // In MB
412 #endif
413 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
414 max_count /= kEstimatedWebContentsMemoryUsage;
416 const size_t kMinRendererProcessCount = 3;
417 max_count = std::max(max_count, kMinRendererProcessCount);
418 max_count = std::min(max_count, kMaxRendererProcessCount);
420 return max_count;
423 // static
424 bool g_run_renderer_in_process_ = false;
426 // static
427 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
428 g_max_renderer_count_override = count;
431 RenderProcessHostImpl::RenderProcessHostImpl(
432 BrowserContext* browser_context,
433 StoragePartitionImpl* storage_partition_impl,
434 bool is_isolated_guest)
435 : fast_shutdown_started_(false),
436 deleting_soon_(false),
437 #ifndef NDEBUG
438 is_self_deleted_(false),
439 #endif
440 pending_views_(0),
441 mojo_application_host_(new MojoApplicationHost),
442 visible_widgets_(0),
443 backgrounded_(true),
444 is_initialized_(false),
445 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
446 browser_context_(browser_context),
447 storage_partition_impl_(storage_partition_impl),
448 sudden_termination_allowed_(true),
449 ignore_input_events_(false),
450 is_isolated_guest_(is_isolated_guest),
451 gpu_observer_registered_(false),
452 delayed_cleanup_needed_(false),
453 within_process_died_observer_(false),
454 power_monitor_broadcaster_(this),
455 worker_ref_count_(0),
456 weak_factory_(this) {
457 widget_helper_ = new RenderWidgetHelper();
459 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
461 CHECK(!g_exited_main_message_loop);
462 RegisterHost(GetID(), this);
463 g_all_hosts.Get().set_check_on_null_data(true);
464 // Initialize |child_process_activity_time_| to a reasonable value.
465 mark_child_process_activity_time();
467 if (!GetBrowserContext()->IsOffTheRecord() &&
468 !base::CommandLine::ForCurrentProcess()->HasSwitch(
469 switches::kDisableGpuShaderDiskCache)) {
470 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
471 base::Bind(&CacheShaderInfo, GetID(),
472 storage_partition_impl_->GetPath()));
475 // Note: When we create the RenderProcessHostImpl, it's technically
476 // backgrounded, because it has no visible listeners. But the process
477 // doesn't actually exist yet, so we'll Background it later, after
478 // creation.
481 // static
482 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
483 DCHECK(g_run_renderer_in_process_);
485 switch (g_all_hosts.Pointer()->size()) {
486 case 0:
487 return;
488 case 1: {
489 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
490 AllHostsIterator().GetCurrentValue());
491 FOR_EACH_OBSERVER(RenderProcessHostObserver,
492 host->observers_,
493 RenderProcessHostDestroyed(host));
494 #ifndef NDEBUG
495 host->is_self_deleted_ = true;
496 #endif
497 delete host;
498 return;
500 default:
501 NOTREACHED() << "There should be only one RenderProcessHost when running "
502 << "in-process.";
506 void RenderProcessHostImpl::RegisterRendererMainThreadFactory(
507 RendererMainThreadFactoryFunction create) {
508 g_renderer_main_thread_factory = create;
511 RenderProcessHostImpl::~RenderProcessHostImpl() {
512 #ifndef NDEBUG
513 DCHECK(is_self_deleted_)
514 << "RenderProcessHostImpl is destroyed by something other than itself";
515 #endif
517 // Make sure to clean up the in-process renderer before the channel, otherwise
518 // it may still run and have its IPCs fail, causing asserts.
519 in_process_renderer_.reset();
521 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
523 if (gpu_observer_registered_) {
524 ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this);
525 gpu_observer_registered_ = false;
528 // We may have some unsent messages at this point, but that's OK.
529 channel_.reset();
530 while (!queued_messages_.empty()) {
531 delete queued_messages_.front();
532 queued_messages_.pop();
535 UnregisterHost(GetID());
537 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
538 switches::kDisableGpuShaderDiskCache)) {
539 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
540 base::Bind(&RemoveShaderInfo, GetID()));
544 void RenderProcessHostImpl::EnableSendQueue() {
545 is_initialized_ = false;
548 bool RenderProcessHostImpl::Init() {
549 // calling Init() more than once does nothing, this makes it more convenient
550 // for the view host which may not be sure in some cases
551 if (channel_)
552 return true;
554 base::CommandLine::StringType renderer_prefix;
555 #if defined(OS_POSIX)
556 // A command prefix is something prepended to the command line of the spawned
557 // process. It is supported only on POSIX systems.
558 const base::CommandLine& browser_command_line =
559 *base::CommandLine::ForCurrentProcess();
560 renderer_prefix =
561 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
562 #endif // defined(OS_POSIX)
564 #if defined(OS_LINUX)
565 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
566 ChildProcessHost::CHILD_NORMAL;
567 #else
568 int flags = ChildProcessHost::CHILD_NORMAL;
569 #endif
571 // Find the renderer before creating the channel so if this fails early we
572 // return without creating the channel.
573 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
574 if (renderer_path.empty())
575 return false;
577 // Setup the IPC channel.
578 const std::string channel_id =
579 IPC::Channel::GenerateVerifiedChannelID(std::string());
580 channel_ = CreateChannelProxy(channel_id);
582 // Setup the Mojo channel.
583 mojo_application_host_->Init();
585 // Call the embedder first so that their IPC filters have priority.
586 GetContentClient()->browser()->RenderProcessWillLaunch(this);
588 CreateMessageFilters();
590 if (run_renderer_in_process()) {
591 DCHECK(g_renderer_main_thread_factory);
592 // Crank up a thread and run the initialization there. With the way that
593 // messages flow between the browser and renderer, this thread is required
594 // to prevent a deadlock in single-process mode. Since the primordial
595 // thread in the renderer process runs the WebKit code and can sometimes
596 // make blocking calls to the UI thread (i.e. this thread), they need to run
597 // on separate threads.
598 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
600 base::Thread::Options options;
601 #if defined(OS_WIN) && !defined(OS_MACOSX)
602 // In-process plugins require this to be a UI message loop.
603 options.message_loop_type = base::MessageLoop::TYPE_UI;
604 #else
605 // We can't have multiple UI loops on Linux and Android, so we don't support
606 // in-process plugins.
607 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
608 #endif
609 in_process_renderer_->StartWithOptions(options);
611 g_in_process_thread = in_process_renderer_->message_loop();
613 OnProcessLaunched(); // Fake a callback that the process is ready.
614 } else {
615 // Build command line for renderer. We call AppendRendererCommandLine()
616 // first so the process type argument will appear first.
617 base::CommandLine* cmd_line = new base::CommandLine(renderer_path);
618 if (!renderer_prefix.empty())
619 cmd_line->PrependWrapper(renderer_prefix);
620 AppendRendererCommandLine(cmd_line);
621 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
623 // Spawn the child process asynchronously to avoid blocking the UI thread.
624 // As long as there's no renderer prefix, we can use the zygote process
625 // at this stage.
626 child_process_launcher_.reset(new ChildProcessLauncher(
627 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
628 cmd_line,
629 GetID(),
630 this));
632 fast_shutdown_started_ = false;
635 if (!gpu_observer_registered_) {
636 gpu_observer_registered_ = true;
637 ui::GpuSwitchingManager::GetInstance()->AddObserver(this);
640 power_monitor_broadcaster_.Init();
642 is_initialized_ = true;
643 init_time_ = base::TimeTicks::Now();
644 return true;
647 bool RenderProcessHostImpl::ShouldUseMojoChannel() const {
648 const base::CommandLine& command_line =
649 *base::CommandLine::ForCurrentProcess();
650 return command_line.HasSwitch(switches::kEnableRendererMojoChannel) ||
651 IPC::ChannelMojo::ShouldBeUsed();
654 scoped_ptr<IPC::ChannelProxy> RenderProcessHostImpl::CreateChannelProxy(
655 const std::string& channel_id) {
656 scoped_refptr<base::SingleThreadTaskRunner> runner =
657 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
658 if (ShouldUseMojoChannel()) {
659 VLOG(1) << "Mojo Channel is enabled on host";
660 if (!channel_mojo_host_) {
661 channel_mojo_host_.reset(new IPC::ChannelMojoHost(
662 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
665 return IPC::ChannelProxy::Create(
666 IPC::ChannelMojo::CreateServerFactory(
667 channel_mojo_host_->channel_delegate(), channel_id),
668 this,
669 runner.get());
672 return IPC::ChannelProxy::Create(
673 channel_id, IPC::Channel::MODE_SERVER, this, runner.get());
676 void RenderProcessHostImpl::CreateMessageFilters() {
677 DCHECK_CURRENTLY_ON(BrowserThread::UI);
678 AddFilter(new ResourceSchedulerFilter(GetID()));
679 MediaInternals* media_internals = MediaInternals::GetInstance();
680 media::AudioManager* audio_manager =
681 BrowserMainLoop::GetInstance()->audio_manager();
682 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
683 // from guests.
684 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
685 new BrowserPluginMessageFilter(GetID()));
686 AddFilter(bp_message_filter.get());
688 scoped_refptr<RenderMessageFilter> render_message_filter(
689 new RenderMessageFilter(
690 GetID(),
691 #if defined(ENABLE_PLUGINS)
692 PluginServiceImpl::GetInstance(),
693 #else
694 NULL,
695 #endif
696 GetBrowserContext(),
697 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
698 widget_helper_.get(),
699 audio_manager,
700 media_internals,
701 storage_partition_impl_->GetDOMStorageContext()));
702 AddFilter(render_message_filter.get());
703 AddFilter(
704 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
705 BrowserContext* browser_context = GetBrowserContext();
706 ResourceContext* resource_context = browser_context->GetResourceContext();
708 scoped_refptr<net::URLRequestContextGetter> request_context(
709 browser_context->GetRequestContextForRenderProcess(GetID()));
710 scoped_refptr<net::URLRequestContextGetter> media_request_context(
711 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
713 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
714 base::Bind(&GetContexts, browser_context->GetResourceContext(),
715 request_context, media_request_context));
717 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
718 GetID(), PROCESS_TYPE_RENDERER,
719 storage_partition_impl_->GetAppCacheService(),
720 ChromeBlobStorageContext::GetFor(browser_context),
721 storage_partition_impl_->GetFileSystemContext(),
722 storage_partition_impl_->GetServiceWorkerContext(),
723 get_contexts_callback);
725 AddFilter(resource_message_filter);
726 MediaStreamManager* media_stream_manager =
727 BrowserMainLoop::GetInstance()->media_stream_manager();
728 AddFilter(new AudioInputRendererHost(
729 audio_manager,
730 media_stream_manager,
731 AudioMirroringManager::GetInstance(),
732 BrowserMainLoop::GetInstance()->user_input_monitor()));
733 // The AudioRendererHost needs to be available for lookup, so it's
734 // stashed in a member variable.
735 audio_renderer_host_ = new AudioRendererHost(
736 GetID(),
737 audio_manager,
738 AudioMirroringManager::GetInstance(),
739 media_internals,
740 media_stream_manager);
741 AddFilter(audio_renderer_host_.get());
742 AddFilter(
743 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
744 AddFilter(new VideoCaptureHost(media_stream_manager));
745 AddFilter(new AppCacheDispatcherHost(
746 storage_partition_impl_->GetAppCacheService(),
747 GetID()));
748 AddFilter(new ClipboardMessageFilter);
749 AddFilter(new DOMStorageMessageFilter(
750 GetID(),
751 storage_partition_impl_->GetDOMStorageContext()));
752 AddFilter(new IndexedDBDispatcherHost(
753 GetID(),
754 storage_partition_impl_->GetURLRequestContext(),
755 storage_partition_impl_->GetIndexedDBContext(),
756 ChromeBlobStorageContext::GetFor(browser_context)));
758 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
759 AddFilter(gpu_message_filter_);
760 #if defined(ENABLE_WEBRTC)
761 AddFilter(new WebRTCIdentityServiceHost(
762 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
763 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
764 AddFilter(peer_connection_tracker_host_.get());
765 AddFilter(new MediaStreamDispatcherHost(
766 GetID(),
767 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
768 media_stream_manager));
769 AddFilter(new MediaStreamTrackMetricsHost());
770 #endif
771 #if defined(ENABLE_PLUGINS)
772 AddFilter(new PepperRendererConnection(GetID()));
773 #endif
774 AddFilter(new SpeechRecognitionDispatcherHost(
775 GetID(), storage_partition_impl_->GetURLRequestContext()));
776 AddFilter(new FileAPIMessageFilter(
777 GetID(),
778 storage_partition_impl_->GetURLRequestContext(),
779 storage_partition_impl_->GetFileSystemContext(),
780 ChromeBlobStorageContext::GetFor(browser_context),
781 StreamContext::GetFor(browser_context)));
782 AddFilter(new FileUtilitiesMessageFilter(GetID()));
783 AddFilter(new MimeRegistryMessageFilter());
784 AddFilter(new DatabaseMessageFilter(
785 storage_partition_impl_->GetDatabaseTracker()));
786 #if defined(OS_MACOSX)
787 AddFilter(new TextInputClientMessageFilter(GetID()));
788 #elif defined(OS_WIN)
789 // The FontCacheDispatcher is required only when we're using GDI rendering.
790 // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
791 // GDI fonts (http://crbug.com/383227), even when using DirectWrite. This
792 // should eventually be if (!ShouldUseDirectWrite()) guarded.
793 channel_->AddFilter(new FontCacheDispatcher());
794 #elif defined(OS_ANDROID)
795 browser_demuxer_android_ = new BrowserDemuxerAndroid();
796 AddFilter(browser_demuxer_android_.get());
797 #endif
798 #if defined(ENABLE_BROWSER_CDMS)
799 browser_cdm_manager_ = new BrowserCdmManager(GetID(), NULL);
800 AddFilter(browser_cdm_manager_.get());
801 #endif
803 WebSocketDispatcherHost::GetRequestContextCallback
804 websocket_request_context_callback(
805 base::Bind(&GetRequestContext, request_context,
806 media_request_context, RESOURCE_TYPE_SUB_RESOURCE));
808 AddFilter(
809 new WebSocketDispatcherHost(GetID(), websocket_request_context_callback));
811 message_port_message_filter_ = new MessagePortMessageFilter(
812 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
813 base::Unretained(widget_helper_.get())));
814 AddFilter(message_port_message_filter_.get());
816 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
817 new ServiceWorkerDispatcherHost(
818 GetID(), message_port_message_filter_.get(), resource_context);
819 service_worker_filter->Init(
820 storage_partition_impl_->GetServiceWorkerContext());
821 AddFilter(service_worker_filter.get());
823 AddFilter(new SharedWorkerMessageFilter(
824 GetID(),
825 resource_context,
826 WorkerStoragePartition(
827 storage_partition_impl_->GetURLRequestContext(),
828 storage_partition_impl_->GetMediaURLRequestContext(),
829 storage_partition_impl_->GetAppCacheService(),
830 storage_partition_impl_->GetQuotaManager(),
831 storage_partition_impl_->GetFileSystemContext(),
832 storage_partition_impl_->GetDatabaseTracker(),
833 storage_partition_impl_->GetIndexedDBContext(),
834 storage_partition_impl_->GetServiceWorkerContext()),
835 message_port_message_filter_.get()));
837 #if defined(ENABLE_WEBRTC)
838 p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost(
839 resource_context,
840 browser_context->GetRequestContextForRenderProcess(GetID()));
841 AddFilter(p2p_socket_dispatcher_host_.get());
842 #endif
844 AddFilter(new TraceMessageFilter());
845 AddFilter(new ResolveProxyMsgHelper(
846 browser_context->GetRequestContextForRenderProcess(GetID())));
847 AddFilter(new QuotaDispatcherHost(
848 GetID(),
849 storage_partition_impl_->GetQuotaManager(),
850 GetContentClient()->browser()->CreateQuotaPermissionContext()));
851 AddFilter(new NotificationMessageFilter(
852 GetID(),
853 resource_context));
854 AddFilter(new GamepadBrowserMessageFilter());
855 AddFilter(new DeviceLightMessageFilter());
856 AddFilter(new DeviceMotionMessageFilter());
857 AddFilter(new DeviceOrientationMessageFilter());
858 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
859 AddFilter(new HistogramMessageFilter());
860 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
861 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
862 switches::kEnableMemoryBenchmarking))
863 AddFilter(new MemoryBenchmarkMessageFilter());
864 #endif
865 AddFilter(new VibrationMessageFilter());
866 AddFilter(new PushMessagingMessageFilter(
867 GetID(), storage_partition_impl_->GetServiceWorkerContext()));
868 AddFilter(new BatteryStatusMessageFilter());
869 #if defined(OS_ANDROID)
870 AddFilter(new ScreenOrientationMessageFilterAndroid());
871 #endif
872 AddFilter(new GeofencingDispatcherHost(
873 storage_partition_impl_->GetGeofencingManager()));
876 int RenderProcessHostImpl::GetNextRoutingID() {
877 return widget_helper_->GetNextRoutingID();
881 void RenderProcessHostImpl::ResumeDeferredNavigation(
882 const GlobalRequestID& request_id) {
883 widget_helper_->ResumeDeferredNavigation(request_id);
886 void RenderProcessHostImpl::ResumeResponseDeferredAtStart(
887 const GlobalRequestID& request_id) {
888 widget_helper_->ResumeResponseDeferredAtStart(request_id);
891 void RenderProcessHostImpl::NotifyTimezoneChange() {
892 Send(new ViewMsg_TimezoneChange());
895 ServiceRegistry* RenderProcessHostImpl::GetServiceRegistry() {
896 DCHECK(mojo_application_host_);
897 return mojo_application_host_->service_registry();
900 const base::TimeTicks& RenderProcessHostImpl::GetInitTimeForNavigationMetrics()
901 const {
902 return init_time_;
905 void RenderProcessHostImpl::AddRoute(
906 int32 routing_id,
907 IPC::Listener* listener) {
908 CHECK(!listeners_.Lookup(routing_id))
909 << "Found Routing ID Conflict: " << routing_id;
910 listeners_.AddWithID(listener, routing_id);
913 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
914 DCHECK(listeners_.Lookup(routing_id) != NULL);
915 listeners_.Remove(routing_id);
917 #if defined(OS_WIN)
918 // Dump the handle table if handle auditing is enabled.
919 const base::CommandLine& browser_command_line =
920 *base::CommandLine::ForCurrentProcess();
921 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
922 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
923 DumpHandles();
925 // We wait to close the channels until the child process has finished
926 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
927 return;
929 #endif
930 // Keep the one renderer thread around forever in single process mode.
931 if (!run_renderer_in_process())
932 Cleanup();
935 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
936 observers_.AddObserver(observer);
939 void RenderProcessHostImpl::RemoveObserver(
940 RenderProcessHostObserver* observer) {
941 observers_.RemoveObserver(observer);
944 void RenderProcessHostImpl::ReceivedBadMessage() {
945 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
946 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
947 return;
949 if (run_renderer_in_process()) {
950 // In single process mode it is better if we don't suicide but just
951 // crash.
952 CHECK(false);
954 // We kill the renderer but don't include a NOTREACHED, because we want the
955 // browser to try to survive when it gets illegal messages from the renderer.
956 base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
957 false);
960 void RenderProcessHostImpl::WidgetRestored() {
961 // Verify we were properly backgrounded.
962 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
963 visible_widgets_++;
964 SetBackgrounded(false);
967 void RenderProcessHostImpl::WidgetHidden() {
968 // On startup, the browser will call Hide
969 if (backgrounded_)
970 return;
972 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
973 visible_widgets_--;
974 DCHECK_GE(visible_widgets_, 0);
975 if (visible_widgets_ == 0) {
976 DCHECK(!backgrounded_);
977 SetBackgrounded(true);
981 int RenderProcessHostImpl::VisibleWidgetCount() const {
982 return visible_widgets_;
985 bool RenderProcessHostImpl::IsIsolatedGuest() const {
986 return is_isolated_guest_;
989 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
990 return storage_partition_impl_;
993 static void AppendCompositorCommandLineFlags(base::CommandLine* command_line) {
994 if (IsPinchVirtualViewportEnabled())
995 command_line->AppendSwitch(cc::switches::kEnablePinchVirtualViewport);
997 if (IsDelegatedRendererEnabled())
998 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
1000 if (IsImplSidePaintingEnabled()) {
1001 command_line->AppendSwitch(switches::kEnableImplSidePainting);
1002 command_line->AppendSwitchASCII(
1003 switches::kNumRasterThreads,
1004 base::IntToString(NumberOfRendererRasterThreads()));
1007 if (IsGpuRasterizationEnabled())
1008 command_line->AppendSwitch(switches::kEnableGpuRasterization);
1010 if (IsForceGpuRasterizationEnabled())
1011 command_line->AppendSwitch(switches::kForceGpuRasterization);
1013 // Appending disable-gpu-feature switches due to software rendering list.
1014 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
1015 DCHECK(gpu_data_manager);
1016 gpu_data_manager->AppendRendererCommandLine(command_line);
1019 void RenderProcessHostImpl::AppendRendererCommandLine(
1020 base::CommandLine* command_line) const {
1021 // Pass the process type first, so it shows first in process listings.
1022 command_line->AppendSwitchASCII(switches::kProcessType,
1023 switches::kRendererProcess);
1025 // Now send any options from our own command line we want to propagate.
1026 const base::CommandLine& browser_command_line =
1027 *base::CommandLine::ForCurrentProcess();
1028 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
1030 // Pass on the browser locale.
1031 const std::string locale =
1032 GetContentClient()->browser()->GetApplicationLocale();
1033 command_line->AppendSwitchASCII(switches::kLang, locale);
1035 // If we run base::FieldTrials, we want to pass to their state to the
1036 // renderer so that it can act in accordance with each state, or record
1037 // histograms relating to the base::FieldTrial states.
1038 std::string field_trial_states;
1039 base::FieldTrialList::StatesToString(&field_trial_states);
1040 if (!field_trial_states.empty()) {
1041 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1042 field_trial_states);
1045 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1046 command_line, GetID());
1048 if (IsPinchToZoomEnabled())
1049 command_line->AppendSwitch(switches::kEnablePinch);
1051 #if defined(OS_WIN)
1052 command_line->AppendSwitchASCII(switches::kDeviceScaleFactor,
1053 base::DoubleToString(gfx::GetDPIScale()));
1054 #endif
1056 AppendCompositorCommandLineFlags(command_line);
1059 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1060 const base::CommandLine& browser_cmd,
1061 base::CommandLine* renderer_cmd) const {
1062 // Propagate the following switches to the renderer command line (along
1063 // with any associated values) if present in the browser command line.
1064 static const char* const kSwitchNames[] = {
1065 switches::kAllowInsecureWebSocketFromHttpsOrigin,
1066 switches::kAllowLoopbackInPeerConnection,
1067 switches::kAudioBufferSize,
1068 switches::kAuditAllHandles,
1069 switches::kAuditHandles,
1070 switches::kBlinkPlatformLogChannels,
1071 switches::kBlockCrossSiteDocuments,
1072 switches::kDefaultTileWidth,
1073 switches::kDefaultTileHeight,
1074 switches::kDisable3DAPIs,
1075 switches::kDisableAcceleratedVideoDecode,
1076 switches::kDisableApplicationCache,
1077 switches::kDisableBlinkScheduler,
1078 switches::kDisableBreakpad,
1079 switches::kDisablePreferCompositingToLCDText,
1080 switches::kDisableCompositingForTransition,
1081 switches::kDisableDatabases,
1082 switches::kDisableDirectNPAPIRequests,
1083 switches::kDisableDisplayList2dCanvas,
1084 switches::kDisableDistanceFieldText,
1085 switches::kDisableFileSystem,
1086 switches::kDisableGpuCompositing,
1087 switches::kDisableGpuVsync,
1088 switches::kDisableLowResTiling,
1089 switches::kDisableHistogramCustomizer,
1090 switches::kDisableLCDText,
1091 switches::kDisableLayerSquashing,
1092 switches::kDisableLocalStorage,
1093 switches::kDisableLogging,
1094 switches::kDisableMediaSource,
1095 switches::kDisableOverlayScrollbar,
1096 switches::kDisablePinch,
1097 switches::kDisablePrefixedEncryptedMedia,
1098 switches::kDisableSeccompFilterSandbox,
1099 switches::kDisableSessionStorage,
1100 switches::kDisableSharedWorkers,
1101 switches::kDisableSVG1DOM,
1102 switches::kDisableThreadedCompositing,
1103 switches::kDisableThreadedScrolling,
1104 switches::kDisableTouchAdjustment,
1105 switches::kDisableTouchDragDrop,
1106 switches::kDisableTouchEditing,
1107 switches::kDisableV8IdleNotificationAfterCommit,
1108 switches::kDisableZeroCopy,
1109 switches::kDomAutomationController,
1110 switches::kEnableAcceleratedJpegDecoding,
1111 switches::kEnableBeginFrameScheduling,
1112 switches::kEnableBleedingEdgeRenderingFastPaths,
1113 switches::kEnableBrowserSideNavigation,
1114 switches::kEnablePreferCompositingToLCDText,
1115 switches::kEnableCompositingForTransition,
1116 switches::kEnableCredentialManagerAPI,
1117 switches::kEnableDeferredImageDecoding,
1118 switches::kEnableDisplayList2dCanvas,
1119 switches::kEnableDistanceFieldText,
1120 switches::kEnableEncryptedMedia,
1121 switches::kEnableExperimentalCanvasFeatures,
1122 switches::kEnableExperimentalWebPlatformFeatures,
1123 switches::kEnableGPUClientLogging,
1124 switches::kEnableGpuClientTracing,
1125 switches::kEnableGPUServiceLogging,
1126 switches::kEnableLowResTiling,
1127 switches::kEnableInbandTextTracks,
1128 switches::kEnableLCDText,
1129 switches::kEnableLayerSquashing,
1130 switches::kEnableLogging,
1131 switches::kEnableMemoryBenchmarking,
1132 switches::kEnableNetworkInformation,
1133 switches::kEnableOneCopy,
1134 switches::kEnableOverlayFullscreenVideo,
1135 switches::kEnableOverlayScrollbar,
1136 switches::kEnableOverscrollNotifications,
1137 switches::kEnablePinch,
1138 switches::kEnablePreciseMemoryInfo,
1139 switches::kEnableRendererMojoChannel,
1140 switches::kEnableSeccompFilterSandbox,
1141 switches::kEnableSkiaBenchmarking,
1142 switches::kEnableSmoothScrolling,
1143 switches::kEnableStatsTable,
1144 switches::kEnableStrictSiteIsolation,
1145 switches::kEnableThreadedCompositing,
1146 switches::kEnableTouchDragDrop,
1147 switches::kEnableTouchEditing,
1148 switches::kEnableV8IdleNotificationAfterCommit,
1149 switches::kEnableViewport,
1150 switches::kEnableViewportMeta,
1151 switches::kEnableVtune,
1152 switches::kEnableWebGLDraftExtensions,
1153 switches::kEnableWebGLImageChromium,
1154 switches::kEnableWebMIDI,
1155 switches::kEnableZeroCopy,
1156 switches::kForceDeviceScaleFactor,
1157 switches::kFullMemoryCrashReport,
1158 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
1159 switches::kIPCConnectionTimeout,
1160 switches::kJavaScriptFlags,
1161 switches::kLoggingLevel,
1162 switches::kMainFrameResizesAreOrientationChanges,
1163 switches::kMaxUntiledLayerWidth,
1164 switches::kMaxUntiledLayerHeight,
1165 switches::kMemoryMetrics,
1166 switches::kNoReferrers,
1167 switches::kNoSandbox,
1168 switches::kPpapiInProcess,
1169 switches::kProfilerTiming,
1170 switches::kReduceSecurityForTesting,
1171 switches::kRegisterPepperPlugins,
1172 switches::kRendererAssertTest,
1173 switches::kRendererStartupDialog,
1174 switches::kShowPaintRects,
1175 switches::kSitePerProcess,
1176 switches::kStatsCollectionController,
1177 switches::kTestType,
1178 switches::kTouchEvents,
1179 switches::kTraceToConsole,
1180 switches::kUseDiscardableMemory,
1181 // This flag needs to be propagated to the renderer process for
1182 // --in-process-webgl.
1183 switches::kUseGL,
1184 switches::kUseMobileUserAgent,
1185 switches::kV,
1186 switches::kVideoThreads,
1187 switches::kVModule,
1188 // Please keep these in alphabetical order. Compositor switches here should
1189 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1190 cc::switches::kCompositeToMailbox,
1191 cc::switches::kDisableCompositedAntialiasing,
1192 cc::switches::kDisableMainFrameBeforeActivation,
1193 cc::switches::kDisableThreadedAnimation,
1194 cc::switches::kEnableGpuBenchmarking,
1195 cc::switches::kEnableMainFrameBeforeActivation,
1196 cc::switches::kEnableTopControlsPositionCalculation,
1197 cc::switches::kMaxTilesForInterestArea,
1198 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1199 cc::switches::kShowCompositedLayerBorders,
1200 cc::switches::kShowFPSCounter,
1201 cc::switches::kShowLayerAnimationBounds,
1202 cc::switches::kShowNonOccludingRects,
1203 cc::switches::kShowOccludingRects,
1204 cc::switches::kShowPropertyChangedRects,
1205 cc::switches::kShowReplicaScreenSpaceRects,
1206 cc::switches::kShowScreenSpaceRects,
1207 cc::switches::kShowSurfaceDamageRects,
1208 cc::switches::kSlowDownRasterScaleFactor,
1209 cc::switches::kStrictLayerPropertyChangeChecking,
1210 cc::switches::kTopControlsHeight,
1211 cc::switches::kTopControlsHideThreshold,
1212 cc::switches::kTopControlsShowThreshold,
1213 #if defined(ENABLE_PLUGINS)
1214 switches::kEnablePepperTesting,
1215 switches::kEnablePluginPowerSaver,
1216 #endif
1217 #if defined(ENABLE_WEBRTC)
1218 switches::kDisableAudioTrackProcessing,
1219 switches::kDisableWebRtcHWDecoding,
1220 switches::kDisableWebRtcHWEncoding,
1221 switches::kEnableWebRtcHWVp8Encoding,
1222 switches::kEnableWebRtcHWH264Encoding,
1223 #endif
1224 switches::kLowEndDeviceMode,
1225 #if defined(OS_ANDROID)
1226 switches::kDisableGestureRequirementForMediaPlayback,
1227 switches::kDisableWebRTC,
1228 switches::kEnableSpeechRecognition,
1229 switches::kMediaDrmEnableNonCompositing,
1230 switches::kNetworkCountryIso,
1231 switches::kDisableWebAudio,
1232 switches::kRendererWaitForJavaDebugger,
1233 #endif
1234 #if defined(OS_MACOSX)
1235 // Allow this to be set when invoking the browser and relayed along.
1236 switches::kEnableSandboxLogging,
1237 #endif
1238 #if defined(OS_MACOSX) && !defined(OS_IOS)
1239 switches::kEnableThreadedEventHandlingMac,
1240 #endif
1241 #if defined(OS_WIN)
1242 switches::kDisableDirectWrite,
1243 switches::kEnableWin32kRendererLockDown,
1244 #endif
1245 #if defined(OS_CHROMEOS)
1246 switches::kDisableVaapiAcceleratedVideoEncode,
1247 #endif
1249 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1250 arraysize(kSwitchNames));
1252 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1253 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1254 // Pass kTraceStartup switch to renderer only if startup tracing has not
1255 // finished.
1256 renderer_cmd->AppendSwitchASCII(
1257 switches::kTraceStartup,
1258 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1261 // Disable databases in incognito mode.
1262 if (GetBrowserContext()->IsOffTheRecord() &&
1263 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1264 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1267 // Enforce the extra command line flags for impl-side painting.
1268 if (IsImplSidePaintingEnabled() &&
1269 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1270 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1272 // Add kWaitForDebugger to let renderer process wait for a debugger.
1273 if (browser_cmd.HasSwitch(switches::kWaitForDebuggerChildren)) {
1274 // Look to pass-on the kWaitForDebugger flag.
1275 std::string value =
1276 browser_cmd.GetSwitchValueASCII(switches::kWaitForDebuggerChildren);
1277 if (value.empty() || value == switches::kRendererProcess) {
1278 renderer_cmd->AppendSwitch(switches::kWaitForDebugger);
1283 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1284 if (run_renderer_in_process())
1285 return base::GetCurrentProcessHandle();
1287 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1288 return base::kNullProcessHandle;
1290 return child_process_launcher_->GetProcess().Handle();
1293 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1294 if (run_renderer_in_process())
1295 return false; // Single process mode never shutdown the renderer.
1297 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1298 return false;
1300 if (!child_process_launcher_.get() ||
1301 child_process_launcher_->IsStarting() ||
1302 !GetHandle())
1303 return false; // Render process hasn't started or is probably crashed.
1305 // Test if there's an unload listener.
1306 // NOTE: It's possible that an onunload listener may be installed
1307 // while we're shutting down, so there's a small race here. Given that
1308 // the window is small, it's unlikely that the web page has much
1309 // state that will be lost by not calling its unload handlers properly.
1310 if (!SuddenTerminationAllowed())
1311 return false;
1313 if (worker_ref_count_ != 0) {
1314 if (survive_for_worker_start_time_.is_null())
1315 survive_for_worker_start_time_ = base::TimeTicks::Now();
1316 return false;
1319 // Set this before ProcessDied() so observers can tell if the render process
1320 // died due to fast shutdown versus another cause.
1321 fast_shutdown_started_ = true;
1323 ProcessDied(false /* already_dead */);
1324 return true;
1327 void RenderProcessHostImpl::DumpHandles() {
1328 #if defined(OS_WIN)
1329 Send(new ChildProcessMsg_DumpHandles());
1330 #else
1331 NOTIMPLEMENTED();
1332 #endif
1335 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1336 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1337 if (!channel_) {
1338 if (!is_initialized_) {
1339 queued_messages_.push(msg);
1340 return true;
1341 } else {
1342 delete msg;
1343 return false;
1347 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1348 queued_messages_.push(msg);
1349 return true;
1352 return channel_->Send(msg);
1355 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1356 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1357 // we ignore incoming messages.
1359 if (deleting_soon_ || fast_shutdown_started_)
1360 return false;
1362 mark_child_process_activity_time();
1363 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1364 // Dispatch control messages.
1365 IPC_BEGIN_MESSAGE_MAP(RenderProcessHostImpl, msg)
1366 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1367 OnShutdownRequest)
1368 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1369 OnDumpHandlesDone)
1370 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1371 SuddenTerminationChanged)
1372 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1373 OnUserMetricsRecordAction)
1374 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1375 IPC_MESSAGE_HANDLER(ViewHostMsg_Close_ACK, OnCloseACK)
1376 #if defined(ENABLE_WEBRTC)
1377 IPC_MESSAGE_HANDLER(AecDumpMsg_RegisterAecDumpConsumer,
1378 OnRegisterAecDumpConsumer)
1379 IPC_MESSAGE_HANDLER(AecDumpMsg_UnregisterAecDumpConsumer,
1380 OnUnregisterAecDumpConsumer)
1381 #endif
1382 // Adding single handlers for your service here is fine, but once your
1383 // service needs more than one handler, please extract them into a new
1384 // message filter and add that filter to CreateMessageFilters().
1385 IPC_END_MESSAGE_MAP()
1387 return true;
1390 // Dispatch incoming messages to the appropriate IPC::Listener.
1391 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1392 if (!listener) {
1393 if (msg.is_sync()) {
1394 // The listener has gone away, so we must respond or else the caller will
1395 // hang waiting for a reply.
1396 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1397 reply->set_reply_error();
1398 Send(reply);
1400 return true;
1402 return listener->OnMessageReceived(msg);
1405 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1406 #if defined(IPC_MESSAGE_LOG_ENABLED)
1407 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1408 IPC::Logging::GetInstance()->Enabled()));
1409 #endif
1411 tracked_objects::ThreadData::Status status =
1412 tracked_objects::ThreadData::status();
1413 Send(new ChildProcessMsg_SetProfilerStatus(status));
1416 void RenderProcessHostImpl::OnChannelError() {
1417 ProcessDied(true /* already_dead */);
1420 void RenderProcessHostImpl::OnBadMessageReceived(const IPC::Message& message) {
1421 // Message de-serialization failed. We consider this a capital crime. Kill the
1422 // renderer if we have one.
1423 LOG(ERROR) << "bad message " << message.type() << " terminating renderer.";
1424 BrowserChildProcessHostImpl::HistogramBadMessageTerminated(
1425 PROCESS_TYPE_RENDERER);
1426 ReceivedBadMessage();
1429 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1430 return browser_context_;
1433 bool RenderProcessHostImpl::InSameStoragePartition(
1434 StoragePartition* partition) const {
1435 return storage_partition_impl_ == partition;
1438 int RenderProcessHostImpl::GetID() const {
1439 return id_;
1442 bool RenderProcessHostImpl::HasConnection() const {
1443 return channel_.get() != NULL;
1446 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1447 ignore_input_events_ = ignore_input_events;
1450 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1451 return ignore_input_events_;
1454 void RenderProcessHostImpl::Cleanup() {
1455 // If within_process_died_observer_ is true, one of our observers performed an
1456 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1457 // delay the destruction until all of the observer callbacks have been made,
1458 // and guarantee that the RenderProcessHostDestroyed observer callback is
1459 // always the last callback fired.
1460 if (within_process_died_observer_) {
1461 delayed_cleanup_needed_ = true;
1462 return;
1464 delayed_cleanup_needed_ = false;
1466 // Records the time when the process starts surviving for workers for UMA.
1467 if (listeners_.IsEmpty() && worker_ref_count_ > 0 &&
1468 survive_for_worker_start_time_.is_null()) {
1469 survive_for_worker_start_time_ = base::TimeTicks::Now();
1472 // When there are no other owners of this object, we can delete ourselves.
1473 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1474 if (!survive_for_worker_start_time_.is_null()) {
1475 UMA_HISTOGRAM_LONG_TIMES(
1476 "SharedWorker.RendererSurviveForWorkerTime",
1477 base::TimeTicks::Now() - survive_for_worker_start_time_);
1479 // We cannot clean up twice; if this fails, there is an issue with our
1480 // control flow.
1481 DCHECK(!deleting_soon_);
1483 DCHECK_EQ(0, pending_views_);
1484 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1485 observers_,
1486 RenderProcessHostDestroyed(this));
1487 NotificationService::current()->Notify(
1488 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1489 Source<RenderProcessHost>(this),
1490 NotificationService::NoDetails());
1492 #ifndef NDEBUG
1493 is_self_deleted_ = true;
1494 #endif
1495 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1496 deleting_soon_ = true;
1497 // It's important not to wait for the DeleteTask to delete the channel
1498 // proxy. Kill it off now. That way, in case the profile is going away, the
1499 // rest of the objects attached to this RenderProcessHost start going
1500 // away first, since deleting the channel proxy will post a
1501 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1502 channel_.reset();
1503 gpu_message_filter_ = NULL;
1504 message_port_message_filter_ = NULL;
1505 RemoveUserData(kSessionStorageHolderKey);
1507 // Remove ourself from the list of renderer processes so that we can't be
1508 // reused in between now and when the Delete task runs.
1509 UnregisterHost(GetID());
1513 void RenderProcessHostImpl::AddPendingView() {
1514 pending_views_++;
1517 void RenderProcessHostImpl::RemovePendingView() {
1518 DCHECK(pending_views_);
1519 pending_views_--;
1522 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1523 sudden_termination_allowed_ = enabled;
1526 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1527 return sudden_termination_allowed_;
1530 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1531 return base::TimeTicks::Now() - child_process_activity_time_;
1534 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1535 widget_helper_->ResumeRequestsForView(route_id);
1538 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1539 FilterURL(this, empty_allowed, url);
1542 #if defined(ENABLE_WEBRTC)
1543 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1544 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1545 // Enable AEC dump for each registered consumer.
1546 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
1547 it != aec_dump_consumers_.end(); ++it) {
1548 EnableAecDumpForId(file, *it);
1552 void RenderProcessHostImpl::DisableAecDump() {
1553 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1554 // Posting on the FILE thread and then replying back on the UI thread is only
1555 // for avoiding races between enable and disable. Nothing is done on the FILE
1556 // thread.
1557 BrowserThread::PostTaskAndReply(
1558 BrowserThread::FILE, FROM_HERE,
1559 base::Bind(&DisableAecDumpOnFileThread),
1560 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1561 weak_factory_.GetWeakPtr()));
1564 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1565 base::Callback<void(const std::string&)> callback) {
1566 webrtc_log_message_callback_ = callback;
1569 RenderProcessHostImpl::WebRtcStopRtpDumpCallback
1570 RenderProcessHostImpl::StartRtpDump(
1571 bool incoming,
1572 bool outgoing,
1573 const WebRtcRtpPacketCallback& packet_callback) {
1574 if (!p2p_socket_dispatcher_host_.get())
1575 return WebRtcStopRtpDumpCallback();
1577 BrowserThread::PostTask(BrowserThread::IO,
1578 FROM_HERE,
1579 base::Bind(&P2PSocketDispatcherHost::StartRtpDump,
1580 p2p_socket_dispatcher_host_,
1581 incoming,
1582 outgoing,
1583 packet_callback));
1585 if (stop_rtp_dump_callback_.is_null()) {
1586 stop_rtp_dump_callback_ =
1587 base::Bind(&P2PSocketDispatcherHost::StopRtpDumpOnUIThread,
1588 p2p_socket_dispatcher_host_);
1590 return stop_rtp_dump_callback_;
1592 #endif
1594 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1595 return channel_.get();
1598 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1599 channel_->AddFilter(filter->GetFilter());
1602 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1603 if (static_cast<size_t>(GetActiveViewCount()) == count)
1604 return FastShutdownIfPossible();
1605 return false;
1608 bool RenderProcessHostImpl::FastShutdownStarted() const {
1609 return fast_shutdown_started_;
1612 // static
1613 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1614 g_all_hosts.Get().AddWithID(host, host_id);
1617 // static
1618 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1619 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1620 if (!host)
1621 return;
1623 g_all_hosts.Get().Remove(host_id);
1625 // Look up the map of site to process for the given browser_context,
1626 // in case we need to remove this process from it. It will be registered
1627 // under any sites it rendered that use process-per-site mode.
1628 SiteProcessMap* map =
1629 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1630 map->RemoveProcess(host);
1633 // static
1634 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1635 bool empty_allowed,
1636 GURL* url) {
1637 ChildProcessSecurityPolicyImpl* policy =
1638 ChildProcessSecurityPolicyImpl::GetInstance();
1640 if (empty_allowed && url->is_empty())
1641 return;
1643 // The browser process should never hear the swappedout:// URL from any
1644 // of the renderer's messages. Check for this in debug builds, but don't
1645 // let it crash a release browser.
1646 DCHECK(GURL(kSwappedOutURL) != *url);
1648 if (!url->is_valid()) {
1649 // Have to use about:blank for the denied case, instead of an empty GURL.
1650 // This is because the browser treats navigation to an empty GURL as a
1651 // navigation to the home page. This is often a privileged page
1652 // (chrome://newtab/) which is exactly what we don't want.
1653 *url = GURL(url::kAboutBlankURL);
1654 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1655 return;
1658 if (url->SchemeIs(url::kAboutScheme)) {
1659 // The renderer treats all URLs in the about: scheme as being about:blank.
1660 // Canonicalize about: URLs to about:blank.
1661 *url = GURL(url::kAboutBlankURL);
1662 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1665 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1666 // cannot swap processes or grant bindings.
1667 bool non_web_url_in_guest = rph->IsIsolatedGuest() &&
1668 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1670 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1671 // If this renderer is not permitted to request this URL, we invalidate the
1672 // URL. This prevents us from storing the blocked URL and becoming confused
1673 // later.
1674 VLOG(1) << "Blocked URL " << url->spec();
1675 *url = GURL(url::kAboutBlankURL);
1676 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1680 // static
1681 bool RenderProcessHostImpl::IsSuitableHost(
1682 RenderProcessHost* host,
1683 BrowserContext* browser_context,
1684 const GURL& site_url) {
1685 if (run_renderer_in_process())
1686 return true;
1688 if (host->GetBrowserContext() != browser_context)
1689 return false;
1691 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1692 // and non-guest storage gets mixed. In the future, we might consider enabling
1693 // the sharing of guests, in this case this check should be removed and
1694 // InSameStoragePartition should handle the possible sharing.
1695 if (host->IsIsolatedGuest())
1696 return false;
1698 // Check whether the given host and the intended site_url will be using the
1699 // same StoragePartition, since a RenderProcessHost can only support a single
1700 // StoragePartition. This is relevant for packaged apps and isolated sites.
1701 StoragePartition* dest_partition =
1702 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1703 if (!host->InSameStoragePartition(dest_partition))
1704 return false;
1706 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1707 host->GetID()) !=
1708 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1709 browser_context, site_url)) {
1710 return false;
1713 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1716 // static
1717 bool RenderProcessHost::run_renderer_in_process() {
1718 return g_run_renderer_in_process_;
1721 // static
1722 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1723 g_run_renderer_in_process_ = value;
1725 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
1726 if (value) {
1727 if (!command_line->HasSwitch(switches::kLang)) {
1728 // Modify the current process' command line to include the browser locale,
1729 // as the renderer expects this flag to be set.
1730 const std::string locale =
1731 GetContentClient()->browser()->GetApplicationLocale();
1732 command_line->AppendSwitchASCII(switches::kLang, locale);
1734 // TODO(piman): we should really send configuration through bools rather
1735 // than by parsing strings, i.e. sending an IPC rather than command line
1736 // args. crbug.com/314909
1737 AppendCompositorCommandLineFlags(command_line);
1741 // static
1742 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1743 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1744 return iterator(g_all_hosts.Pointer());
1747 // static
1748 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1749 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1750 return g_all_hosts.Get().Lookup(render_process_id);
1753 // static
1754 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1755 BrowserContext* browser_context, const GURL& url) {
1756 // Experimental:
1757 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1758 // try to reuse renderer processes when over the limit. (We could allow pages
1759 // from the same site to share, if we knew what the given process was
1760 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1761 // resource exhaustion issues if too many sites are open at once.
1762 const base::CommandLine& command_line =
1763 *base::CommandLine::ForCurrentProcess();
1764 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1765 command_line.HasSwitch(switches::kSitePerProcess))
1766 return false;
1768 if (run_renderer_in_process())
1769 return true;
1771 // NOTE: Sometimes it's necessary to create more render processes than
1772 // GetMaxRendererProcessCount(), for instance when we want to create
1773 // a renderer process for a browser context that has no existing
1774 // renderers. This is OK in moderation, since the
1775 // GetMaxRendererProcessCount() is conservative.
1776 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1777 return true;
1779 return GetContentClient()->browser()->
1780 ShouldTryToUseExistingProcessHost(browser_context, url);
1783 // static
1784 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1785 BrowserContext* browser_context,
1786 const GURL& site_url) {
1787 // First figure out which existing renderers we can use.
1788 std::vector<RenderProcessHost*> suitable_renderers;
1789 suitable_renderers.reserve(g_all_hosts.Get().size());
1791 iterator iter(AllHostsIterator());
1792 while (!iter.IsAtEnd()) {
1793 if (GetContentClient()->browser()->MayReuseHost(iter.GetCurrentValue()) &&
1794 RenderProcessHostImpl::IsSuitableHost(
1795 iter.GetCurrentValue(),
1796 browser_context, site_url)) {
1797 suitable_renderers.push_back(iter.GetCurrentValue());
1799 iter.Advance();
1802 // Now pick a random suitable renderer, if we have any.
1803 if (!suitable_renderers.empty()) {
1804 int suitable_count = static_cast<int>(suitable_renderers.size());
1805 int random_index = base::RandInt(0, suitable_count - 1);
1806 return suitable_renderers[random_index];
1809 return NULL;
1812 // static
1813 bool RenderProcessHost::ShouldUseProcessPerSite(
1814 BrowserContext* browser_context,
1815 const GURL& url) {
1816 // Returns true if we should use the process-per-site model. This will be
1817 // the case if the --process-per-site switch is specified, or in
1818 // process-per-site-instance for particular sites (e.g., WebUI).
1819 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1820 const base::CommandLine& command_line =
1821 *base::CommandLine::ForCurrentProcess();
1822 if (command_line.HasSwitch(switches::kProcessPerSite))
1823 return true;
1825 // We want to consolidate particular sites like WebUI even when we are using
1826 // the process-per-tab or process-per-site-instance models.
1827 // Note: DevTools pages have WebUI type but should not reuse the same host.
1828 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1829 browser_context, url) &&
1830 !url.SchemeIs(kChromeDevToolsScheme)) {
1831 return true;
1834 // Otherwise let the content client decide, defaulting to false.
1835 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1836 url);
1839 // static
1840 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1841 BrowserContext* browser_context,
1842 const GURL& url) {
1843 // Look up the map of site to process for the given browser_context.
1844 SiteProcessMap* map =
1845 GetSiteProcessMapForBrowserContext(browser_context);
1847 // See if we have an existing process with appropriate bindings for this site.
1848 // If not, the caller should create a new process and register it.
1849 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1850 .possibly_invalid_spec();
1851 RenderProcessHost* host = map->FindProcess(site);
1852 if (host && (!GetContentClient()->browser()->MayReuseHost(host) ||
1853 !IsSuitableHost(host, browser_context, url))) {
1854 // The registered process does not have an appropriate set of bindings for
1855 // the url. Remove it from the map so we can register a better one.
1856 RecordAction(
1857 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1858 map->RemoveProcess(host);
1859 host = NULL;
1862 return host;
1865 void RenderProcessHostImpl::RegisterProcessHostForSite(
1866 BrowserContext* browser_context,
1867 RenderProcessHost* process,
1868 const GURL& url) {
1869 // Look up the map of site to process for the given browser_context.
1870 SiteProcessMap* map =
1871 GetSiteProcessMapForBrowserContext(browser_context);
1873 // Only register valid, non-empty sites. Empty or invalid sites will not
1874 // use process-per-site mode. We cannot check whether the process has
1875 // appropriate bindings here, because the bindings have not yet been granted.
1876 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1877 .possibly_invalid_spec();
1878 if (!site.empty())
1879 map->RegisterProcess(site, process);
1882 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1883 // Our child process has died. If we didn't expect it, it's a crash.
1884 // In any case, we need to let everyone know it's gone.
1885 // The OnChannelError notification can fire multiple times due to nested sync
1886 // calls to a renderer. If we don't have a valid channel here it means we
1887 // already handled the error.
1889 // It should not be possible for us to be called re-entrantly.
1890 DCHECK(!within_process_died_observer_);
1892 // It should not be possible for a process death notification to come in while
1893 // we are dying.
1894 DCHECK(!deleting_soon_);
1896 // child_process_launcher_ can be NULL in single process mode or if fast
1897 // termination happened.
1898 int exit_code = 0;
1899 base::TerminationStatus status =
1900 child_process_launcher_.get() ?
1901 child_process_launcher_->GetChildTerminationStatus(already_dead,
1902 &exit_code) :
1903 base::TERMINATION_STATUS_NORMAL_TERMINATION;
1905 RendererClosedDetails details(GetHandle(), status, exit_code);
1906 mojo_application_host_->WillDestroySoon();
1908 child_process_launcher_.reset();
1909 channel_.reset();
1911 within_process_died_observer_ = true;
1912 NotificationService::current()->Notify(
1913 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1914 Source<RenderProcessHost>(this),
1915 Details<RendererClosedDetails>(&details));
1916 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1917 observers_,
1918 RenderProcessExited(this, status, exit_code));
1919 within_process_died_observer_ = false;
1921 gpu_message_filter_ = NULL;
1922 message_port_message_filter_ = NULL;
1923 RemoveUserData(kSessionStorageHolderKey);
1925 IDMap<IPC::Listener>::iterator iter(&listeners_);
1926 while (!iter.IsAtEnd()) {
1927 iter.GetCurrentValue()->OnMessageReceived(
1928 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1929 static_cast<int>(status),
1930 exit_code));
1931 iter.Advance();
1934 mojo_application_host_.reset(new MojoApplicationHost);
1936 // It's possible that one of the calls out to the observers might have caused
1937 // this object to be no longer needed.
1938 if (delayed_cleanup_needed_)
1939 Cleanup();
1941 // This object is not deleted at this point and might be reused later.
1942 // TODO(darin): clean this up
1945 int RenderProcessHostImpl::GetActiveViewCount() {
1946 int num_active_views = 0;
1947 scoped_ptr<RenderWidgetHostIterator> widgets(
1948 RenderWidgetHost::GetRenderWidgetHosts());
1949 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1950 // Count only RenderWidgetHosts in this process.
1951 if (widget->GetProcess()->GetID() == GetID())
1952 num_active_views++;
1954 return num_active_views;
1957 // Frame subscription API for this class is for accelerated composited path
1958 // only. These calls are redirected to GpuMessageFilter.
1959 void RenderProcessHostImpl::BeginFrameSubscription(
1960 int route_id,
1961 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1962 if (!gpu_message_filter_)
1963 return;
1964 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1965 &GpuMessageFilter::BeginFrameSubscription,
1966 gpu_message_filter_,
1967 route_id, base::Passed(&subscriber)));
1970 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1971 if (!gpu_message_filter_)
1972 return;
1973 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1974 &GpuMessageFilter::EndFrameSubscription,
1975 gpu_message_filter_,
1976 route_id));
1979 #if defined(ENABLE_WEBRTC)
1980 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
1981 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1982 if (!webrtc_log_message_callback_.is_null())
1983 webrtc_log_message_callback_.Run(message);
1985 #endif
1987 void RenderProcessHostImpl::ReleaseOnCloseACK(
1988 RenderProcessHost* host,
1989 const SessionStorageNamespaceMap& sessions,
1990 int view_route_id) {
1991 DCHECK(host);
1992 if (sessions.empty())
1993 return;
1994 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
1995 (host->GetUserData(kSessionStorageHolderKey));
1996 if (!holder) {
1997 holder = new SessionStorageHolder();
1998 host->SetUserData(
1999 kSessionStorageHolderKey,
2000 holder);
2002 holder->Hold(sessions, view_route_id);
2005 void RenderProcessHostImpl::OnShutdownRequest() {
2006 // Don't shut down if there are active RenderViews, or if there are pending
2007 // RenderViews being swapped back in.
2008 // In single process mode, we never shutdown the renderer.
2009 int num_active_views = GetActiveViewCount();
2010 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2011 return;
2013 // Notify any contents that might have swapped out renderers from this
2014 // process. They should not attempt to swap them back in.
2015 NotificationService::current()->Notify(
2016 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2017 Source<RenderProcessHost>(this),
2018 NotificationService::NoDetails());
2020 mojo_application_host_->WillDestroySoon();
2022 Send(new ChildProcessMsg_Shutdown());
2025 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2026 SetSuddenTerminationAllowed(enabled);
2029 void RenderProcessHostImpl::OnDumpHandlesDone() {
2030 Cleanup();
2033 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2034 // Note: we always set the backgrounded_ value. If the process is NULL
2035 // (and hence hasn't been created yet), we will set the process priority
2036 // later when we create the process.
2037 backgrounded_ = backgrounded;
2038 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2039 return;
2041 // Don't background processes which have active audio streams.
2042 if (backgrounded_ && audio_renderer_host_->HasActiveAudio())
2043 return;
2045 #if defined(OS_WIN)
2046 // The cbstext.dll loads as a global GetMessage hook in the browser process
2047 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2048 // background thread. If the UI thread invokes this API just when it is
2049 // intercepted the stack is messed up on return from the interceptor
2050 // which causes random crashes in the browser process. Our hack for now
2051 // is to not invoke the SetPriorityClass API if the dll is loaded.
2052 if (GetModuleHandle(L"cbstext.dll"))
2053 return;
2054 #endif // OS_WIN
2056 // Notify the child process of background state.
2057 Send(new ChildProcessMsg_SetProcessBackgrounded(backgrounded));
2059 #if !defined(OS_WIN)
2060 // Backgrounding may require elevated privileges not available to renderer
2061 // processes, so control backgrounding from the process host.
2063 // Windows Vista+ has a fancy process backgrounding mode that can only be set
2064 // from within the process.
2065 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2066 #endif // !OS_WIN
2069 void RenderProcessHostImpl::OnProcessLaunched() {
2070 // No point doing anything, since this object will be destructed soon. We
2071 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2072 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2073 // properly cleanup.
2074 if (deleting_soon_)
2075 return;
2077 if (child_process_launcher_) {
2078 DCHECK(child_process_launcher_->GetProcess().IsValid());
2079 SetBackgrounded(backgrounded_);
2082 // NOTE: This needs to be before sending queued messages because
2083 // ExtensionService uses this notification to initialize the renderer process
2084 // with state that must be there before any JavaScript executes.
2086 // The queued messages contain such things as "navigate". If this notification
2087 // was after, we can end up executing JavaScript before the initialization
2088 // happens.
2089 NotificationService::current()->Notify(
2090 NOTIFICATION_RENDERER_PROCESS_CREATED,
2091 Source<RenderProcessHost>(this),
2092 NotificationService::NoDetails());
2094 // Allow Mojo to be setup before the renderer sees any Chrome IPC messages.
2095 // This way, Mojo can be safely used from the renderer in response to any
2096 // Chrome IPC message.
2097 mojo_application_host_->Activate(this, GetHandle());
2099 if (channel_mojo_host_)
2100 channel_mojo_host_->OnClientLaunched(GetHandle());
2102 while (!queued_messages_.empty()) {
2103 Send(queued_messages_.front());
2104 queued_messages_.pop();
2107 #if defined(ENABLE_WEBRTC)
2108 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2109 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2110 #endif
2113 scoped_refptr<AudioRendererHost>
2114 RenderProcessHostImpl::audio_renderer_host() const {
2115 return audio_renderer_host_;
2118 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2119 const std::string& action) {
2120 RecordComputedAction(action);
2123 void RenderProcessHostImpl::OnCloseACK(int old_route_id) {
2124 SessionStorageHolder* holder = static_cast<SessionStorageHolder*>
2125 (GetUserData(kSessionStorageHolderKey));
2126 if (!holder)
2127 return;
2128 holder->Release(old_route_id);
2131 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2132 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2135 void RenderProcessHostImpl::OnGpuSwitched() {
2136 // We are updating all widgets including swapped out ones.
2137 scoped_ptr<RenderWidgetHostIterator> widgets(
2138 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2139 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2140 if (!widget->IsRenderView())
2141 continue;
2143 // Skip widgets in other processes.
2144 if (widget->GetProcess()->GetID() != GetID())
2145 continue;
2147 RenderViewHost* rvh = RenderViewHost::From(widget);
2148 rvh->OnWebkitPreferencesChanged();
2152 #if defined(ENABLE_WEBRTC)
2153 void RenderProcessHostImpl::OnRegisterAecDumpConsumer(int id) {
2154 BrowserThread::PostTask(
2155 BrowserThread::UI,
2156 FROM_HERE,
2157 base::Bind(
2158 &RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread,
2159 weak_factory_.GetWeakPtr(),
2160 id));
2163 void RenderProcessHostImpl::OnUnregisterAecDumpConsumer(int id) {
2164 BrowserThread::PostTask(
2165 BrowserThread::UI,
2166 FROM_HERE,
2167 base::Bind(
2168 &RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread,
2169 weak_factory_.GetWeakPtr(),
2170 id));
2173 void RenderProcessHostImpl::RegisterAecDumpConsumerOnUIThread(int id) {
2174 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2175 aec_dump_consumers_.push_back(id);
2176 if (WebRTCInternals::GetInstance()->aec_dump_enabled()) {
2177 EnableAecDumpForId(WebRTCInternals::GetInstance()->aec_dump_file_path(),
2178 id);
2182 void RenderProcessHostImpl::UnregisterAecDumpConsumerOnUIThread(int id) {
2183 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2184 for (std::vector<int>::iterator it = aec_dump_consumers_.begin();
2185 it != aec_dump_consumers_.end(); ++it) {
2186 if (*it == id) {
2187 aec_dump_consumers_.erase(it);
2188 break;
2193 #if defined(OS_WIN)
2194 #define IntToStringType base::IntToString16
2195 #else
2196 #define IntToStringType base::IntToString
2197 #endif
2199 void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
2200 int id) {
2201 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2202 base::FilePath unique_file =
2203 file.AddExtension(IntToStringType(base::GetProcId(GetHandle())))
2204 .AddExtension(IntToStringType(id));
2205 BrowserThread::PostTaskAndReplyWithResult(
2206 BrowserThread::FILE, FROM_HERE,
2207 base::Bind(&CreateAecDumpFileForProcess, unique_file, GetHandle()),
2208 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
2209 weak_factory_.GetWeakPtr(),
2210 id));
2213 #undef IntToStringType
2215 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2216 int id,
2217 IPC::PlatformFileForTransit file_for_transit) {
2218 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2219 return;
2220 Send(new AecDumpMsg_EnableAecDump(id, file_for_transit));
2223 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2224 Send(new AecDumpMsg_DisableAecDump());
2226 #endif
2228 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2229 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2230 ++worker_ref_count_;
2233 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2234 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2235 DCHECK_GT(worker_ref_count_, 0);
2236 --worker_ref_count_;
2237 if (worker_ref_count_ == 0)
2238 Cleanup();
2241 } // namespace content