Implement ServiceWorker::postMessage()
[chromium-blink-merge.git] / content / browser / renderer_host / render_process_host_impl.cc
blobfaa46bd71defa5497aa234391edb0e72cc975a5d
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/lazy_instance.h"
25 #include "base/logging.h"
26 #include "base/metrics/field_trial.h"
27 #include "base/metrics/histogram.h"
28 #include "base/path_service.h"
29 #include "base/platform_file.h"
30 #include "base/rand_util.h"
31 #include "base/stl_util.h"
32 #include "base/strings/string_util.h"
33 #include "base/supports_user_data.h"
34 #include "base/sys_info.h"
35 #include "base/threading/thread.h"
36 #include "base/threading/thread_restrictions.h"
37 #include "base/tracked_objects.h"
38 #include "cc/base/switches.h"
39 #include "content/browser/appcache/appcache_dispatcher_host.h"
40 #include "content/browser/appcache/chrome_appcache_service.h"
41 #include "content/browser/browser_main.h"
42 #include "content/browser/browser_main_loop.h"
43 #include "content/browser/browser_plugin/browser_plugin_geolocation_permission_context.h"
44 #include "content/browser/browser_plugin/browser_plugin_message_filter.h"
45 #include "content/browser/child_process_security_policy_impl.h"
46 #include "content/browser/device_orientation/device_motion_message_filter.h"
47 #include "content/browser/device_orientation/device_orientation_message_filter.h"
48 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
49 #include "content/browser/dom_storage/dom_storage_message_filter.h"
50 #include "content/browser/download/mhtml_generation_manager.h"
51 #include "content/browser/fileapi/chrome_blob_storage_context.h"
52 #include "content/browser/fileapi/fileapi_message_filter.h"
53 #include "content/browser/frame_host/render_frame_message_filter.h"
54 #include "content/browser/gpu/compositor_util.h"
55 #include "content/browser/gpu/gpu_data_manager_impl.h"
56 #include "content/browser/gpu/gpu_process_host.h"
57 #include "content/browser/gpu/shader_disk_cache.h"
58 #include "content/browser/histogram_message_filter.h"
59 #include "content/browser/indexed_db/indexed_db_context_impl.h"
60 #include "content/browser/indexed_db/indexed_db_dispatcher_host.h"
61 #include "content/browser/loader/resource_message_filter.h"
62 #include "content/browser/loader/resource_scheduler_filter.h"
63 #include "content/browser/media/android/browser_demuxer_android.h"
64 #include "content/browser/media/capture/audio_mirroring_manager.h"
65 #include "content/browser/media/media_internals.h"
66 #include "content/browser/message_port_message_filter.h"
67 #include "content/browser/mime_registry_message_filter.h"
68 #include "content/browser/plugin_service_impl.h"
69 #include "content/browser/profiler_message_filter.h"
70 #include "content/browser/quota_dispatcher_host.h"
71 #include "content/browser/renderer_host/clipboard_message_filter.h"
72 #include "content/browser/renderer_host/database_message_filter.h"
73 #include "content/browser/renderer_host/file_utilities_message_filter.h"
74 #include "content/browser/renderer_host/gamepad_browser_message_filter.h"
75 #include "content/browser/renderer_host/gpu_message_filter.h"
76 #include "content/browser/renderer_host/media/audio_input_renderer_host.h"
77 #include "content/browser/renderer_host/media/audio_renderer_host.h"
78 #include "content/browser/renderer_host/media/device_request_message_filter.h"
79 #include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
80 #include "content/browser/renderer_host/media/midi_dispatcher_host.h"
81 #include "content/browser/renderer_host/media/midi_host.h"
82 #include "content/browser/renderer_host/media/peer_connection_tracker_host.h"
83 #include "content/browser/renderer_host/media/video_capture_host.h"
84 #include "content/browser/renderer_host/memory_benchmark_message_filter.h"
85 #include "content/browser/renderer_host/p2p/socket_dispatcher_host.h"
86 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
87 #include "content/browser/renderer_host/pepper/pepper_renderer_connection.h"
88 #include "content/browser/renderer_host/render_message_filter.h"
89 #include "content/browser/renderer_host/render_view_host_delegate.h"
90 #include "content/browser/renderer_host/render_view_host_impl.h"
91 #include "content/browser/renderer_host/render_widget_helper.h"
92 #include "content/browser/renderer_host/render_widget_host_impl.h"
93 #include "content/browser/renderer_host/socket_stream_dispatcher_host.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/screen_orientation/screen_orientation_dispatcher_host.h"
98 #include "content/browser/service_worker/service_worker_context_wrapper.h"
99 #include "content/browser/service_worker/service_worker_dispatcher_host.h"
100 #include "content/browser/shared_worker/shared_worker_message_filter.h"
101 #include "content/browser/speech/input_tag_speech_dispatcher_host.h"
102 #include "content/browser/speech/speech_recognition_dispatcher_host.h"
103 #include "content/browser/storage_partition_impl.h"
104 #include "content/browser/streams/stream_context.h"
105 #include "content/browser/tracing/trace_message_filter.h"
106 #include "content/browser/vibration/vibration_message_filter.h"
107 #include "content/browser/webui/web_ui_controller_factory_registry.h"
108 #include "content/browser/worker_host/worker_message_filter.h"
109 #include "content/browser/worker_host/worker_storage_partition.h"
110 #include "content/common/child_process_host_impl.h"
111 #include "content/common/child_process_messages.h"
112 #include "content/common/content_switches_internal.h"
113 #include "content/common/gpu/gpu_messages.h"
114 #include "content/common/resource_messages.h"
115 #include "content/common/view_messages.h"
116 #include "content/port/browser/render_widget_host_view_frame_subscriber.h"
117 #include "content/public/browser/browser_context.h"
118 #include "content/public/browser/content_browser_client.h"
119 #include "content/public/browser/notification_service.h"
120 #include "content/public/browser/notification_types.h"
121 #include "content/public/browser/render_process_host_factory.h"
122 #include "content/public/browser/render_process_host_observer.h"
123 #include "content/public/browser/render_widget_host.h"
124 #include "content/public/browser/render_widget_host_iterator.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/result_codes.h"
132 #include "content/public/common/sandboxed_process_launcher_delegate.h"
133 #include "content/public/common/url_constants.h"
134 #include "gpu/command_buffer/service/gpu_switches.h"
135 #include "ipc/ipc_channel.h"
136 #include "ipc/ipc_logging.h"
137 #include "ipc/ipc_switches.h"
138 #include "media/base/media_switches.h"
139 #include "net/url_request/url_request_context_getter.h"
140 #include "ppapi/shared_impl/ppapi_switches.h"
141 #include "third_party/skia/include/core/SkBitmap.h"
142 #include "ui/base/ui_base_switches.h"
143 #include "ui/events/event_switches.h"
144 #include "ui/gfx/switches.h"
145 #include "ui/gl/gl_switches.h"
146 #include "ui/native_theme/native_theme_switches.h"
147 #include "webkit/browser/fileapi/sandbox_file_system_backend.h"
148 #include "webkit/common/resource_type.h"
150 #if defined(OS_WIN)
151 #include "base/win/scoped_com_initializer.h"
152 #include "content/common/font_cache_dispatcher_win.h"
153 #include "content/common/sandbox_win.h"
154 #endif
156 #if defined(ENABLE_WEBRTC)
157 #include "content/browser/media/webrtc_internals.h"
158 #include "content/browser/renderer_host/media/media_stream_track_metrics_host.h"
159 #include "content/browser/renderer_host/media/webrtc_identity_service_host.h"
160 #include "content/common/media/media_stream_messages.h"
161 #endif
163 #if defined(USE_MOJO)
164 #include "content/common/mojo/mojo_channel_init.h"
165 #include "content/common/mojo/mojo_messages.h"
166 #include "mojo/embedder/platform_channel_pair.h"
167 #endif
169 extern bool g_exited_main_message_loop;
171 static const char* kSiteProcessMapKeyName = "content_site_process_map";
173 namespace content {
174 namespace {
176 void CacheShaderInfo(int32 id, base::FilePath path) {
177 ShaderCacheFactory::GetInstance()->SetCacheInfo(id, path);
180 void RemoveShaderInfo(int32 id) {
181 ShaderCacheFactory::GetInstance()->RemoveCacheInfo(id);
184 net::URLRequestContext* GetRequestContext(
185 scoped_refptr<net::URLRequestContextGetter> request_context,
186 scoped_refptr<net::URLRequestContextGetter> media_request_context,
187 ResourceType::Type resource_type) {
188 // If the request has resource type of ResourceType::MEDIA, we use a request
189 // context specific to media for handling it because these resources have
190 // specific needs for caching.
191 if (resource_type == ResourceType::MEDIA)
192 return media_request_context->GetURLRequestContext();
193 return request_context->GetURLRequestContext();
196 void GetContexts(
197 ResourceContext* resource_context,
198 scoped_refptr<net::URLRequestContextGetter> request_context,
199 scoped_refptr<net::URLRequestContextGetter> media_request_context,
200 const ResourceHostMsg_Request& request,
201 ResourceContext** resource_context_out,
202 net::URLRequestContext** request_context_out) {
203 *resource_context_out = resource_context;
204 *request_context_out =
205 GetRequestContext(request_context, media_request_context,
206 request.resource_type);
209 #if defined(ENABLE_WEBRTC)
210 // Creates a file used for diagnostic echo canceller recordings for handing
211 // over to the renderer.
212 IPC::PlatformFileForTransit CreateAecDumpFileForProcess(
213 base::FilePath file_path,
214 base::ProcessHandle process) {
215 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
216 base::PlatformFileError error = base::PLATFORM_FILE_OK;
217 base::PlatformFile aec_dump_file = base::CreatePlatformFile(
218 file_path,
219 base::PLATFORM_FILE_OPEN_ALWAYS | base::PLATFORM_FILE_APPEND,
220 NULL,
221 &error);
222 if (error != base::PLATFORM_FILE_OK) {
223 VLOG(1) << "Could not open AEC dump file, error=" << error;
224 return IPC::InvalidPlatformFileForTransit();
226 return IPC::GetFileHandleForProcess(aec_dump_file, process, true);
229 // Does nothing. Just to avoid races between enable and disable.
230 void DisableAecDumpOnFileThread() {
231 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
233 #endif
235 // the global list of all renderer processes
236 base::LazyInstance<IDMap<RenderProcessHost> >::Leaky
237 g_all_hosts = LAZY_INSTANCE_INITIALIZER;
239 base::LazyInstance<scoped_refptr<BrowserPluginGeolocationPermissionContext> >
240 g_browser_plugin_geolocation_context = LAZY_INSTANCE_INITIALIZER;
242 // Map of site to process, to ensure we only have one RenderProcessHost per
243 // site in process-per-site mode. Each map is specific to a BrowserContext.
244 class SiteProcessMap : public base::SupportsUserData::Data {
245 public:
246 typedef base::hash_map<std::string, RenderProcessHost*> SiteToProcessMap;
247 SiteProcessMap() {}
249 void RegisterProcess(const std::string& site, RenderProcessHost* process) {
250 map_[site] = process;
253 RenderProcessHost* FindProcess(const std::string& site) {
254 SiteToProcessMap::iterator i = map_.find(site);
255 if (i != map_.end())
256 return i->second;
257 return NULL;
260 void RemoveProcess(RenderProcessHost* host) {
261 // Find all instances of this process in the map, then separately remove
262 // them.
263 std::set<std::string> sites;
264 for (SiteToProcessMap::const_iterator i = map_.begin();
265 i != map_.end();
266 i++) {
267 if (i->second == host)
268 sites.insert(i->first);
270 for (std::set<std::string>::iterator i = sites.begin();
271 i != sites.end();
272 i++) {
273 SiteToProcessMap::iterator iter = map_.find(*i);
274 if (iter != map_.end()) {
275 DCHECK_EQ(iter->second, host);
276 map_.erase(iter);
281 private:
282 SiteToProcessMap map_;
285 // Find the SiteProcessMap specific to the given context.
286 SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) {
287 DCHECK(context);
288 SiteProcessMap* map = static_cast<SiteProcessMap*>(
289 context->GetUserData(kSiteProcessMapKeyName));
290 if (!map) {
291 map = new SiteProcessMap();
292 context->SetUserData(kSiteProcessMapKeyName, map);
294 return map;
297 // NOTE: changes to this class need to be reviewed by the security team.
298 class RendererSandboxedProcessLauncherDelegate
299 : public content::SandboxedProcessLauncherDelegate {
300 public:
301 RendererSandboxedProcessLauncherDelegate(IPC::ChannelProxy* channel)
302 #if defined(OS_POSIX)
303 : ipc_fd_(channel->TakeClientFileDescriptor())
304 #endif // OS_POSIX
307 virtual ~RendererSandboxedProcessLauncherDelegate() {}
309 #if defined(OS_WIN)
310 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
311 bool* success) {
312 AddBaseHandleClosePolicy(policy);
313 GetContentClient()->browser()->PreSpawnRenderer(policy, success);
316 #elif defined(OS_POSIX)
317 virtual bool ShouldUseZygote() OVERRIDE {
318 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
319 CommandLine::StringType renderer_prefix =
320 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
321 return renderer_prefix.empty();
323 virtual int GetIpcFd() OVERRIDE {
324 return ipc_fd_;
326 #endif // OS_WIN
328 private:
329 #if defined(OS_POSIX)
330 int ipc_fd_;
331 #endif // OS_POSIX
334 #if defined(USE_MOJO)
335 base::PlatformFile PlatformFileFromScopedPlatformHandle(
336 mojo::embedder::ScopedPlatformHandle handle) {
337 #if defined(OS_POSIX)
338 return handle.release().fd;
339 #elif defined(OS_WIN)
340 return handle.release().handle;
341 #endif
343 #endif
345 } // namespace
347 RendererMainThreadFactoryFunction g_renderer_main_thread_factory = NULL;
349 void RenderProcessHost::RegisterRendererMainThreadFactory(
350 RendererMainThreadFactoryFunction create) {
351 g_renderer_main_thread_factory = create;
354 base::MessageLoop* g_in_process_thread;
356 base::MessageLoop*
357 RenderProcessHostImpl::GetInProcessRendererThreadForTesting() {
358 return g_in_process_thread;
361 // Stores the maximum number of renderer processes the content module can
362 // create.
363 static size_t g_max_renderer_count_override = 0;
365 // static
366 size_t RenderProcessHost::GetMaxRendererProcessCount() {
367 if (g_max_renderer_count_override)
368 return g_max_renderer_count_override;
370 // Defines the maximum number of renderer processes according to the
371 // amount of installed memory as reported by the OS. The calculation
372 // assumes that you want the renderers to use half of the installed
373 // RAM and assuming that each WebContents uses ~40MB.
374 // If you modify this assumption, you need to adjust the
375 // ThirtyFourTabs test to match the expected number of processes.
377 // With the given amounts of installed memory below on a 32-bit CPU,
378 // the maximum renderer count will roughly be as follows:
380 // 128 MB -> 3
381 // 512 MB -> 6
382 // 1024 MB -> 12
383 // 4096 MB -> 51
384 // 16384 MB -> 82 (kMaxRendererProcessCount)
386 static size_t max_count = 0;
387 if (!max_count) {
388 const size_t kEstimatedWebContentsMemoryUsage =
389 #if defined(ARCH_CPU_64_BITS)
390 60; // In MB
391 #else
392 40; // In MB
393 #endif
394 max_count = base::SysInfo::AmountOfPhysicalMemoryMB() / 2;
395 max_count /= kEstimatedWebContentsMemoryUsage;
397 const size_t kMinRendererProcessCount = 3;
398 max_count = std::max(max_count, kMinRendererProcessCount);
399 max_count = std::min(max_count, kMaxRendererProcessCount);
401 return max_count;
404 // static
405 bool g_run_renderer_in_process_ = false;
407 // static
408 void RenderProcessHost::SetMaxRendererProcessCount(size_t count) {
409 g_max_renderer_count_override = count;
412 RenderProcessHostImpl::RenderProcessHostImpl(
413 BrowserContext* browser_context,
414 StoragePartitionImpl* storage_partition_impl,
415 bool supports_browser_plugin,
416 bool is_guest)
417 : fast_shutdown_started_(false),
418 deleting_soon_(false),
419 #ifndef NDEBUG
420 is_self_deleted_(false),
421 #endif
422 pending_views_(0),
423 visible_widgets_(0),
424 backgrounded_(true),
425 cached_dibs_cleaner_(FROM_HERE,
426 base::TimeDelta::FromSeconds(5),
427 this,
428 &RenderProcessHostImpl::ClearTransportDIBCache),
429 is_initialized_(false),
430 id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
431 browser_context_(browser_context),
432 storage_partition_impl_(storage_partition_impl),
433 sudden_termination_allowed_(true),
434 ignore_input_events_(false),
435 supports_browser_plugin_(supports_browser_plugin),
436 is_guest_(is_guest),
437 gpu_observer_registered_(false),
438 delayed_cleanup_needed_(false),
439 within_process_died_observer_(false),
440 power_monitor_broadcaster_(this),
441 geolocation_dispatcher_host_(NULL),
442 screen_orientation_dispatcher_host_(NULL),
443 worker_ref_count_(0),
444 weak_factory_(this) {
445 widget_helper_ = new RenderWidgetHelper();
447 ChildProcessSecurityPolicyImpl::GetInstance()->Add(GetID());
449 CHECK(!g_exited_main_message_loop);
450 RegisterHost(GetID(), this);
451 g_all_hosts.Get().set_check_on_null_data(true);
452 // Initialize |child_process_activity_time_| to a reasonable value.
453 mark_child_process_activity_time();
455 if (!GetBrowserContext()->IsOffTheRecord() &&
456 !CommandLine::ForCurrentProcess()->HasSwitch(
457 switches::kDisableGpuShaderDiskCache)) {
458 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
459 base::Bind(&CacheShaderInfo, GetID(),
460 storage_partition_impl_->GetPath()));
463 // Note: When we create the RenderProcessHostImpl, it's technically
464 // backgrounded, because it has no visible listeners. But the process
465 // doesn't actually exist yet, so we'll Background it later, after
466 // creation.
469 // static
470 void RenderProcessHostImpl::ShutDownInProcessRenderer() {
471 DCHECK(g_run_renderer_in_process_);
473 switch (g_all_hosts.Pointer()->size()) {
474 case 0:
475 return;
476 case 1: {
477 RenderProcessHostImpl* host = static_cast<RenderProcessHostImpl*>(
478 AllHostsIterator().GetCurrentValue());
479 FOR_EACH_OBSERVER(RenderProcessHostObserver,
480 host->observers_,
481 RenderProcessHostDestroyed(host));
482 #ifndef NDEBUG
483 host->is_self_deleted_ = true;
484 #endif
485 delete host;
486 return;
488 default:
489 NOTREACHED() << "There should be only one RenderProcessHost when running "
490 << "in-process.";
494 RenderProcessHostImpl::~RenderProcessHostImpl() {
495 #ifndef NDEBUG
496 DCHECK(is_self_deleted_)
497 << "RenderProcessHostImpl is destroyed by something other than itself";
498 #endif
500 // Make sure to clean up the in-process renderer before the channel, otherwise
501 // it may still run and have its IPCs fail, causing asserts.
502 in_process_renderer_.reset();
504 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(GetID());
506 if (gpu_observer_registered_) {
507 GpuDataManagerImpl::GetInstance()->RemoveObserver(this);
508 gpu_observer_registered_ = false;
511 // We may have some unsent messages at this point, but that's OK.
512 channel_.reset();
513 while (!queued_messages_.empty()) {
514 delete queued_messages_.front();
515 queued_messages_.pop();
518 ClearTransportDIBCache();
519 UnregisterHost(GetID());
521 if (!CommandLine::ForCurrentProcess()->HasSwitch(
522 switches::kDisableGpuShaderDiskCache)) {
523 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
524 base::Bind(&RemoveShaderInfo, GetID()));
528 void RenderProcessHostImpl::EnableSendQueue() {
529 is_initialized_ = false;
532 bool RenderProcessHostImpl::Init() {
533 // calling Init() more than once does nothing, this makes it more convenient
534 // for the view host which may not be sure in some cases
535 if (channel_)
536 return true;
538 CommandLine::StringType renderer_prefix;
539 #if defined(OS_POSIX)
540 // A command prefix is something prepended to the command line of the spawned
541 // process. It is supported only on POSIX systems.
542 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
543 renderer_prefix =
544 browser_command_line.GetSwitchValueNative(switches::kRendererCmdPrefix);
545 #endif // defined(OS_POSIX)
547 #if defined(OS_LINUX)
548 int flags = renderer_prefix.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
549 ChildProcessHost::CHILD_NORMAL;
550 #else
551 int flags = ChildProcessHost::CHILD_NORMAL;
552 #endif
554 // Find the renderer before creating the channel so if this fails early we
555 // return without creating the channel.
556 base::FilePath renderer_path = ChildProcessHost::GetChildPath(flags);
557 if (renderer_path.empty())
558 return false;
560 // Setup the IPC channel.
561 const std::string channel_id =
562 IPC::Channel::GenerateVerifiedChannelID(std::string());
563 channel_.reset(
564 new IPC::ChannelProxy(channel_id,
565 IPC::Channel::MODE_SERVER,
566 this,
567 BrowserThread::GetMessageLoopProxyForThread(
568 BrowserThread::IO).get()));
570 // Call the embedder first so that their IPC filters have priority.
571 GetContentClient()->browser()->RenderProcessWillLaunch(this);
573 CreateMessageFilters();
575 if (run_renderer_in_process()) {
576 DCHECK(g_renderer_main_thread_factory);
577 // Crank up a thread and run the initialization there. With the way that
578 // messages flow between the browser and renderer, this thread is required
579 // to prevent a deadlock in single-process mode. Since the primordial
580 // thread in the renderer process runs the WebKit code and can sometimes
581 // make blocking calls to the UI thread (i.e. this thread), they need to run
582 // on separate threads.
583 in_process_renderer_.reset(g_renderer_main_thread_factory(channel_id));
585 base::Thread::Options options;
586 #if defined(OS_WIN) && !defined(OS_MACOSX)
587 // In-process plugins require this to be a UI message loop.
588 options.message_loop_type = base::MessageLoop::TYPE_UI;
589 #else
590 // We can't have multiple UI loops on Linux and Android, so we don't support
591 // in-process plugins.
592 options.message_loop_type = base::MessageLoop::TYPE_DEFAULT;
593 #endif
594 in_process_renderer_->StartWithOptions(options);
596 g_in_process_thread = in_process_renderer_->message_loop();
598 OnProcessLaunched(); // Fake a callback that the process is ready.
599 } else {
600 // Build command line for renderer. We call AppendRendererCommandLine()
601 // first so the process type argument will appear first.
602 CommandLine* cmd_line = new CommandLine(renderer_path);
603 if (!renderer_prefix.empty())
604 cmd_line->PrependWrapper(renderer_prefix);
605 AppendRendererCommandLine(cmd_line);
606 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
608 // Spawn the child process asynchronously to avoid blocking the UI thread.
609 // As long as there's no renderer prefix, we can use the zygote process
610 // at this stage.
611 child_process_launcher_.reset(new ChildProcessLauncher(
612 new RendererSandboxedProcessLauncherDelegate(channel_.get()),
613 cmd_line,
614 GetID(),
615 this));
617 fast_shutdown_started_ = false;
620 if (!gpu_observer_registered_) {
621 gpu_observer_registered_ = true;
622 GpuDataManagerImpl::GetInstance()->AddObserver(this);
625 is_initialized_ = true;
626 return true;
629 void RenderProcessHostImpl::CreateMessageFilters() {
630 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
631 AddFilter(new ResourceSchedulerFilter(GetID()));
632 MediaInternals* media_internals = MediaInternals::GetInstance();
633 media::AudioManager* audio_manager =
634 BrowserMainLoop::GetInstance()->audio_manager();
635 // Add BrowserPluginMessageFilter to ensure it gets the first stab at messages
636 // from guests.
637 if (supports_browser_plugin_) {
638 scoped_refptr<BrowserPluginMessageFilter> bp_message_filter(
639 new BrowserPluginMessageFilter(GetID(), IsGuest()));
640 AddFilter(bp_message_filter.get());
643 scoped_refptr<RenderMessageFilter> render_message_filter(
644 new RenderMessageFilter(
645 GetID(),
646 IsGuest(),
647 #if defined(ENABLE_PLUGINS)
648 PluginServiceImpl::GetInstance(),
649 #else
650 NULL,
651 #endif
652 GetBrowserContext(),
653 GetBrowserContext()->GetRequestContextForRenderProcess(GetID()),
654 widget_helper_.get(),
655 audio_manager,
656 media_internals,
657 storage_partition_impl_->GetDOMStorageContext()));
658 AddFilter(render_message_filter.get());
659 AddFilter(
660 new RenderFrameMessageFilter(GetID(), widget_helper_.get()));
661 BrowserContext* browser_context = GetBrowserContext();
662 ResourceContext* resource_context = browser_context->GetResourceContext();
664 scoped_refptr<net::URLRequestContextGetter> request_context(
665 browser_context->GetRequestContextForRenderProcess(GetID()));
666 scoped_refptr<net::URLRequestContextGetter> media_request_context(
667 browser_context->GetMediaRequestContextForRenderProcess(GetID()));
669 ResourceMessageFilter::GetContextsCallback get_contexts_callback(
670 base::Bind(&GetContexts, browser_context->GetResourceContext(),
671 request_context, media_request_context));
673 ResourceMessageFilter* resource_message_filter = new ResourceMessageFilter(
674 GetID(), PROCESS_TYPE_RENDERER,
675 storage_partition_impl_->GetAppCacheService(),
676 ChromeBlobStorageContext::GetFor(browser_context),
677 storage_partition_impl_->GetFileSystemContext(),
678 storage_partition_impl_->GetServiceWorkerContext(),
679 get_contexts_callback);
681 AddFilter(resource_message_filter);
682 MediaStreamManager* media_stream_manager =
683 BrowserMainLoop::GetInstance()->media_stream_manager();
684 AddFilter(new AudioInputRendererHost(
685 audio_manager,
686 media_stream_manager,
687 BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
688 BrowserMainLoop::GetInstance()->user_input_monitor()));
689 // The AudioRendererHost needs to be available for lookup, so it's
690 // stashed in a member variable.
691 audio_renderer_host_ = new AudioRendererHost(
692 GetID(),
693 audio_manager,
694 BrowserMainLoop::GetInstance()->audio_mirroring_manager(),
695 media_internals,
696 media_stream_manager);
697 AddFilter(audio_renderer_host_);
698 AddFilter(
699 new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_manager()));
700 AddFilter(new MidiDispatcherHost(GetID(), browser_context));
701 AddFilter(new VideoCaptureHost(media_stream_manager));
702 AddFilter(new AppCacheDispatcherHost(
703 storage_partition_impl_->GetAppCacheService(),
704 GetID()));
705 AddFilter(new ClipboardMessageFilter);
706 AddFilter(new DOMStorageMessageFilter(
707 GetID(),
708 storage_partition_impl_->GetDOMStorageContext()));
709 AddFilter(new IndexedDBDispatcherHost(
710 storage_partition_impl_->GetIndexedDBContext()));
712 if (IsGuest()) {
713 if (!g_browser_plugin_geolocation_context.Get().get()) {
714 g_browser_plugin_geolocation_context.Get() =
715 new BrowserPluginGeolocationPermissionContext();
717 geolocation_dispatcher_host_ = GeolocationDispatcherHost::New(
718 GetID(), g_browser_plugin_geolocation_context.Get().get());
719 } else {
720 geolocation_dispatcher_host_ = GeolocationDispatcherHost::New(
721 GetID(), browser_context->GetGeolocationPermissionContext());
723 AddFilter(geolocation_dispatcher_host_);
724 gpu_message_filter_ = new GpuMessageFilter(GetID(), widget_helper_.get());
725 AddFilter(gpu_message_filter_);
726 #if defined(ENABLE_WEBRTC)
727 AddFilter(new WebRTCIdentityServiceHost(
728 GetID(), storage_partition_impl_->GetWebRTCIdentityStore()));
729 peer_connection_tracker_host_ = new PeerConnectionTrackerHost(GetID());
730 AddFilter(peer_connection_tracker_host_.get());
731 AddFilter(new MediaStreamDispatcherHost(
732 GetID(),
733 browser_context->GetResourceContext()->GetMediaDeviceIDSalt(),
734 media_stream_manager));
735 AddFilter(
736 new DeviceRequestMessageFilter(resource_context, media_stream_manager));
737 AddFilter(new MediaStreamTrackMetricsHost());
738 #endif
739 #if defined(ENABLE_PLUGINS)
740 AddFilter(new PepperRendererConnection(GetID()));
741 #endif
742 #if defined(ENABLE_INPUT_SPEECH)
743 AddFilter(new InputTagSpeechDispatcherHost(
744 IsGuest(), GetID(), storage_partition_impl_->GetURLRequestContext()));
745 #endif
746 AddFilter(new SpeechRecognitionDispatcherHost(
747 IsGuest(), GetID(), storage_partition_impl_->GetURLRequestContext()));
748 AddFilter(new FileAPIMessageFilter(
749 GetID(),
750 storage_partition_impl_->GetURLRequestContext(),
751 storage_partition_impl_->GetFileSystemContext(),
752 ChromeBlobStorageContext::GetFor(browser_context),
753 StreamContext::GetFor(browser_context)));
754 AddFilter(new FileUtilitiesMessageFilter(GetID()));
755 AddFilter(new MimeRegistryMessageFilter());
756 AddFilter(new DatabaseMessageFilter(
757 storage_partition_impl_->GetDatabaseTracker()));
758 #if defined(OS_MACOSX)
759 AddFilter(new TextInputClientMessageFilter(GetID()));
760 #elif defined(OS_WIN)
761 channel_->AddFilter(new FontCacheDispatcher());
762 #elif defined(OS_ANDROID)
763 browser_demuxer_android_ = new BrowserDemuxerAndroid();
764 AddFilter(browser_demuxer_android_);
765 #endif
767 SocketStreamDispatcherHost::GetRequestContextCallback
768 request_context_callback(
769 base::Bind(&GetRequestContext, request_context,
770 media_request_context));
772 SocketStreamDispatcherHost* socket_stream_dispatcher_host =
773 new SocketStreamDispatcherHost(
774 GetID(), request_context_callback, resource_context);
775 AddFilter(socket_stream_dispatcher_host);
777 WebSocketDispatcherHost::GetRequestContextCallback
778 websocket_request_context_callback(
779 base::Bind(&GetRequestContext, request_context,
780 media_request_context, ResourceType::SUB_RESOURCE));
782 AddFilter(new WebSocketDispatcherHost(websocket_request_context_callback));
784 message_port_message_filter_ = new MessagePortMessageFilter(
785 base::Bind(&RenderWidgetHelper::GetNextRoutingID,
786 base::Unretained(widget_helper_.get())));
787 AddFilter(message_port_message_filter_);
789 scoped_refptr<ServiceWorkerDispatcherHost> service_worker_filter =
790 new ServiceWorkerDispatcherHost(GetID(), message_port_message_filter_);
791 service_worker_filter->Init(
792 storage_partition_impl_->GetServiceWorkerContext());
793 AddFilter(service_worker_filter);
795 // If "--enable-embedded-shared-worker" is set, we use
796 // SharedWorkerMessageFilter in stead of WorkerMessageFilter.
797 if (WorkerService::EmbeddedSharedWorkerEnabled()) {
798 AddFilter(new SharedWorkerMessageFilter(
799 GetID(),
800 resource_context,
801 WorkerStoragePartition(
802 storage_partition_impl_->GetURLRequestContext(),
803 storage_partition_impl_->GetMediaURLRequestContext(),
804 storage_partition_impl_->GetAppCacheService(),
805 storage_partition_impl_->GetQuotaManager(),
806 storage_partition_impl_->GetFileSystemContext(),
807 storage_partition_impl_->GetDatabaseTracker(),
808 storage_partition_impl_->GetIndexedDBContext(),
809 storage_partition_impl_->GetServiceWorkerContext()),
810 message_port_message_filter_));
811 } else {
812 AddFilter(new WorkerMessageFilter(
813 GetID(),
814 resource_context,
815 WorkerStoragePartition(
816 storage_partition_impl_->GetURLRequestContext(),
817 storage_partition_impl_->GetMediaURLRequestContext(),
818 storage_partition_impl_->GetAppCacheService(),
819 storage_partition_impl_->GetQuotaManager(),
820 storage_partition_impl_->GetFileSystemContext(),
821 storage_partition_impl_->GetDatabaseTracker(),
822 storage_partition_impl_->GetIndexedDBContext(),
823 storage_partition_impl_->GetServiceWorkerContext()),
824 message_port_message_filter_));
827 #if defined(ENABLE_WEBRTC)
828 AddFilter(new P2PSocketDispatcherHost(
829 resource_context,
830 browser_context->GetRequestContextForRenderProcess(GetID())));
831 #endif
833 AddFilter(new TraceMessageFilter());
834 AddFilter(new ResolveProxyMsgHelper(
835 browser_context->GetRequestContextForRenderProcess(GetID())));
836 AddFilter(new QuotaDispatcherHost(
837 GetID(),
838 storage_partition_impl_->GetQuotaManager(),
839 GetContentClient()->browser()->CreateQuotaPermissionContext()));
840 AddFilter(new GamepadBrowserMessageFilter());
841 AddFilter(new DeviceMotionMessageFilter());
842 AddFilter(new DeviceOrientationMessageFilter());
843 AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER));
844 AddFilter(new HistogramMessageFilter());
845 #if defined(USE_TCMALLOC) && (defined(OS_LINUX) || defined(OS_ANDROID))
846 if (CommandLine::ForCurrentProcess()->HasSwitch(
847 switches::kEnableMemoryBenchmarking))
848 AddFilter(new MemoryBenchmarkMessageFilter());
849 #endif
850 AddFilter(new VibrationMessageFilter());
851 screen_orientation_dispatcher_host_ = new ScreenOrientationDispatcherHost();
852 AddFilter(screen_orientation_dispatcher_host_);
855 int RenderProcessHostImpl::GetNextRoutingID() {
856 return widget_helper_->GetNextRoutingID();
860 void RenderProcessHostImpl::ResumeDeferredNavigation(
861 const GlobalRequestID& request_id) {
862 widget_helper_->ResumeDeferredNavigation(request_id);
865 void RenderProcessHostImpl::NotifyTimezoneChange() {
866 Send(new ViewMsg_TimezoneChange());
869 void RenderProcessHostImpl::AddRoute(
870 int32 routing_id,
871 IPC::Listener* listener) {
872 listeners_.AddWithID(listener, routing_id);
875 void RenderProcessHostImpl::RemoveRoute(int32 routing_id) {
876 DCHECK(listeners_.Lookup(routing_id) != NULL);
877 listeners_.Remove(routing_id);
879 #if defined(OS_WIN)
880 // Dump the handle table if handle auditing is enabled.
881 const CommandLine& browser_command_line =
882 *CommandLine::ForCurrentProcess();
883 if (browser_command_line.HasSwitch(switches::kAuditHandles) ||
884 browser_command_line.HasSwitch(switches::kAuditAllHandles)) {
885 DumpHandles();
887 // We wait to close the channels until the child process has finished
888 // dumping handles and sends us ChildProcessHostMsg_DumpHandlesDone.
889 return;
891 #endif
892 // Keep the one renderer thread around forever in single process mode.
893 if (!run_renderer_in_process())
894 Cleanup();
897 void RenderProcessHostImpl::AddObserver(RenderProcessHostObserver* observer) {
898 observers_.AddObserver(observer);
901 void RenderProcessHostImpl::RemoveObserver(
902 RenderProcessHostObserver* observer) {
903 observers_.RemoveObserver(observer);
906 bool RenderProcessHostImpl::WaitForBackingStoreMsg(
907 int render_widget_id,
908 const base::TimeDelta& max_delay,
909 IPC::Message* msg) {
910 // The post task to this thread with the process id could be in queue, and we
911 // don't want to dispatch a message before then since it will need the handle.
912 if (child_process_launcher_.get() && child_process_launcher_->IsStarting())
913 return false;
915 return widget_helper_->WaitForBackingStoreMsg(render_widget_id,
916 max_delay, msg);
919 void RenderProcessHostImpl::ReceivedBadMessage() {
920 CommandLine* command_line = CommandLine::ForCurrentProcess();
921 if (command_line->HasSwitch(switches::kDisableKillAfterBadIPC))
922 return;
924 if (run_renderer_in_process()) {
925 // In single process mode it is better if we don't suicide but just
926 // crash.
927 CHECK(false);
929 // We kill the renderer but don't include a NOTREACHED, because we want the
930 // browser to try to survive when it gets illegal messages from the renderer.
931 base::KillProcess(GetHandle(), RESULT_CODE_KILLED_BAD_MESSAGE,
932 false);
935 void RenderProcessHostImpl::WidgetRestored() {
936 // Verify we were properly backgrounded.
937 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
938 visible_widgets_++;
939 SetBackgrounded(false);
942 void RenderProcessHostImpl::WidgetHidden() {
943 // On startup, the browser will call Hide
944 if (backgrounded_)
945 return;
947 DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
948 visible_widgets_--;
949 DCHECK_GE(visible_widgets_, 0);
950 if (visible_widgets_ == 0) {
951 DCHECK(!backgrounded_);
952 SetBackgrounded(true);
956 int RenderProcessHostImpl::VisibleWidgetCount() const {
957 return visible_widgets_;
960 bool RenderProcessHostImpl::IsGuest() const {
961 return is_guest_;
964 StoragePartition* RenderProcessHostImpl::GetStoragePartition() const {
965 return storage_partition_impl_;
968 static void AppendGpuCommandLineFlags(CommandLine* command_line) {
969 if (content::IsThreadedCompositingEnabled())
970 command_line->AppendSwitch(switches::kEnableThreadedCompositing);
972 if (content::IsDelegatedRendererEnabled())
973 command_line->AppendSwitch(switches::kEnableDelegatedRenderer);
975 if (content::IsImplSidePaintingEnabled())
976 command_line->AppendSwitch(switches::kEnableImplSidePainting);
978 // Appending disable-gpu-feature switches due to software rendering list.
979 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
980 DCHECK(gpu_data_manager);
981 gpu_data_manager->AppendRendererCommandLine(command_line);
984 void RenderProcessHostImpl::AppendRendererCommandLine(
985 CommandLine* command_line) const {
986 // Pass the process type first, so it shows first in process listings.
987 command_line->AppendSwitchASCII(switches::kProcessType,
988 switches::kRendererProcess);
990 // Now send any options from our own command line we want to propagate.
991 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
992 PropagateBrowserCommandLineToRenderer(browser_command_line, command_line);
994 // Pass on the browser locale.
995 const std::string locale =
996 GetContentClient()->browser()->GetApplicationLocale();
997 command_line->AppendSwitchASCII(switches::kLang, locale);
999 // If we run base::FieldTrials, we want to pass to their state to the
1000 // renderer so that it can act in accordance with each state, or record
1001 // histograms relating to the base::FieldTrial states.
1002 std::string field_trial_states;
1003 base::FieldTrialList::StatesToString(&field_trial_states);
1004 if (!field_trial_states.empty()) {
1005 command_line->AppendSwitchASCII(switches::kForceFieldTrials,
1006 field_trial_states);
1009 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1010 command_line, GetID());
1012 if (content::IsPinchToZoomEnabled())
1013 command_line->AppendSwitch(switches::kEnablePinch);
1015 AppendGpuCommandLineFlags(command_line);
1018 void RenderProcessHostImpl::PropagateBrowserCommandLineToRenderer(
1019 const CommandLine& browser_cmd,
1020 CommandLine* renderer_cmd) const {
1021 // Propagate the following switches to the renderer command line (along
1022 // with any associated values) if present in the browser command line.
1023 static const char* const kSwitchNames[] = {
1024 switches::kAllowLoopbackInPeerConnection,
1025 switches::kAudioBufferSize,
1026 switches::kAuditAllHandles,
1027 switches::kAuditHandles,
1028 switches::kBlinkPlatformLogChannels,
1029 switches::kBlockCrossSiteDocuments,
1030 switches::kDefaultTileWidth,
1031 switches::kDefaultTileHeight,
1032 switches::kDisable3DAPIs,
1033 switches::kDisableAcceleratedCompositing,
1034 switches::kDisableAcceleratedFixedRootBackground,
1035 switches::kDisableAcceleratedVideoDecode,
1036 switches::kDisableApplicationCache,
1037 switches::kDisableBreakpad,
1038 switches::kDisableCompositingForFixedPosition,
1039 switches::kDisableCompositingForTransition,
1040 switches::kDisableDatabases,
1041 switches::kDisableDelegatedRenderer,
1042 switches::kDisableDesktopNotifications,
1043 switches::kDisableDirectNPAPIRequests,
1044 switches::kDisableFastTextAutosizing,
1045 switches::kDisableFileSystem,
1046 switches::kDisableFiltersOverIPC,
1047 switches::kDisableGpu,
1048 switches::kDisableGpuCompositing,
1049 switches::kDisableGpuRasterization,
1050 switches::kDisableGpuVsync,
1051 switches::kDisableLowResTiling,
1052 switches::kDisableHistogramCustomizer,
1053 switches::kDisableImplSidePainting,
1054 switches::kDisableLCDText,
1055 switches::kDisableLayerSquashing,
1056 switches::kDisableLocalStorage,
1057 switches::kDisableLogging,
1058 switches::kDisableMapImage,
1059 switches::kDisableOverlayScrollbar,
1060 switches::kDisablePinch,
1061 switches::kDisablePrefixedEncryptedMedia,
1062 switches::kDisableRepaintAfterLayout,
1063 switches::kDisableSeccompFilterSandbox,
1064 switches::kDisableSessionStorage,
1065 switches::kDisableSharedWorkers,
1066 switches::kDisableSpeechInput,
1067 switches::kDisableThreadedCompositing,
1068 switches::kDisableTouchAdjustment,
1069 switches::kDisableTouchDragDrop,
1070 switches::kDisableTouchEditing,
1071 switches::kDisableUniversalAcceleratedOverflowScroll,
1072 switches::kDisableUnprefixedMediaSource,
1073 switches::kDisableWebKitMediaSource,
1074 switches::kDomAutomationController,
1075 switches::kEnableAcceleratedFixedRootBackground,
1076 switches::kEnableAcceleratedOverflowScroll,
1077 switches::kEnableAccessibilityLogging,
1078 switches::kEnableADTSStreamParser,
1079 switches::kEnableBeginFrameScheduling,
1080 switches::kEnableBleedingEdgeRenderingFastPaths,
1081 switches::kEnableBrowserPluginForAllViewTypes,
1082 switches::kEnableCompositingForFixedPosition,
1083 switches::kEnableCompositingForTransition,
1084 switches::kEnableDeferredImageDecoding,
1085 switches::kEnableDelegatedRenderer,
1086 switches::kEnableEncryptedMedia,
1087 switches::kEnableExperimentalCanvasFeatures,
1088 switches::kEnableExperimentalWebPlatformFeatures,
1089 switches::kEnableExperimentalWebSocket,
1090 switches::kEnableFastTextAutosizing,
1091 switches::kEnableGPUClientLogging,
1092 switches::kEnableGpuClientTracing,
1093 switches::kEnableGpuRasterization,
1094 switches::kEnableGPUServiceLogging,
1095 switches::kEnableHighDpiCompositingForFixedPosition,
1096 switches::kEnableHTMLImports,
1097 switches::kEnableLowResTiling,
1098 switches::kEnableImplSidePainting,
1099 switches::kEnableInbandTextTracks,
1100 switches::kEnableLCDText,
1101 switches::kEnableLayerSquashing,
1102 switches::kEnableLogging,
1103 switches::kEnableMapImage,
1104 switches::kEnableMemoryBenchmarking,
1105 switches::kEnableOverlayFullscreenVideo,
1106 switches::kEnableOverlayScrollbar,
1107 switches::kEnableOverscrollNotifications,
1108 switches::kEnablePinch,
1109 switches::kEnablePreparsedJsCaching,
1110 switches::kEnableRepaintAfterLayout,
1111 switches::kEnableServiceWorker,
1112 switches::kEnableSkiaBenchmarking,
1113 switches::kEnableSoftwareCompositing,
1114 switches::kEnableSpeechSynthesis,
1115 switches::kEnableStatsTable,
1116 switches::kEnableStrictSiteIsolation,
1117 switches::kEnableTargetedStyleRecalc,
1118 switches::kEnableThreadedCompositing,
1119 switches::kEnableUniversalAcceleratedOverflowScroll,
1120 switches::kEnableTouchDragDrop,
1121 switches::kEnableTouchEditing,
1122 switches::kEnableViewport,
1123 switches::kEnableViewportMeta,
1124 switches::kMainFrameResizesAreOrientationChanges,
1125 switches::kEnableVtune,
1126 switches::kEnableWebAnimationsSVG,
1127 switches::kEnableWebGLDraftExtensions,
1128 switches::kEnableWebMIDI,
1129 switches::kForceDeviceScaleFactor,
1130 switches::kForceGpuRasterization,
1131 switches::kFullMemoryCrashReport,
1132 switches::kJavaScriptFlags,
1133 switches::kLoggingLevel,
1134 switches::kMaxUntiledLayerWidth,
1135 switches::kMaxUntiledLayerHeight,
1136 switches::kMemoryMetrics,
1137 switches::kNoReferrers,
1138 switches::kNoSandbox,
1139 switches::kNumRasterThreads,
1140 switches::kPpapiInProcess,
1141 switches::kProfilerTiming,
1142 switches::kReduceSecurityForTesting,
1143 switches::kRegisterPepperPlugins,
1144 switches::kRendererAssertTest,
1145 switches::kRendererStartupDialog,
1146 switches::kShowPaintRects,
1147 switches::kSitePerProcess,
1148 switches::kStatsCollectionController,
1149 switches::kTestSandbox,
1150 switches::kTestType,
1151 switches::kTouchEvents,
1152 switches::kTraceToConsole,
1153 switches::kUseDiscardableMemory,
1154 // This flag needs to be propagated to the renderer process for
1155 // --in-process-webgl.
1156 switches::kUseGL,
1157 switches::kUseMobileUserAgent,
1158 switches::kV,
1159 switches::kVideoThreads,
1160 switches::kVModule,
1161 switches::kWebGLCommandBufferSizeKb,
1162 // Please keep these in alphabetical order. Compositor switches here should
1163 // also be added to chrome/browser/chromeos/login/chrome_restart_request.cc.
1164 cc::switches::kCompositeToMailbox,
1165 cc::switches::kDisableCompositedAntialiasing,
1166 cc::switches::kDisableCompositorTouchHitTesting,
1167 cc::switches::kDisableMainFrameBeforeActivation,
1168 cc::switches::kDisableMainFrameBeforeDraw,
1169 cc::switches::kDisableThreadedAnimation,
1170 cc::switches::kEnableGpuBenchmarking,
1171 cc::switches::kEnablePinchVirtualViewport,
1172 cc::switches::kEnableMainFrameBeforeActivation,
1173 cc::switches::kEnableTopControlsPositionCalculation,
1174 cc::switches::kMaxTilesForInterestArea,
1175 cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
1176 cc::switches::kShowCompositedLayerBorders,
1177 cc::switches::kShowFPSCounter,
1178 cc::switches::kShowLayerAnimationBounds,
1179 cc::switches::kShowNonOccludingRects,
1180 cc::switches::kShowOccludingRects,
1181 cc::switches::kShowPropertyChangedRects,
1182 cc::switches::kShowReplicaScreenSpaceRects,
1183 cc::switches::kShowScreenSpaceRects,
1184 cc::switches::kShowSurfaceDamageRects,
1185 cc::switches::kSlowDownRasterScaleFactor,
1186 cc::switches::kStrictLayerPropertyChangeChecking,
1187 cc::switches::kTopControlsHeight,
1188 cc::switches::kTopControlsHideThreshold,
1189 cc::switches::kTopControlsShowThreshold,
1190 #if defined(ENABLE_PLUGINS)
1191 switches::kEnablePepperTesting,
1192 #endif
1193 #if defined(ENABLE_WEBRTC)
1194 switches::kEnableAudioTrackProcessing,
1195 switches::kDisableDeviceEnumeration,
1196 switches::kDisableWebRtcHWDecoding,
1197 switches::kDisableWebRtcHWEncoding,
1198 switches::kEnableWebRtcAecRecordings,
1199 switches::kEnableWebRtcHWVp8Encoding,
1200 switches::kEnableWebRtcTcpServerSocket,
1201 #endif
1202 #if defined(OS_ANDROID)
1203 switches::kDisableGestureRequirementForMediaPlayback,
1204 switches::kDisableLowEndDeviceMode,
1205 switches::kDisableWebRTC,
1206 switches::kEnableLowEndDeviceMode,
1207 switches::kEnableSpeechRecognition,
1208 switches::kMediaDrmEnableNonCompositing,
1209 switches::kNetworkCountryIso,
1210 #endif
1211 #if defined(OS_ANDROID) && defined(ARCH_CPU_X86)
1212 switches::kEnableWebAudio,
1213 #else
1214 // Need to be able to disable webaudio on other platforms where it
1215 // is enabled by default.
1216 switches::kDisableWebAudio,
1217 #endif
1218 #if defined(OS_MACOSX)
1219 // Allow this to be set when invoking the browser and relayed along.
1220 switches::kEnableSandboxLogging,
1221 #endif
1222 #if defined(OS_POSIX)
1223 switches::kChildCleanExit,
1224 #endif
1225 #if defined(OS_WIN)
1226 switches::kEnableDirectWrite,
1227 switches::kEnableHighResolutionTime,
1228 switches::kHighDPISupport,
1229 #endif
1231 renderer_cmd->CopySwitchesFrom(browser_cmd, kSwitchNames,
1232 arraysize(kSwitchNames));
1234 if (browser_cmd.HasSwitch(switches::kTraceStartup) &&
1235 BrowserMainLoop::GetInstance()->is_tracing_startup()) {
1236 // Pass kTraceStartup switch to renderer only if startup tracing has not
1237 // finished.
1238 renderer_cmd->AppendSwitchASCII(
1239 switches::kTraceStartup,
1240 browser_cmd.GetSwitchValueASCII(switches::kTraceStartup));
1243 // Disable databases in incognito mode.
1244 if (GetBrowserContext()->IsOffTheRecord() &&
1245 !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
1246 renderer_cmd->AppendSwitch(switches::kDisableDatabases);
1247 #if defined(OS_ANDROID)
1248 renderer_cmd->AppendSwitch(switches::kDisableMediaHistoryLogging);
1249 #endif
1252 // Enforce the extra command line flags for impl-side painting.
1253 if (IsImplSidePaintingEnabled() &&
1254 !browser_cmd.HasSwitch(switches::kEnableDeferredImageDecoding))
1255 renderer_cmd->AppendSwitch(switches::kEnableDeferredImageDecoding);
1258 base::ProcessHandle RenderProcessHostImpl::GetHandle() const {
1259 if (run_renderer_in_process())
1260 return base::Process::Current().handle();
1262 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
1263 return base::kNullProcessHandle;
1265 return child_process_launcher_->GetHandle();
1268 bool RenderProcessHostImpl::FastShutdownIfPossible() {
1269 if (run_renderer_in_process())
1270 return false; // Single process mode never shutdown the renderer.
1272 if (!GetContentClient()->browser()->IsFastShutdownPossible())
1273 return false;
1275 if (!child_process_launcher_.get() ||
1276 child_process_launcher_->IsStarting() ||
1277 !GetHandle())
1278 return false; // Render process hasn't started or is probably crashed.
1280 // Test if there's an unload listener.
1281 // NOTE: It's possible that an onunload listener may be installed
1282 // while we're shutting down, so there's a small race here. Given that
1283 // the window is small, it's unlikely that the web page has much
1284 // state that will be lost by not calling its unload handlers properly.
1285 if (!SuddenTerminationAllowed())
1286 return false;
1288 if (worker_ref_count_ != 0)
1289 return false;
1291 // Set this before ProcessDied() so observers can tell if the render process
1292 // died due to fast shutdown versus another cause.
1293 fast_shutdown_started_ = true;
1295 ProcessDied(false /* already_dead */);
1296 return true;
1299 void RenderProcessHostImpl::DumpHandles() {
1300 #if defined(OS_WIN)
1301 Send(new ChildProcessMsg_DumpHandles());
1302 #else
1303 NOTIMPLEMENTED();
1304 #endif
1307 // This is a platform specific function for mapping a transport DIB given its id
1308 TransportDIB* RenderProcessHostImpl::MapTransportDIB(
1309 TransportDIB::Id dib_id) {
1310 #if defined(OS_WIN)
1311 // On Windows we need to duplicate the handle from the remote process
1312 HANDLE section;
1313 DuplicateHandle(GetHandle(), dib_id.handle, GetCurrentProcess(), &section,
1314 FILE_MAP_READ | FILE_MAP_WRITE,
1315 FALSE, 0);
1316 return TransportDIB::Map(section);
1317 #elif defined(TOOLKIT_GTK)
1318 return TransportDIB::Map(dib_id.shmkey);
1319 #elif defined(OS_ANDROID)
1320 return TransportDIB::Map(dib_id);
1321 #else
1322 // On POSIX, the browser allocates all DIBs and keeps a file descriptor around
1323 // for each.
1324 return widget_helper_->MapTransportDIB(dib_id);
1325 #endif
1328 TransportDIB* RenderProcessHostImpl::GetTransportDIB(
1329 TransportDIB::Id dib_id) {
1330 if (!TransportDIB::is_valid_id(dib_id))
1331 return NULL;
1333 const std::map<TransportDIB::Id, TransportDIB*>::iterator
1334 i = cached_dibs_.find(dib_id);
1335 if (i != cached_dibs_.end()) {
1336 cached_dibs_cleaner_.Reset();
1337 return i->second;
1340 TransportDIB* dib = MapTransportDIB(dib_id);
1341 if (!dib)
1342 return NULL;
1344 if (cached_dibs_.size() >= MAX_MAPPED_TRANSPORT_DIBS) {
1345 // Clean a single entry from the cache
1346 std::map<TransportDIB::Id, TransportDIB*>::iterator smallest_iterator;
1347 size_t smallest_size = std::numeric_limits<size_t>::max();
1349 for (std::map<TransportDIB::Id, TransportDIB*>::iterator
1350 i = cached_dibs_.begin(); i != cached_dibs_.end(); ++i) {
1351 if (i->second->size() <= smallest_size) {
1352 smallest_iterator = i;
1353 smallest_size = i->second->size();
1357 #if defined(TOOLKIT_GTK)
1358 smallest_iterator->second->Detach();
1359 #else
1360 delete smallest_iterator->second;
1361 #endif
1362 cached_dibs_.erase(smallest_iterator);
1365 cached_dibs_[dib_id] = dib;
1366 cached_dibs_cleaner_.Reset();
1367 return dib;
1370 void RenderProcessHostImpl::ClearTransportDIBCache() {
1371 #if defined(TOOLKIT_GTK)
1372 std::map<TransportDIB::Id, TransportDIB*>::const_iterator dib =
1373 cached_dibs_.begin();
1374 for (; dib != cached_dibs_.end(); ++dib)
1375 dib->second->Detach();
1376 #else
1377 STLDeleteContainerPairSecondPointers(
1378 cached_dibs_.begin(), cached_dibs_.end());
1379 #endif
1380 cached_dibs_.clear();
1383 bool RenderProcessHostImpl::Send(IPC::Message* msg) {
1384 TRACE_EVENT0("renderer_host", "RenderProcessHostImpl::Send");
1385 if (!channel_) {
1386 if (!is_initialized_) {
1387 queued_messages_.push(msg);
1388 return true;
1389 } else {
1390 delete msg;
1391 return false;
1395 if (child_process_launcher_.get() && child_process_launcher_->IsStarting()) {
1396 queued_messages_.push(msg);
1397 return true;
1400 return channel_->Send(msg);
1403 bool RenderProcessHostImpl::OnMessageReceived(const IPC::Message& msg) {
1404 // If we're about to be deleted, or have initiated the fast shutdown sequence,
1405 // we ignore incoming messages.
1407 if (deleting_soon_ || fast_shutdown_started_)
1408 return false;
1410 mark_child_process_activity_time();
1411 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
1412 // Dispatch control messages.
1413 bool msg_is_ok = true;
1414 IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1415 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_ShutdownRequest,
1416 OnShutdownRequest)
1417 IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DumpHandlesDone,
1418 OnDumpHandlesDone)
1419 IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
1420 SuddenTerminationChanged)
1421 IPC_MESSAGE_HANDLER(ViewHostMsg_UserMetricsRecordAction,
1422 OnUserMetricsRecordAction)
1423 IPC_MESSAGE_HANDLER(ViewHostMsg_SavedPageAsMHTML, OnSavedPageAsMHTML)
1424 // Adding single handlers for your service here is fine, but once your
1425 // service needs more than one handler, please extract them into a new
1426 // message filter and add that filter to CreateMessageFilters().
1427 IPC_END_MESSAGE_MAP_EX()
1429 if (!msg_is_ok) {
1430 // The message had a handler, but its de-serialization failed.
1431 // We consider this a capital crime. Kill the renderer if we have one.
1432 LOG(ERROR) << "bad message " << msg.type() << " terminating renderer.";
1433 RecordAction(base::UserMetricsAction("BadMessageTerminate_BRPH"));
1434 ReceivedBadMessage();
1436 return true;
1439 // Dispatch incoming messages to the appropriate IPC::Listener.
1440 IPC::Listener* listener = listeners_.Lookup(msg.routing_id());
1441 if (!listener) {
1442 if (msg.is_sync()) {
1443 // The listener has gone away, so we must respond or else the caller will
1444 // hang waiting for a reply.
1445 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1446 reply->set_reply_error();
1447 Send(reply);
1450 // If this is a SwapBuffers, we need to ack it if we're not going to handle
1451 // it so that the GPU process doesn't get stuck in unscheduled state.
1452 bool msg_is_ok = true;
1453 IPC_BEGIN_MESSAGE_MAP_EX(RenderProcessHostImpl, msg, msg_is_ok)
1454 IPC_MESSAGE_HANDLER(ViewHostMsg_CompositorSurfaceBuffersSwapped,
1455 OnCompositorSurfaceBuffersSwappedNoHost)
1456 IPC_END_MESSAGE_MAP_EX()
1457 return true;
1459 return listener->OnMessageReceived(msg);
1462 void RenderProcessHostImpl::OnChannelConnected(int32 peer_pid) {
1463 #if defined(IPC_MESSAGE_LOG_ENABLED)
1464 Send(new ChildProcessMsg_SetIPCLoggingEnabled(
1465 IPC::Logging::GetInstance()->Enabled()));
1466 #endif
1468 tracked_objects::ThreadData::Status status =
1469 tracked_objects::ThreadData::status();
1470 Send(new ChildProcessMsg_SetProfilerStatus(status));
1473 void RenderProcessHostImpl::OnChannelError() {
1474 ProcessDied(true /* already_dead */);
1477 BrowserContext* RenderProcessHostImpl::GetBrowserContext() const {
1478 return browser_context_;
1481 bool RenderProcessHostImpl::InSameStoragePartition(
1482 StoragePartition* partition) const {
1483 return storage_partition_impl_ == partition;
1486 int RenderProcessHostImpl::GetID() const {
1487 return id_;
1490 bool RenderProcessHostImpl::HasConnection() const {
1491 return channel_.get() != NULL;
1494 void RenderProcessHostImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1495 ignore_input_events_ = ignore_input_events;
1498 bool RenderProcessHostImpl::IgnoreInputEvents() const {
1499 return ignore_input_events_;
1502 void RenderProcessHostImpl::Cleanup() {
1503 // If within_process_died_observer_ is true, one of our observers performed an
1504 // action that caused us to die (e.g. http://crbug.com/339504). Therefore,
1505 // delay the destruction until all of the observer callbacks have been made,
1506 // and guarantee that the RenderProcessHostDestroyed observer callback is
1507 // always the last callback fired.
1508 if (within_process_died_observer_) {
1509 delayed_cleanup_needed_ = true;
1510 return;
1512 delayed_cleanup_needed_ = false;
1514 // When there are no other owners of this object, we can delete ourselves.
1515 if (listeners_.IsEmpty() && worker_ref_count_ == 0) {
1516 // We cannot clean up twice; if this fails, there is an issue with our
1517 // control flow.
1518 DCHECK(!deleting_soon_);
1520 DCHECK_EQ(0, pending_views_);
1521 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1522 observers_,
1523 RenderProcessHostDestroyed(this));
1524 NotificationService::current()->Notify(
1525 NOTIFICATION_RENDERER_PROCESS_TERMINATED,
1526 Source<RenderProcessHost>(this),
1527 NotificationService::NoDetails());
1529 #ifndef NDEBUG
1530 is_self_deleted_ = true;
1531 #endif
1532 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
1533 deleting_soon_ = true;
1534 // It's important not to wait for the DeleteTask to delete the channel
1535 // proxy. Kill it off now. That way, in case the profile is going away, the
1536 // rest of the objects attached to this RenderProcessHost start going
1537 // away first, since deleting the channel proxy will post a
1538 // OnChannelClosed() to IPC::ChannelProxy::Context on the IO thread.
1539 channel_.reset();
1540 gpu_message_filter_ = NULL;
1541 message_port_message_filter_ = NULL;
1542 geolocation_dispatcher_host_ = NULL;
1543 screen_orientation_dispatcher_host_ = NULL;
1545 // Remove ourself from the list of renderer processes so that we can't be
1546 // reused in between now and when the Delete task runs.
1547 UnregisterHost(GetID());
1551 void RenderProcessHostImpl::AddPendingView() {
1552 pending_views_++;
1555 void RenderProcessHostImpl::RemovePendingView() {
1556 DCHECK(pending_views_);
1557 pending_views_--;
1560 void RenderProcessHostImpl::SetSuddenTerminationAllowed(bool enabled) {
1561 sudden_termination_allowed_ = enabled;
1564 bool RenderProcessHostImpl::SuddenTerminationAllowed() const {
1565 return sudden_termination_allowed_;
1568 base::TimeDelta RenderProcessHostImpl::GetChildProcessIdleTime() const {
1569 return base::TimeTicks::Now() - child_process_activity_time_;
1572 void RenderProcessHostImpl::ResumeRequestsForView(int route_id) {
1573 widget_helper_->ResumeRequestsForView(route_id);
1576 void RenderProcessHostImpl::FilterURL(bool empty_allowed, GURL* url) {
1577 FilterURL(this, empty_allowed, url);
1580 #if defined(ENABLE_WEBRTC)
1581 void RenderProcessHostImpl::EnableAecDump(const base::FilePath& file) {
1582 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1583 BrowserThread::PostTaskAndReplyWithResult(
1584 BrowserThread::FILE, FROM_HERE,
1585 base::Bind(&CreateAecDumpFileForProcess, file, GetHandle()),
1586 base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
1587 weak_factory_.GetWeakPtr()));
1590 void RenderProcessHostImpl::DisableAecDump() {
1591 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1592 // Posting on the FILE thread and then replying back on the UI thread is only
1593 // for avoiding races between enable and disable. Nothing is done on the FILE
1594 // thread.
1595 BrowserThread::PostTaskAndReply(
1596 BrowserThread::FILE, FROM_HERE,
1597 base::Bind(&DisableAecDumpOnFileThread),
1598 base::Bind(&RenderProcessHostImpl::SendDisableAecDumpToRenderer,
1599 weak_factory_.GetWeakPtr()));
1602 void RenderProcessHostImpl::SetWebRtcLogMessageCallback(
1603 base::Callback<void(const std::string&)> callback) {
1604 webrtc_log_message_callback_ = callback;
1606 #endif
1608 IPC::ChannelProxy* RenderProcessHostImpl::GetChannel() {
1609 return channel_.get();
1612 void RenderProcessHostImpl::AddFilter(BrowserMessageFilter* filter) {
1613 channel_->AddFilter(filter->GetFilter());
1616 bool RenderProcessHostImpl::FastShutdownForPageCount(size_t count) {
1617 if (static_cast<size_t>(GetActiveViewCount()) == count)
1618 return FastShutdownIfPossible();
1619 return false;
1622 bool RenderProcessHostImpl::FastShutdownStarted() const {
1623 return fast_shutdown_started_;
1626 // static
1627 void RenderProcessHostImpl::RegisterHost(int host_id, RenderProcessHost* host) {
1628 g_all_hosts.Get().AddWithID(host, host_id);
1631 // static
1632 void RenderProcessHostImpl::UnregisterHost(int host_id) {
1633 RenderProcessHost* host = g_all_hosts.Get().Lookup(host_id);
1634 if (!host)
1635 return;
1637 g_all_hosts.Get().Remove(host_id);
1639 // Look up the map of site to process for the given browser_context,
1640 // in case we need to remove this process from it. It will be registered
1641 // under any sites it rendered that use process-per-site mode.
1642 SiteProcessMap* map =
1643 GetSiteProcessMapForBrowserContext(host->GetBrowserContext());
1644 map->RemoveProcess(host);
1647 // static
1648 void RenderProcessHostImpl::FilterURL(RenderProcessHost* rph,
1649 bool empty_allowed,
1650 GURL* url) {
1651 ChildProcessSecurityPolicyImpl* policy =
1652 ChildProcessSecurityPolicyImpl::GetInstance();
1654 if (empty_allowed && url->is_empty())
1655 return;
1657 // The browser process should never hear the swappedout:// URL from any
1658 // of the renderer's messages. Check for this in debug builds, but don't
1659 // let it crash a release browser.
1660 DCHECK(GURL(kSwappedOutURL) != *url);
1662 if (!url->is_valid()) {
1663 // Have to use about:blank for the denied case, instead of an empty GURL.
1664 // This is because the browser treats navigation to an empty GURL as a
1665 // navigation to the home page. This is often a privileged page
1666 // (chrome://newtab/) which is exactly what we don't want.
1667 *url = GURL(kAboutBlankURL);
1668 RecordAction(base::UserMetricsAction("FilterURLTermiate_Invalid"));
1669 return;
1672 if (url->SchemeIs(kAboutScheme)) {
1673 // The renderer treats all URLs in the about: scheme as being about:blank.
1674 // Canonicalize about: URLs to about:blank.
1675 *url = GURL(kAboutBlankURL);
1676 RecordAction(base::UserMetricsAction("FilterURLTermiate_About"));
1679 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1680 // cannot swap processes or grant bindings.
1681 bool non_web_url_in_guest = rph->IsGuest() &&
1682 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1684 if (non_web_url_in_guest || !policy->CanRequestURL(rph->GetID(), *url)) {
1685 // If this renderer is not permitted to request this URL, we invalidate the
1686 // URL. This prevents us from storing the blocked URL and becoming confused
1687 // later.
1688 VLOG(1) << "Blocked URL " << url->spec();
1689 *url = GURL(kAboutBlankURL);
1690 RecordAction(base::UserMetricsAction("FilterURLTermiate_Blocked"));
1694 // static
1695 bool RenderProcessHostImpl::IsSuitableHost(
1696 RenderProcessHost* host,
1697 BrowserContext* browser_context,
1698 const GURL& site_url) {
1699 if (run_renderer_in_process())
1700 return true;
1702 if (host->GetBrowserContext() != browser_context)
1703 return false;
1705 // Do not allow sharing of guest hosts. This is to prevent bugs where guest
1706 // and non-guest storage gets mixed. In the future, we might consider enabling
1707 // the sharing of guests, in this case this check should be removed and
1708 // InSameStoragePartition should handle the possible sharing.
1709 if (host->IsGuest())
1710 return false;
1712 // Check whether the given host and the intended site_url will be using the
1713 // same StoragePartition, since a RenderProcessHost can only support a single
1714 // StoragePartition. This is relevant for packaged apps and isolated sites.
1715 StoragePartition* dest_partition =
1716 BrowserContext::GetStoragePartitionForSite(browser_context, site_url);
1717 if (!host->InSameStoragePartition(dest_partition))
1718 return false;
1720 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
1721 host->GetID()) !=
1722 WebUIControllerFactoryRegistry::GetInstance()->UseWebUIBindingsForURL(
1723 browser_context, site_url)) {
1724 return false;
1727 return GetContentClient()->browser()->IsSuitableHost(host, site_url);
1730 // static
1731 bool RenderProcessHost::run_renderer_in_process() {
1732 return g_run_renderer_in_process_;
1735 // static
1736 void RenderProcessHost::SetRunRendererInProcess(bool value) {
1737 g_run_renderer_in_process_ = value;
1739 CommandLine* command_line = CommandLine::ForCurrentProcess();
1740 if (value) {
1741 if (!command_line->HasSwitch(switches::kLang)) {
1742 // Modify the current process' command line to include the browser locale,
1743 // as the renderer expects this flag to be set.
1744 const std::string locale =
1745 GetContentClient()->browser()->GetApplicationLocale();
1746 command_line->AppendSwitchASCII(switches::kLang, locale);
1748 // TODO(piman): we should really send configuration through bools rather
1749 // than by parsing strings, i.e. sending an IPC rather than command line
1750 // args. crbug.com/314909
1751 AppendGpuCommandLineFlags(command_line);
1755 // static
1756 RenderProcessHost::iterator RenderProcessHost::AllHostsIterator() {
1757 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1758 return iterator(g_all_hosts.Pointer());
1761 // static
1762 RenderProcessHost* RenderProcessHost::FromID(int render_process_id) {
1763 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1764 return g_all_hosts.Get().Lookup(render_process_id);
1767 // static
1768 bool RenderProcessHost::ShouldTryToUseExistingProcessHost(
1769 BrowserContext* browser_context, const GURL& url) {
1770 // Experimental:
1771 // If --enable-strict-site-isolation or --site-per-process is enabled, do not
1772 // try to reuse renderer processes when over the limit. (We could allow pages
1773 // from the same site to share, if we knew what the given process was
1774 // dedicated to. Allowing no sharing is simpler for now.) This may cause
1775 // resource exhaustion issues if too many sites are open at once.
1776 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1777 if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) ||
1778 command_line.HasSwitch(switches::kSitePerProcess))
1779 return false;
1781 if (run_renderer_in_process())
1782 return true;
1784 // NOTE: Sometimes it's necessary to create more render processes than
1785 // GetMaxRendererProcessCount(), for instance when we want to create
1786 // a renderer process for a browser context that has no existing
1787 // renderers. This is OK in moderation, since the
1788 // GetMaxRendererProcessCount() is conservative.
1789 if (g_all_hosts.Get().size() >= GetMaxRendererProcessCount())
1790 return true;
1792 return GetContentClient()->browser()->
1793 ShouldTryToUseExistingProcessHost(browser_context, url);
1796 // static
1797 RenderProcessHost* RenderProcessHost::GetExistingProcessHost(
1798 BrowserContext* browser_context,
1799 const GURL& site_url) {
1800 // First figure out which existing renderers we can use.
1801 std::vector<RenderProcessHost*> suitable_renderers;
1802 suitable_renderers.reserve(g_all_hosts.Get().size());
1804 iterator iter(AllHostsIterator());
1805 while (!iter.IsAtEnd()) {
1806 if (RenderProcessHostImpl::IsSuitableHost(
1807 iter.GetCurrentValue(),
1808 browser_context, site_url))
1809 suitable_renderers.push_back(iter.GetCurrentValue());
1811 iter.Advance();
1814 // Now pick a random suitable renderer, if we have any.
1815 if (!suitable_renderers.empty()) {
1816 int suitable_count = static_cast<int>(suitable_renderers.size());
1817 int random_index = base::RandInt(0, suitable_count - 1);
1818 return suitable_renderers[random_index];
1821 return NULL;
1824 // static
1825 bool RenderProcessHost::ShouldUseProcessPerSite(
1826 BrowserContext* browser_context,
1827 const GURL& url) {
1828 // Returns true if we should use the process-per-site model. This will be
1829 // the case if the --process-per-site switch is specified, or in
1830 // process-per-site-instance for particular sites (e.g., WebUI).
1831 // Note that --single-process is handled in ShouldTryToUseExistingProcessHost.
1832 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1833 if (command_line.HasSwitch(switches::kProcessPerSite))
1834 return true;
1836 // We want to consolidate particular sites like WebUI even when we are using
1837 // the process-per-tab or process-per-site-instance models.
1838 // Note: DevTools pages have WebUI type but should not reuse the same host.
1839 if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
1840 browser_context, url) &&
1841 !url.SchemeIs(kChromeDevToolsScheme)) {
1842 return true;
1845 // Otherwise let the content client decide, defaulting to false.
1846 return GetContentClient()->browser()->ShouldUseProcessPerSite(browser_context,
1847 url);
1850 // static
1851 RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
1852 BrowserContext* browser_context,
1853 const GURL& url) {
1854 // Look up the map of site to process for the given browser_context.
1855 SiteProcessMap* map =
1856 GetSiteProcessMapForBrowserContext(browser_context);
1858 // See if we have an existing process with appropriate bindings for this site.
1859 // If not, the caller should create a new process and register it.
1860 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1861 .possibly_invalid_spec();
1862 RenderProcessHost* host = map->FindProcess(site);
1863 if (host && !IsSuitableHost(host, browser_context, url)) {
1864 // The registered process does not have an appropriate set of bindings for
1865 // the url. Remove it from the map so we can register a better one.
1866 RecordAction(
1867 base::UserMetricsAction("BindingsMismatch_GetProcessHostPerSite"));
1868 map->RemoveProcess(host);
1869 host = NULL;
1872 return host;
1875 void RenderProcessHostImpl::RegisterProcessHostForSite(
1876 BrowserContext* browser_context,
1877 RenderProcessHost* process,
1878 const GURL& url) {
1879 // Look up the map of site to process for the given browser_context.
1880 SiteProcessMap* map =
1881 GetSiteProcessMapForBrowserContext(browser_context);
1883 // Only register valid, non-empty sites. Empty or invalid sites will not
1884 // use process-per-site mode. We cannot check whether the process has
1885 // appropriate bindings here, because the bindings have not yet been granted.
1886 std::string site = SiteInstance::GetSiteForURL(browser_context, url)
1887 .possibly_invalid_spec();
1888 if (!site.empty())
1889 map->RegisterProcess(site, process);
1892 void RenderProcessHostImpl::ProcessDied(bool already_dead) {
1893 // Our child process has died. If we didn't expect it, it's a crash.
1894 // In any case, we need to let everyone know it's gone.
1895 // The OnChannelError notification can fire multiple times due to nested sync
1896 // calls to a renderer. If we don't have a valid channel here it means we
1897 // already handled the error.
1899 // It should not be possible for us to be called re-entrantly.
1900 DCHECK(!within_process_died_observer_);
1902 // It should not be possible for a process death notification to come in while
1903 // we are dying.
1904 DCHECK(!deleting_soon_);
1906 // child_process_launcher_ can be NULL in single process mode or if fast
1907 // termination happened.
1908 int exit_code = 0;
1909 base::TerminationStatus status =
1910 child_process_launcher_.get() ?
1911 child_process_launcher_->GetChildTerminationStatus(already_dead,
1912 &exit_code) :
1913 base::TERMINATION_STATUS_NORMAL_TERMINATION;
1915 RendererClosedDetails details(GetHandle(), status, exit_code);
1916 within_process_died_observer_ = true;
1917 NotificationService::current()->Notify(
1918 NOTIFICATION_RENDERER_PROCESS_CLOSED,
1919 Source<RenderProcessHost>(this),
1920 Details<RendererClosedDetails>(&details));
1921 FOR_EACH_OBSERVER(RenderProcessHostObserver,
1922 observers_,
1923 RenderProcessExited(this, GetHandle(), status, exit_code));
1924 within_process_died_observer_ = false;
1926 child_process_launcher_.reset();
1927 channel_.reset();
1928 gpu_message_filter_ = NULL;
1929 message_port_message_filter_ = NULL;
1930 geolocation_dispatcher_host_ = NULL;
1931 screen_orientation_dispatcher_host_ = NULL;
1933 IDMap<IPC::Listener>::iterator iter(&listeners_);
1934 while (!iter.IsAtEnd()) {
1935 iter.GetCurrentValue()->OnMessageReceived(
1936 ViewHostMsg_RenderProcessGone(iter.GetCurrentKey(),
1937 static_cast<int>(status),
1938 exit_code));
1939 iter.Advance();
1942 ClearTransportDIBCache();
1944 // It's possible that one of the calls out to the observers might have caused
1945 // this object to be no longer needed.
1946 if (delayed_cleanup_needed_)
1947 Cleanup();
1949 // This object is not deleted at this point and might be reused later.
1950 // TODO(darin): clean this up
1953 int RenderProcessHostImpl::GetActiveViewCount() {
1954 int num_active_views = 0;
1955 scoped_ptr<RenderWidgetHostIterator> widgets(
1956 RenderWidgetHost::GetRenderWidgetHosts());
1957 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
1958 // Count only RenderWidgetHosts in this process.
1959 if (widget->GetProcess()->GetID() == GetID())
1960 num_active_views++;
1962 return num_active_views;
1965 // Frame subscription API for this class is for accelerated composited path
1966 // only. These calls are redirected to GpuMessageFilter.
1967 void RenderProcessHostImpl::BeginFrameSubscription(
1968 int route_id,
1969 scoped_ptr<RenderWidgetHostViewFrameSubscriber> subscriber) {
1970 if (!gpu_message_filter_)
1971 return;
1972 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1973 &GpuMessageFilter::BeginFrameSubscription,
1974 gpu_message_filter_,
1975 route_id, base::Passed(&subscriber)));
1978 void RenderProcessHostImpl::EndFrameSubscription(int route_id) {
1979 if (!gpu_message_filter_)
1980 return;
1981 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
1982 &GpuMessageFilter::EndFrameSubscription,
1983 gpu_message_filter_,
1984 route_id));
1987 #if defined(ENABLE_WEBRTC)
1988 void RenderProcessHostImpl::WebRtcLogMessage(const std::string& message) {
1989 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1990 if (!webrtc_log_message_callback_.is_null())
1991 webrtc_log_message_callback_.Run(message);
1993 #endif
1995 scoped_refptr<ScreenOrientationDispatcherHost>
1996 RenderProcessHostImpl::screen_orientation_dispatcher_host() const {
1997 return make_scoped_refptr(screen_orientation_dispatcher_host_);
2000 void RenderProcessHostImpl::OnShutdownRequest() {
2001 // Don't shut down if there are active RenderViews, or if there are pending
2002 // RenderViews being swapped back in.
2003 // In single process mode, we never shutdown the renderer.
2004 int num_active_views = GetActiveViewCount();
2005 if (pending_views_ || num_active_views > 0 || run_renderer_in_process())
2006 return;
2008 // Notify any contents that might have swapped out renderers from this
2009 // process. They should not attempt to swap them back in.
2010 NotificationService::current()->Notify(
2011 NOTIFICATION_RENDERER_PROCESS_CLOSING,
2012 Source<RenderProcessHost>(this),
2013 NotificationService::NoDetails());
2015 Send(new ChildProcessMsg_Shutdown());
2018 void RenderProcessHostImpl::SuddenTerminationChanged(bool enabled) {
2019 SetSuddenTerminationAllowed(enabled);
2022 void RenderProcessHostImpl::OnDumpHandlesDone() {
2023 Cleanup();
2026 void RenderProcessHostImpl::SetBackgrounded(bool backgrounded) {
2027 // Note: we always set the backgrounded_ value. If the process is NULL
2028 // (and hence hasn't been created yet), we will set the process priority
2029 // later when we create the process.
2030 backgrounded_ = backgrounded;
2031 if (!child_process_launcher_.get() || child_process_launcher_->IsStarting())
2032 return;
2034 #if defined(OS_WIN)
2035 // The cbstext.dll loads as a global GetMessage hook in the browser process
2036 // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
2037 // background thread. If the UI thread invokes this API just when it is
2038 // intercepted the stack is messed up on return from the interceptor
2039 // which causes random crashes in the browser process. Our hack for now
2040 // is to not invoke the SetPriorityClass API if the dll is loaded.
2041 if (GetModuleHandle(L"cbstext.dll"))
2042 return;
2043 #endif // OS_WIN
2045 child_process_launcher_->SetProcessBackgrounded(backgrounded);
2048 void RenderProcessHostImpl::OnProcessLaunched() {
2049 // No point doing anything, since this object will be destructed soon. We
2050 // especially don't want to send the RENDERER_PROCESS_CREATED notification,
2051 // since some clients might expect a RENDERER_PROCESS_TERMINATED afterwards to
2052 // properly cleanup.
2053 if (deleting_soon_)
2054 return;
2056 if (child_process_launcher_) {
2057 if (!child_process_launcher_->GetHandle()) {
2058 OnChannelError();
2059 return;
2062 child_process_launcher_->SetProcessBackgrounded(backgrounded_);
2065 // NOTE: This needs to be before sending queued messages because
2066 // ExtensionService uses this notification to initialize the renderer process
2067 // with state that must be there before any JavaScript executes.
2069 // The queued messages contain such things as "navigate". If this notification
2070 // was after, we can end up executing JavaScript before the initialization
2071 // happens.
2072 NotificationService::current()->Notify(
2073 NOTIFICATION_RENDERER_PROCESS_CREATED,
2074 Source<RenderProcessHost>(this),
2075 NotificationService::NoDetails());
2077 while (!queued_messages_.empty()) {
2078 Send(queued_messages_.front());
2079 queued_messages_.pop();
2082 #if defined(ENABLE_WEBRTC)
2083 if (WebRTCInternals::GetInstance()->aec_dump_enabled())
2084 EnableAecDump(WebRTCInternals::GetInstance()->aec_dump_file_path());
2085 #endif
2088 scoped_refptr<AudioRendererHost>
2089 RenderProcessHostImpl::audio_renderer_host() const {
2090 return audio_renderer_host_;
2093 void RenderProcessHostImpl::OnUserMetricsRecordAction(
2094 const std::string& action) {
2095 RecordComputedAction(action);
2098 void RenderProcessHostImpl::OnSavedPageAsMHTML(int job_id, int64 data_size) {
2099 MHTMLGenerationManager::GetInstance()->MHTMLGenerated(job_id, data_size);
2102 void RenderProcessHostImpl::OnCompositorSurfaceBuffersSwappedNoHost(
2103 const ViewHostMsg_CompositorSurfaceBuffersSwapped_Params& params) {
2104 TRACE_EVENT0("renderer_host",
2105 "RenderWidgetHostImpl::OnCompositorSurfaceBuffersSwappedNoHost");
2106 if (!ui::LatencyInfo::Verify(params.latency_info,
2107 "ViewHostMsg_CompositorSurfaceBuffersSwapped"))
2108 return;
2109 AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
2110 ack_params.sync_point = 0;
2111 RenderWidgetHostImpl::AcknowledgeBufferPresent(params.route_id,
2112 params.gpu_process_host_id,
2113 ack_params);
2116 void RenderProcessHostImpl::OnGpuSwitching() {
2117 // We are updating all widgets including swapped out ones.
2118 scoped_ptr<RenderWidgetHostIterator> widgets(
2119 RenderWidgetHostImpl::GetAllRenderWidgetHosts());
2120 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
2121 if (!widget->IsRenderView())
2122 continue;
2124 // Skip widgets in other processes.
2125 if (widget->GetProcess()->GetID() != GetID())
2126 continue;
2128 RenderViewHost* rvh = RenderViewHost::From(widget);
2129 rvh->UpdateWebkitPreferences(rvh->GetWebkitPreferences());
2133 #if defined(ENABLE_WEBRTC)
2134 void RenderProcessHostImpl::SendAecDumpFileToRenderer(
2135 IPC::PlatformFileForTransit file_for_transit) {
2136 if (file_for_transit == IPC::InvalidPlatformFileForTransit())
2137 return;
2138 Send(new MediaStreamMsg_EnableAecDump(file_for_transit));
2141 void RenderProcessHostImpl::SendDisableAecDumpToRenderer() {
2142 Send(new MediaStreamMsg_DisableAecDump());
2144 #endif
2146 void RenderProcessHostImpl::IncrementWorkerRefCount() {
2147 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2148 ++worker_ref_count_;
2151 void RenderProcessHostImpl::DecrementWorkerRefCount() {
2152 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2153 DCHECK_GT(worker_ref_count_, 0);
2154 --worker_ref_count_;
2155 if (worker_ref_count_ == 0)
2156 Cleanup();
2159 #if defined(USE_MOJO)
2160 void RenderProcessHostImpl::CreateMojoChannel() {
2161 if (mojo_channel_init_.get())
2162 return;
2164 mojo::embedder::PlatformChannelPair channel_pair;
2165 mojo_channel_init_.reset(new MojoChannelInit);
2166 mojo_channel_init_->Init(
2167 PlatformFileFromScopedPlatformHandle(channel_pair.PassServerHandle()),
2168 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
2169 if (mojo_channel_init_->is_handle_valid()) {
2170 base::ProcessHandle process_handle = run_renderer_in_process() ?
2171 base::Process::Current().handle() :
2172 child_process_launcher_->GetHandle();
2173 base::PlatformFile client_file =
2174 PlatformFileFromScopedPlatformHandle(channel_pair.PassClientHandle());
2175 Send(new MojoMsg_ChannelCreated(
2176 IPC::GetFileHandleForProcess(client_file, process_handle, true)));
2179 #endif
2181 } // namespace content