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