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